Skip to content

Adds indent option #2165

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/compiler/commandLineParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,12 @@ module ts {
experimental: true
},
{
name: "indentSize",
type: { "2": IndentSize.Narrow, "4": IndentSize.Wide },
description: Diagnostics.Specify_indent_size,
error: Diagnostics.Argument_for_indent_size_must_be_2_or_4
},
{
name: "target",
shortName: "t",
type: { "es3": ScriptTarget.ES3, "es5": ScriptTarget.ES5, "es6": ScriptTarget.ES6 },
Expand All @@ -161,7 +167,7 @@ module ts {
description: Diagnostics.Watch_input_files,
}
];

export function parseCommandLine(commandLine: string[]): ParsedCommandLine {
var options: CompilerOptions = {};
var fileNames: string[] = [];
Expand Down
4 changes: 2 additions & 2 deletions src/compiler/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@ module ts {
}

var backslashOrDoubleQuote = /[\"\\]/g;
var escapedCharsRegExp = /[\0-\19\t\v\f\b\0\r\n\u2028\u2029\u0085]/g;
var escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
var escapedCharsMap: Map<string> = {
"\0": "\\0",
"\t": "\\t",
Expand All @@ -624,7 +624,7 @@ module ts {
};

/**
* Based heavily on the abstract 'Quote' operation from ECMA-262 (24.3.2.2),
* Based heavily on the abstract 'Quote'/ 'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
* but augmented for a few select characters.
* Note that this doesn't actually wrap the input in double quotes.
*/
Expand Down
2 changes: 2 additions & 0 deletions src/compiler/diagnosticInformationMap.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,8 @@ module ts {
File_0_must_have_extension_ts_or_d_ts: { code: 6054, category: DiagnosticCategory.Error, key: "File '{0}' must have extension '.ts' or '.d.ts'." },
Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: { code: 6055, category: DiagnosticCategory.Message, key: "Suppress noImplicitAny errors for indexing objects lacking index signatures." },
Do_not_emit_declarations_for_code_that_has_an_internal_annotation: { code: 6056, category: DiagnosticCategory.Message, key: "Do not emit declarations for code that has an '@internal' annotation." },
Specify_indent_size: { code: 6057, category: DiagnosticCategory.Message, key: "Specify indent size." },
Argument_for_indent_size_must_be_2_or_4: { code: 6058, category: DiagnosticCategory.Message, key: "Argument for indent size must be 2 or 4." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: DiagnosticCategory.Error, key: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: DiagnosticCategory.Error, key: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." },
Expand Down
8 changes: 8 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -1797,6 +1797,14 @@
"category": "Message",
"code": 6056
},
"Specify indent size.": {
"category": "Message",
"code": 6057
},
"Argument for indent size must be 2 or 4.": {
"category": "Message",
"code": 6058
},

"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
Expand Down
45 changes: 25 additions & 20 deletions src/compiler/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,19 @@ module ts {
referencePathsOutput: string;
}

var indentStrings: string[] = ["", " "];
export function getIndentString(level: number) {
if (indentStrings[level] === undefined) {
indentStrings[level] = getIndentString(level - 1) + indentStrings[1];
var indentStrings: string[][] = [["", " "], ["", " "]];
export function getIndentString(level: number, indentSize: IndentSize) {
if (indentStrings[indentSize][level] === undefined) {
indentStrings[indentSize][level] = getIndentString(level - 1, indentSize) + indentStrings[indentSize][1];
}
return indentStrings[level];
return indentStrings[indentSize][level];
}

function getIndentSize() {
return indentStrings[1].length;
function getIndentSize(indentSize: IndentSize): number {
if(indentSize === IndentSize.Narrow) {
return 2;
}
return 4;
}

export function shouldEmitToOwnFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean {
Expand All @@ -79,7 +82,7 @@ module ts {
return isExternalModule(sourceFile) || isDeclarationFile(sourceFile);
}

function createTextWriter(newLine: String): EmitTextWriter {
function createTextWriter(newLine: String, indentSize: IndentSize): EmitTextWriter {
var output = "";
var indent = 0;
var lineStart = true;
Expand All @@ -89,7 +92,7 @@ module ts {
function write(s: string) {
if (s && s.length) {
if (lineStart) {
output += getIndentString(indent);
output += getIndentString(indent, indentSize);
lineStart = false;
}
output += s;
Expand Down Expand Up @@ -140,7 +143,7 @@ module ts {
getIndent: () => indent,
getTextPos: () => output.length,
getLine: () => lineCount + 1,
getColumn: () => lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1,
getColumn: () => lineStart ? indent * getIndentSize(indentSize) + 1 : output.length - linePos + 1,
getText: () => output,
};
}
Expand Down Expand Up @@ -183,6 +186,7 @@ module ts {
if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk) {
var firstCommentLineAndCharacter = getLineAndCharacterOfPosition(currentSourceFile, comment.pos);
var lineCount = getLineStarts(currentSourceFile).length;
var indentSize = typeof currentSourceFile.indentSize === 'number' ? currentSourceFile.indentSize : IndentSize.Wide;
var firstCommentLineIndent: number;
for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) {
var nextLineStart = (currentLine + 1) === lineCount
Expand All @@ -192,11 +196,11 @@ module ts {
if (pos !== comment.pos) {
// If we are not emitting first line, we need to write the spaces to adjust the alignment
if (firstCommentLineIndent === undefined) {
firstCommentLineIndent = calculateIndent(getStartPositionOfLine(firstCommentLineAndCharacter.line, currentSourceFile), comment.pos);
firstCommentLineIndent = calculateIndent(getStartPositionOfLine(firstCommentLineAndCharacter.line, currentSourceFile), comment.pos, indentSize);
}

// These are number of spaces writer is going to write at current indent
var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(indentSize);

// Number of spaces we want to be writing
// eg: Assume writer indent
Expand All @@ -212,10 +216,10 @@ module ts {
// More right indented comment */ --4 = 8 - 4 + 11
// class c { }
// }
var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart);
var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart, currentSourceFile.indentSize);
if (spacesToEmit > 0) {
var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(indentSize);
var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize(indentSize), indentSize);

// Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
writer.rawWrite(indentSizeSpaceString);
Expand Down Expand Up @@ -259,12 +263,12 @@ module ts {
}
}

function calculateIndent(pos: number, end: number) {
function calculateIndent(pos: number, end: number, indentSize: IndentSize) {
var currentLineIndent = 0;
for (; pos < end && isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) {
if (currentSourceFile.text.charCodeAt(pos) === CharacterCodes.tab) {
// Tabs = TabSize = indent size and go to next tabStop
currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
currentLineIndent += getIndentSize(indentSize) - (currentLineIndent % getIndentSize(indentSize));
}
else {
// Single space
Expand Down Expand Up @@ -357,7 +361,7 @@ module ts {
var newLine = host.getNewLine();
var compilerOptions = host.getCompilerOptions();
var languageVersion = compilerOptions.target || ScriptTarget.ES3;
var indentSize = typeof compilerOptions.indentSize === 'number' ? compilerOptions.indentSize : IndentSize.Wide;
var write: (s: string) => void;
var writeLine: () => void;
var increaseIndent: () => void;
Expand Down Expand Up @@ -452,7 +456,7 @@ module ts {
}

function createAndSetNewTextWriterWithSymbolWriter(): EmitTextWriterWithSymbolWriter {
var writer = <EmitTextWriterWithSymbolWriter>createTextWriter(newLine);
var writer = <EmitTextWriterWithSymbolWriter>createTextWriter(newLine, indentSize);
writer.trackSymbol = trackSymbol;
writer.writeKeyword = writer.write;
writer.writeOperator = writer.write;
Expand Down Expand Up @@ -1528,6 +1532,7 @@ module ts {
export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile): EmitResult {
var compilerOptions = host.getCompilerOptions();
var languageVersion = compilerOptions.target || ScriptTarget.ES3;
var indentSize = typeof compilerOptions.indentSize === 'number' ? compilerOptions.indentSize : IndentSize.Wide;
var sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap ? [] : undefined;
var diagnostics: Diagnostic[] = [];
var newLine = host.getNewLine();
Expand Down Expand Up @@ -1565,7 +1570,7 @@ module ts {
};

function emitJavaScript(jsFilePath: string, root?: SourceFile) {
var writer = createTextWriter(newLine);
var writer = createTextWriter(newLine, indentSize);
var write = writer.write;
var writeTextOfNode = writer.writeTextOfNode;
var writeLine = writer.writeLine;
Expand Down
19 changes: 10 additions & 9 deletions src/compiler/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -760,11 +760,11 @@ module ts {
if (sourceFile.statements.length === 0) {
// If we don't have any statements in the current source file, then there's no real
// way to incrementally parse. So just do a full parse instead.
return parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setNodeParents*/ true)
return parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, sourceFile.indentSize, /*syntaxCursor*/ undefined, /*setNodeParents*/ true)
}

// Make sure we're not trying to incrementally update a source file more than once. Once
// we do an update the original source file is considered unusbale from that point onwards.
// we do an update the original source file is considered unusbale from that point onwards.
//
// This is because we do incremental parsing in-place. i.e. we take nodes from the old
// tree and give them new positions and parents. From that point on, trusting the old
Expand Down Expand Up @@ -817,14 +817,14 @@ module ts {
// Now that we've set up our internal incremental state just proceed and parse the
// source file in the normal fashion. When possible the parser will retrieve and
// reuse nodes from the old tree.
//
//
// Note: passing in 'true' for setNodeParents is very important. When incrementally
// parsing, we will be reusing nodes from the old tree, and placing it into new
// parents. If we don't set the parents now, we'll end up with an observably
// inconsistent tree. Setting the parents on the new tree should be very fast. We
// parents. If we don't set the parents now, we'll end up with an observably
// inconsistent tree. Setting the parents on the new tree should be very fast. We
// will immediately bail out of walking any subtrees when we can see that their parents
// are already correct.
var result = parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true)
var result = parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, sourceFile.indentSize, syntaxCursor, /* setParentNode */ true)

return result;
}
Expand Down Expand Up @@ -971,15 +971,15 @@ module ts {
}
}

export function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes = false): SourceFile {
export function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, indentSize: IndentSize, setParentNodes = false): SourceFile {
var start = new Date().getTime();
var result = parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes);
var result = parseSourceFile(fileName, sourceText, languageVersion, indentSize, /*syntaxCursor*/ undefined, setParentNodes);

parseTime += new Date().getTime() - start;
return result;
}

function parseSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, syntaxCursor: SyntaxCursor, setParentNodes = false): SourceFile {
function parseSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, indentSize: IndentSize, syntaxCursor: SyntaxCursor, setParentNodes = false): SourceFile {
var parsingContext: ParsingContext = 0;
var identifiers: Map<string> = {};
var identifierCount = 0;
Expand All @@ -995,6 +995,7 @@ module ts {
sourceFile.parseDiagnostics = [];
sourceFile.bindDiagnostics = [];
sourceFile.languageVersion = languageVersion;
sourceFile.indentSize = indentSize;
sourceFile.fileName = normalizePath(fileName);
sourceFile.flags = fileExtensionIs(sourceFile.fileName, ".d.ts") ? NodeFlags.DeclarationFile : 0;

Expand Down
15 changes: 10 additions & 5 deletions src/compiler/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ module ts {
// otherwise use toLowerCase as a canonical form.
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}

// returned by CScript sys environment
var unsupportedFileEncodingErrorCode = -2147024809;

function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile {
function getSourceFile(fileName: string, languageVersion: ScriptTarget, indentSize: IndentSize, onError?: (message: string) => void): SourceFile {
try {
var text = sys.readFile(fileName, options.charset);
}
Expand All @@ -30,7 +30,7 @@ module ts {
text = "";
}

return text !== undefined ? createSourceFile(fileName, text, languageVersion) : undefined;
return text !== undefined ? createSourceFile(fileName, text, languageVersion, indentSize) : undefined;
}

function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) {
Expand Down Expand Up @@ -177,10 +177,15 @@ module ts {
return { diagnostics: [], sourceMaps: undefined, emitSkipped: true };
}

// Create the emit resolver outside of the "emitTime" tracking code below. That way
// any cost associated with it (like type checking) are appropriate associated with
// the type-checking counter.
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile);

var start = new Date().getTime();

var emitResult = emitFiles(
getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile),
emitResolver,
getEmitHost(writeFileCallback),
sourceFile);

Expand Down Expand Up @@ -299,7 +304,7 @@ module ts {
}

// We haven't looked for this file, do so now and cache result
var file = filesByName[canonicalName] = host.getSourceFile(fileName, options.target, hostErrorMessage => {
var file = filesByName[canonicalName] = host.getSourceFile(fileName, options.target, options.indentSize, hostErrorMessage => {
if (refFile) {
diagnostics.add(createFileDiagnostic(refFile, refStart, refLength,
Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
Expand Down
4 changes: 2 additions & 2 deletions src/compiler/tsc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ module ts {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Compilation_complete_Watching_for_file_changes));
}

function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError ?: (message: string) => void) {
function getSourceFile(fileName: string, languageVersion: ScriptTarget, indentSize: IndentSize, onError ?: (message: string) => void) {
// Return existing SourceFile object if one is available
if (cachedProgram) {
var sourceFile = cachedProgram.getSourceFile(fileName);
Expand All @@ -268,7 +268,7 @@ module ts {
}
}
// Use default host function
var sourceFile = hostGetSourceFile(fileName, languageVersion, onError);
var sourceFile = hostGetSourceFile(fileName, languageVersion, indentSize, onError);
if (sourceFile && commandLine.options.watch) {
// Attach a file watcher
sourceFile.fileWatcher = sys.watchFile(sourceFile.fileName, () => sourceFileChanged(sourceFile));
Expand Down
Loading