code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function shouldRescanTemplateToken(container) { return container.kind === 13 /* TemplateMiddle */ || container.kind === 14 /* TemplateTail */; }
Scanner that is currently used for formatting
shouldRescanTemplateToken
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function startsWithSlashToken(t) { return t === 39 /* SlashToken */ || t === 61 /* SlashEqualsToken */; }
Scanner that is currently used for formatting
startsWithSlashToken
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function readTokenInfo(n) { ts.Debug.assert(scanner !== undefined); if (!isOnToken()) { // scanner is not on the token (either advance was not called yet or scanner is already past the end position) return { leadingTrivia: leadingTrivia, trailingTrivia: undefined, token: undefined }; } // normally scanner returns the smallest available token // check the kind of context node to determine if scanner should have more greedy behavior and consume more text. var expectedScanAction = shouldRescanGreaterThanToken(n) ? 1 /* RescanGreaterThanToken */ : shouldRescanSlashToken(n) ? 2 /* RescanSlashToken */ : shouldRescanTemplateToken(n) ? 3 /* RescanTemplateToken */ : shouldRescanJsxIdentifier(n) ? 4 /* RescanJsxIdentifier */ : 0 /* Scan */; if (lastTokenInfo && expectedScanAction === lastScanAction) { // readTokenInfo was called before with the same expected scan action. // No need to re-scan text, return existing 'lastTokenInfo' // it is ok to call fixTokenKind here since it does not affect // what portion of text is consumed. In opposize rescanning can change it, // i.e. for '>=' when originally scanner eats just one character // and rescanning forces it to consume more. return fixTokenKind(lastTokenInfo, n); } if (scanner.getStartPos() !== savedPos) { ts.Debug.assert(lastTokenInfo !== undefined); // readTokenInfo was called before but scan action differs - rescan text scanner.setTextPos(savedPos); scanner.scan(); } var currentToken = scanner.getToken(); if (expectedScanAction === 1 /* RescanGreaterThanToken */ && currentToken === 27 /* GreaterThanToken */) { currentToken = scanner.reScanGreaterToken(); ts.Debug.assert(n.kind === currentToken); lastScanAction = 1 /* RescanGreaterThanToken */; } else if (expectedScanAction === 2 /* RescanSlashToken */ && startsWithSlashToken(currentToken)) { currentToken = scanner.reScanSlashToken(); ts.Debug.assert(n.kind === currentToken); lastScanAction = 2 /* RescanSlashToken */; } else if (expectedScanAction === 3 /* RescanTemplateToken */ && currentToken === 16 /* CloseBraceToken */) { currentToken = scanner.reScanTemplateToken(); lastScanAction = 3 /* RescanTemplateToken */; } else if (expectedScanAction === 4 /* RescanJsxIdentifier */ && currentToken === 69 /* Identifier */) { currentToken = scanner.scanJsxIdentifier(); lastScanAction = 4 /* RescanJsxIdentifier */; } else { lastScanAction = 0 /* Scan */; } var token = { pos: scanner.getStartPos(), end: scanner.getTextPos(), kind: currentToken }; // consume trailing trivia if (trailingTrivia) { trailingTrivia = undefined; } while (scanner.getStartPos() < endPos) { currentToken = scanner.scan(); if (!ts.isTrivia(currentToken)) { break; } var trivia = { pos: scanner.getStartPos(), end: scanner.getTextPos(), kind: currentToken }; if (!trailingTrivia) { trailingTrivia = []; } trailingTrivia.push(trivia); if (currentToken === 4 /* NewLineTrivia */) { // move past new line scanner.scan(); break; } } lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; return fixTokenKind(lastTokenInfo, n); }
Scanner that is currently used for formatting
readTokenInfo
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isOnToken() { ts.Debug.assert(scanner !== undefined); var current = (lastTokenInfo && lastTokenInfo.token.kind) || scanner.getToken(); var startPos = (lastTokenInfo && lastTokenInfo.token.pos) || scanner.getStartPos(); return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current); }
Scanner that is currently used for formatting
isOnToken
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function FormattingContext(sourceFile, formattingRequestKind) { this.sourceFile = sourceFile; this.formattingRequestKind = formattingRequestKind; }
Scanner that is currently used for formatting
FormattingContext
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function Rule(Descriptor, Operation, Flag) { if (Flag === void 0) { Flag = 0 /* None */; } this.Descriptor = Descriptor; this.Operation = Operation; this.Flag = Flag; }
Scanner that is currently used for formatting
Rule
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function RuleDescriptor(LeftTokenRange, RightTokenRange) { this.LeftTokenRange = LeftTokenRange; this.RightTokenRange = RightTokenRange; }
Scanner that is currently used for formatting
RuleDescriptor
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function RuleOperation() { this.Context = null; this.Action = null; }
Scanner that is currently used for formatting
RuleOperation
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function RuleOperationContext() { var funcs = []; for (var _i = 0; _i < arguments.length; _i++) { funcs[_i - 0] = arguments[_i]; } this.customContextChecks = funcs; }
Scanner that is currently used for formatting
RuleOperationContext
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function Rules() { /// /// Common Rules /// // Leave comments alone this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1 /* Ignore */)); this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2 /* SingleLineCommentTrivia */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create1(1 /* Ignore */)); // Space after keyword but not before ; or : or ? this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54 /* ColonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 53 /* QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* ColonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 2 /* Space */)); this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsConditionalOperatorContext), 2 /* Space */)); this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); // Space after }. this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */)); // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 80 /* ElseKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 104 /* WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 20 /* CloseBracketToken */, 24 /* CommaToken */, 23 /* SemicolonToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); // No space for dot this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21 /* DotToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(21 /* DotToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); // No space before and after indexer this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* OpenBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8 /* Delete */)); // Place a space before open brace in a function declaration this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([69 /* Identifier */, 3 /* MultiLineCommentTrivia */, 73 /* ClassKeyword */]); this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Place a space before open brace in a control flow construct this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 79 /* DoKeyword */, 100 /* TryKeyword */, 85 /* FinallyKeyword */, 80 /* ElseKeyword */]); this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */)); // Insert new line after { and before } in multi-line contexts. this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); // For functions and control block place } on a new line [multi-line rule] this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(41 /* PlusPlusToken */, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42 /* MinusMinusToken */, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); // More unary operator special-casing. // DevDiv 181814: Be careful when removing leading whitespace // around unary operators. Examples: // 1 - -2 --X--> 1--2 // a + ++b --X--> a+++b this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(41 /* PlusPlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(42 /* MinusMinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24 /* CommaToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([102 /* VarKeyword */, 98 /* ThrowKeyword */, 92 /* NewKeyword */, 78 /* DeleteKeyword */, 94 /* ReturnKeyword */, 101 /* TypeOfKeyword */, 119 /* AwaitKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([108 /* LetKeyword */, 74 /* ConstKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2 /* Space */)); this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8 /* Delete */)); this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(87 /* FunctionKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionDeclContext), 8 /* Delete */)); this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103 /* VoidKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsVoidOpContext), 2 /* Space */)); this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94 /* ReturnKeyword */, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotForContext), 2 /* Space */)); // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100 /* TryKeyword */, 85 /* FinallyKeyword */]), 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); // get x() {} // set x(val) {} this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123 /* GetKeyword */, 129 /* SetKeyword */]), 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); // TypeScript-specific higher priority rules // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(121 /* ConstructorKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); // Use of module as a function call. e.g.: import m2 = module("m2"); this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125 /* ModuleKeyword */, 127 /* RequireKeyword */]), 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); // Add a space around certain TypeScript keywords this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115 /* AbstractKeyword */, 73 /* ClassKeyword */, 122 /* DeclareKeyword */, 77 /* DefaultKeyword */, 81 /* EnumKeyword */, 82 /* ExportKeyword */, 83 /* ExtendsKeyword */, 123 /* GetKeyword */, 106 /* ImplementsKeyword */, 89 /* ImportKeyword */, 107 /* InterfaceKeyword */, 125 /* ModuleKeyword */, 126 /* NamespaceKeyword */, 110 /* PrivateKeyword */, 112 /* PublicKeyword */, 111 /* ProtectedKeyword */, 129 /* SetKeyword */, 113 /* StaticKeyword */, 132 /* TypeKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([83 /* ExtendsKeyword */, 106 /* ImplementsKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9 /* StringLiteral */, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */)); // Lambda expressions this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34 /* EqualsGreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); // Optional parameters and let args this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22 /* DotDotDotToken */, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); // generics and type assertions this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(18 /* CloseParenToken */, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* LessThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.FromTokens([17 /* OpenParenToken */, 19 /* OpenBracketToken */, 27 /* GreaterThanToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); // Remove spaces in empty interface literals. e.g.: x: {} this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectTypeContext), 8 /* Delete */)); // decorators this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* AtToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([115 /* AbstractKeyword */, 69 /* Identifier */, 82 /* ExportKeyword */, 77 /* DefaultKeyword */, 73 /* ClassKeyword */, 113 /* StaticKeyword */, 112 /* PublicKeyword */, 110 /* PrivateKeyword */, 111 /* ProtectedKeyword */, 123 /* GetKeyword */, 129 /* SetKeyword */, 19 /* OpenBracketToken */, 37 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 37 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8 /* Delete */)); this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(37 /* AsteriskToken */, formatting.Shared.TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2 /* Space */)); this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(114 /* YieldKeyword */, 37 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8 /* Delete */)); this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([114 /* YieldKeyword */, 37 /* AsteriskToken */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2 /* Space */)); // Async-await this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsSameLineTokenContext), 2 /* Space */)); this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 87 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); // template string this.SpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); // These rules are higher in priority than user-configurable rules. this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, this.NoSpaceAfterQuestionMark, this.NoSpaceBeforeDot, this.NoSpaceAfterDot, this.NoSpaceAfterUnaryPrefixOperator, this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, this.SpaceAfterPostincrementWhenFollowedByAdd, this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, this.SpaceAfterPostdecrementWhenFollowedBySubtract, this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, this.NoSpaceAfterCloseBrace, this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, this.NoSpaceBetweenReturnAndSemicolon, this.SpaceAfterCertainKeywords, this.SpaceAfterLetConstInVariableDeclaration, this.NoSpaceBeforeOpenParenInFuncCall, this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, this.SpaceAfterVoidOperator, this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, this.SpaceBetweenTagAndTemplateString, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, // TypeScript-specific rules this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, this.SpaceAfterModuleName, this.SpaceAfterArrow, this.NoSpaceAfterEllipsis, this.NoSpaceAfterOptionalParameters, this.NoSpaceBetweenEmptyInterfaceBraceBrackets, this.NoSpaceBeforeOpenAngularBracket, this.NoSpaceBetweenCloseParenAndAngularBracket, this.NoSpaceAfterOpenAngularBracket, this.NoSpaceBeforeCloseAngularBracket, this.NoSpaceAfterCloseAngularBracket, this.NoSpaceAfterTypeAssertion, this.SpaceBeforeAt, this.NoSpaceAfterAt, this.SpaceAfterDecorator, ]; // These rules are lower in priority than user-configurable rules. this.LowPriorityCommonRules = [ this.NoSpaceBeforeSemicolon, this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, this.NoSpaceBeforeComma, this.NoSpaceBeforeOpenBracket, this.NoSpaceAfterCloseBracket, this.SpaceAfterSemicolon, this.NoSpaceBeforeOpenParenInFuncDecl, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; /// /// Rules controlled by user options /// // Insert space after comma delimiter this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); // Insert space before and after binary operators this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); // Insert space after keywords in control flow statements this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2 /* Space */)); this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8 /* Delete */)); // Open Brace braces after function //TypeScript: Function can have return types, which can be made of tons of different token kinds this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); // Open Brace braces after TypeScript module/class/interface this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); // Open Brace braces after control block this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); // Insert space after semicolon in for statement this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsForContext), 2 /* Space */)); this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsForContext), 8 /* Delete */)); // Insert space after opening and before closing nonempty parenthesis this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* OpenParenToken */, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); // Insert space after opening and before closing nonempty brackets this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenBracketToken */, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); // Insert space after function keyword for anonymous functions this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8 /* Delete */)); }
Scanner that is currently used for formatting
Rules
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function RulesMap() { this.map = []; this.mapRowLength = 0; }
Scanner that is currently used for formatting
RulesMap
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function RulesBucketConstructionState() { //// The Rules list contains all the inserted rules into a rulebucket in the following order: //// 1- Ignore rules with specific token combination //// 2- Ignore rules with any token combination //// 3- Context rules with specific token combination //// 4- Context rules with any token combination //// 5- Non-context rules with specific token combination //// 6- Non-context rules with any token combination //// //// The member rulesInsertionIndexBitmap is used to describe the number of rules //// in each sub-bucket (above) hence can be used to know the index of where to insert //// the next rule. It's a bitmap which contains 6 different sections each is given 5 bits. //// //// Example: //// In order to insert a rule to the end of sub-bucket (3), we get the index by adding //// the values in the bitmap segments 3rd, 2nd, and 1st. this.rulesInsertionIndexBitmap = 0; }
Scanner that is currently used for formatting
RulesBucketConstructionState
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function RulesBucket() { this.rules = []; }
Scanner that is currently used for formatting
RulesBucket
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function TokenRangeAccess(from, to, except) { this.tokens = []; for (var token = from; token <= to; token++) { if (ts.indexOf(except, token) < 0) { this.tokens.push(token); } } }
Scanner that is currently used for formatting
TokenRangeAccess
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function TokenValuesAccess(tks) { this.tokens = tks && tks.length ? tks : []; }
Scanner that is currently used for formatting
TokenValuesAccess
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function TokenSingleValueAccess(token) { this.token = token; }
Scanner that is currently used for formatting
TokenSingleValueAccess
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function TokenRange(tokenAccess) { this.tokenAccess = tokenAccess; }
Scanner that is currently used for formatting
TokenRange
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function RulesProvider() { this.globalRules = new formatting.Rules(); }
Scanner that is currently used for formatting
RulesProvider
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function formatOnEnter(position, sourceFile, rulesProvider, options) { var line = sourceFile.getLineAndCharacterOfPosition(position).line; if (line === 0) { return []; } // get the span for the previous\current line var span = { // get start position for the previous line pos: ts.getStartPositionOfLine(line - 1, sourceFile), // get end position for the current line (end value is exclusive so add 1 to the result) end: ts.getEndLinePosition(line, sourceFile) + 1 }; return formatSpan(span, sourceFile, options, rulesProvider, 2 /* FormatOnEnter */); }
Scanner that is currently used for formatting
formatOnEnter
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function formatOnSemicolon(position, sourceFile, rulesProvider, options) { return formatOutermostParent(position, 23 /* SemicolonToken */, sourceFile, options, rulesProvider, 3 /* FormatOnSemicolon */); }
Scanner that is currently used for formatting
formatOnSemicolon
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function formatOnClosingCurly(position, sourceFile, rulesProvider, options) { return formatOutermostParent(position, 16 /* CloseBraceToken */, sourceFile, options, rulesProvider, 4 /* FormatOnClosingCurlyBrace */); }
Scanner that is currently used for formatting
formatOnClosingCurly
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function formatDocument(sourceFile, rulesProvider, options) { var span = { pos: 0, end: sourceFile.text.length }; return formatSpan(span, sourceFile, options, rulesProvider, 0 /* FormatDocument */); }
Scanner that is currently used for formatting
formatDocument
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function formatSelection(start, end, sourceFile, rulesProvider, options) { // format from the beginning of the line var span = { pos: ts.getLineStartPositionForPosition(start, sourceFile), end: end }; return formatSpan(span, sourceFile, options, rulesProvider, 1 /* FormatSelection */); }
Scanner that is currently used for formatting
formatSelection
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function formatOutermostParent(position, expectedLastToken, sourceFile, options, rulesProvider, requestKind) { var parent = findOutermostParent(position, expectedLastToken, sourceFile); if (!parent) { return []; } var span = { pos: ts.getLineStartPositionForPosition(parent.getStart(sourceFile), sourceFile), end: parent.end }; return formatSpan(span, sourceFile, options, rulesProvider, requestKind); }
Scanner that is currently used for formatting
formatOutermostParent
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function findOutermostParent(position, expectedTokenKind, sourceFile) { var precedingToken = ts.findPrecedingToken(position, sourceFile); // when it is claimed that trigger character was typed at given position // we verify that there is a token with a matching kind whose end is equal to position (because the character was just typed). // If this condition is not hold - then trigger character was typed in some other context, // i.e.in comment and thus should not trigger autoformatting if (!precedingToken || precedingToken.kind !== expectedTokenKind || position !== precedingToken.getEnd()) { return undefined; } // walk up and search for the parent node that ends at the same position with precedingToken. // for cases like this // // let x = 1; // while (true) { // } // after typing close curly in while statement we want to reformat just the while statement. // However if we just walk upwards searching for the parent that has the same end value - // we'll end up with the whole source file. isListElement allows to stop on the list element level var current = precedingToken; while (current && current.parent && current.parent.end === precedingToken.end && !isListElement(current.parent, current)) { current = current.parent; } return current; }
Scanner that is currently used for formatting
findOutermostParent
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function find(n) { var candidate = ts.forEachChild(n, function (c) { return ts.startEndContainsRange(c.getStart(sourceFile), c.end, range) && c; }); if (candidate) { var result = find(candidate); if (result) { return result; } } return n; }
find node that fully contains given text range
find
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function prepareRangeContainsErrorFunction(errors, originalRange) { if (!errors.length) { return rangeHasNoErrors; } // pick only errors that fall in range var sorted = errors .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) .sort(function (e1, e2) { return e1.start - e2.start; }); if (!sorted.length) { return rangeHasNoErrors; } var index = 0; return function (r) { // in current implementation sequence of arguments [r1, r2...] is monotonically increasing. // 'index' tracks the index of the most recent error that was checked. while (true) { if (index >= sorted.length) { // all errors in the range were already checked -> no error in specified range return false; } var error = sorted[index]; if (r.end <= error.start) { // specified range ends before the error refered by 'index' - no error in range return false; } if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) { // specified range overlaps with error range return true; } index++; } }; function rangeHasNoErrors(r) { return false; } }
formatting is not applied to ranges that contain parse errors. This function will return a predicate that for a given text range will tell if there are any parse errors that overlap with the range.
prepareRangeContainsErrorFunction
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function rangeHasNoErrors(r) { return false; }
formatting is not applied to ranges that contain parse errors. This function will return a predicate that for a given text range will tell if there are any parse errors that overlap with the range.
rangeHasNoErrors
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getScanStartPosition(enclosingNode, originalRange, sourceFile) { var start = enclosingNode.getStart(sourceFile); if (start === originalRange.pos && enclosingNode.end === originalRange.end) { return start; } var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile); if (!precedingToken) { // no preceding token found - start from the beginning of enclosing node return enclosingNode.pos; } // preceding token ends after the start of original range (i.e when originaRange.pos falls in the middle of literal) // start from the beginning of enclosingNode to handle the entire 'originalRange' if (precedingToken.end >= originalRange.pos) { return enclosingNode.pos; } return precedingToken.end; }
Start of the original range might fall inside the comment - scanner will not yield appropriate results This function will look for token that is located before the start of target range and return its end as start position for the scanner.
getScanStartPosition
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) { var rangeContainsError = prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange); // formatting context is used by rules provider var formattingContext = new formatting.FormattingContext(sourceFile, requestKind); // find the smallest node that fully wraps the range and compute the initial indentation for the node var enclosingNode = findEnclosingNode(originalRange, sourceFile); var formattingScanner = formatting.getFormattingScanner(sourceFile, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end); var initialIndentation = formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options); var previousRangeHasError; var previousRange; var previousParent; var previousRangeStartLine; var lastIndentedLine; var indentationOnLastIndentedLine; var edits = []; formattingScanner.advance(); if (formattingScanner.isOnToken()) { var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line; var undecoratedStartLine = startLine; if (enclosingNode.decorators) { undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line; } var delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile); processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } formattingScanner.close(); return edits; // local functions /** Tries to compute the indentation for a list element. * If list element is not in range then * function will pick its actual indentation * so it can be pushed downstream as inherited indentation. * If list element is in the range - its indentation will be equal * to inherited indentation from its predecessors. */ function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos)) { if (inheritedIndentation !== -1 /* Unknown */) { return inheritedIndentation; } } else { var startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line; var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile); var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options); if (startLine !== parentStartLine || startPos === column) { return column; } } return -1 /* Unknown */; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; if (indentation === -1 /* Unknown */) { if (isSomeBlock(node.kind)) { // blocks should be indented in // - other blocks // - source file // - switch\default clauses if (isSomeBlock(parent.kind) || parent.kind === 248 /* SourceFile */ || parent.kind === 241 /* CaseClause */ || parent.kind === 242 /* DefaultClause */) { indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); } else { indentation = parentDynamicIndentation.getIndentation(); } } else { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { indentation = parentDynamicIndentation.getIndentation(); } else { indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); } } } var delta = formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent // - push children if either parent of node itself has non-zero delta indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta); } return { indentation: indentation, delta: delta }; } function getFirstNonDecoratorTokenOfNode(node) { if (node.modifiers && node.modifiers.length) { return node.modifiers[0].kind; } switch (node.kind) { case 214 /* ClassDeclaration */: return 73 /* ClassKeyword */; case 215 /* InterfaceDeclaration */: return 107 /* InterfaceKeyword */; case 213 /* FunctionDeclaration */: return 87 /* FunctionKeyword */; case 217 /* EnumDeclaration */: return 217 /* EnumDeclaration */; case 145 /* GetAccessor */: return 123 /* GetKeyword */; case 146 /* SetAccessor */: return 129 /* SetKeyword */; case 143 /* MethodDeclaration */: if (node.asteriskToken) { return 37 /* AsteriskToken */; } // fall-through case 141 /* PropertyDeclaration */: case 138 /* Parameter */: return node.name.kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { return { getIndentationForComment: function (kind, tokenIndentation) { switch (kind) { // preceding comment to the token that closes the indentation scope inherits the indentation from the scope // .. { // // comment // } case 16 /* CloseBraceToken */: case 20 /* CloseBracketToken */: case 18 /* CloseParenToken */: return indentation + delta; } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, getIndentationForToken: function (line, kind) { if (nodeStartLine !== line && node.decorators) { if (kind === getFirstNonDecoratorTokenOfNode(node)) { // if this token is the first token following the list of decorators, we do not need to indent return indentation; } } switch (kind) { // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent case 15 /* OpenBraceToken */: case 16 /* CloseBraceToken */: case 19 /* OpenBracketToken */: case 20 /* CloseBracketToken */: case 17 /* OpenParenToken */: case 18 /* CloseParenToken */: case 80 /* ElseKeyword */: case 104 /* WhileKeyword */: case 55 /* AtToken */: return indentation; default: // if token line equals to the line of containing node (this is a first token in the node) - use node indentation return nodeStartLine !== line ? indentation + delta : indentation; } }, getIndentation: function () { return indentation; }, getDelta: function () { return delta; }, recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent.kind, node.kind)) { if (lineAdded) { indentation += options.IndentSize; } else { indentation -= options.IndentSize; } if (formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */)) { delta = options.IndentSize; } else { delta = 0; } } } }; } function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) { return; } var nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta); // a useful observations when tracking context node // / // [a] // / | \ // [b] [c] [d] // node 'a' is a context node for nodes 'b', 'c', 'd' // except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a' // this rule can be applied recursively to child nodes of 'a'. // // context node is set to parent node value after processing every child node // context node is set to parent of the token after processing every token var childContextNode = contextNode; // if there are any tokens that logically belong to node and interleave child nodes // such tokens will be consumed in processChildNode for for the child that follows them ts.forEachChild(node, function (child) { processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListElement*/ false); }, function (nodes) { processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); }); // proceed any tokens in the node that are located after child nodes while (formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(node); if (tokenInfo.token.end > node.end) { break; } consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation); } function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem) { var childStartPos = child.getStart(sourceFile); var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; var undecoratedChildStartLine = childStartLine; if (child.decorators) { undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; } // if child is a list item - try to get its indentation var childIndentationAmount = -1 /* Unknown */; if (isListItem) { childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation); if (childIndentationAmount !== -1 /* Unknown */) { inheritedIndentation = childIndentationAmount; } } // child node is outside the target range - do not dive inside if (!ts.rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) { return inheritedIndentation; } if (child.getFullWidth() === 0) { return inheritedIndentation; } while (formattingScanner.isOnToken()) { // proceed any parent tokens that are located prior to child.getStart() var tokenInfo = formattingScanner.readTokenInfo(node); if (tokenInfo.token.end > childStartPos) { // stop when formatting scanner advances past the beginning of the child break; } consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); } if (!formattingScanner.isOnToken()) { return inheritedIndentation; } if (ts.isToken(child)) { // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules var tokenInfo = formattingScanner.readTokenInfo(child); ts.Debug.assert(tokenInfo.token.end === child.end); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); return inheritedIndentation; } var effectiveParentStartLine = child.kind === 139 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; return inheritedIndentation; } function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { var listStartToken = getOpenTokenForList(parent, nodes); var listEndToken = getCloseTokenForOpenToken(listStartToken); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; if (listStartToken !== 0 /* Unknown */) { // introduce a new indentation scope for lists (including list start and end tokens) while (formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.end > nodes.pos) { // stop when formatting scanner moves past the beginning of node list break; } else if (tokenInfo.token.kind === listStartToken) { // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation); } else { // consume any tokens that precede the list as child elements of 'node' using its indentation scope consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation); } } } var inheritedIndentation = -1 /* Unknown */; for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { var child = nodes_6[_i]; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListElement*/ true); } if (listEndToken !== 0 /* Unknown */) { if (formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(parent); // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation); } } } } function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation) { ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); var indentToken = false; if (currentTokenInfo.leadingTrivia) { processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation); } var lineAdded; var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token); var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos); if (isTokenInRange) { var rangeHasError = rangeContainsError(currentTokenInfo.token); // save previousRange since processRange will overwrite this value with current one var savePreviousRange = previousRange; lineAdded = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); if (rangeHasError) { // do not indent comments\token if token range overlaps with some error indentToken = false; } else { if (lineAdded !== undefined) { indentToken = lineAdded; } else { // indent token only if end line of previous range does not match start line of the token var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line; indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine; } } } if (currentTokenInfo.trailingTrivia) { processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation); } if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind) : -1 /* Unknown */; if (currentTokenInfo.leadingTrivia) { var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation); var indentNextTokenOrTrivia = true; for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { var triviaItem = _a[_i]; if (!ts.rangeContainsRange(originalRange, triviaItem)) { continue; } switch (triviaItem.kind) { case 3 /* MultiLineCommentTrivia */: indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); indentNextTokenOrTrivia = false; break; case 2 /* SingleLineCommentTrivia */: if (indentNextTokenOrTrivia) { insertIndentation(triviaItem.pos, commentIndentation, /*lineAdded*/ false); indentNextTokenOrTrivia = false; } break; case 4 /* NewLineTrivia */: indentNextTokenOrTrivia = true; break; } } } // indent token only if is it is in target range and does not overlap with any error ranges if (tokenIndentation !== -1 /* Unknown */) { insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded); lastIndentedLine = tokenStart.line; indentationOnLastIndentedLine = tokenIndentation; } } formattingScanner.advance(); childContextNode = parent; } } function processTrivia(trivia, parent, contextNode, dynamicIndentation) { for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) { var triviaItem = trivia_1[_i]; if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); } } } function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAdded; if (!rangeHasError && !previousRangeHasError) { if (!previousRange) { // trim whitespaces starting from the beginning of the span up to the current line var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); } else { lineAdded = processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation); } } previousRange = range; previousParent = parent; previousRangeStartLine = rangeStart.line; previousRangeHasError = rangeHasError; return lineAdded; } function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode); var rule = rulesProvider.getRulesMap().GetRule(formattingContext); var trimTrailingWhitespaces; var lineAdded; if (rule) { applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); if (rule.Operation.Action & (2 /* Space */ | 8 /* Delete */) && currentStartLine !== previousStartLine) { lineAdded = false; // Handle the case where the next line is moved to be the end of this line. // In this case we don't indent the next line in the next pass. if (currentParent.getStart(sourceFile) === currentItem.pos) { dynamicIndentation.recomputeIndentation(/*lineAdded*/ false); } } else if (rule.Operation.Action & 4 /* NewLine */ && currentStartLine === previousStartLine) { lineAdded = true; // Handle the case where token2 is moved to the new line. // In this case we indent token2 in the next pass but we set // sameLineIndent flag to notify the indenter that the indentation is within the line. if (currentParent.getStart(sourceFile) === currentItem.pos) { dynamicIndentation.recomputeIndentation(/*lineAdded*/ true); } } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespaces = (rule.Operation.Action & (4 /* NewLine */ | 2 /* Space */)) && rule.Flag !== 1 /* CanDeleteNewLines */; } else { trimTrailingWhitespaces = true; } if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) { // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem); } return lineAdded; } function insertIndentation(pos, indentation, lineAdded) { var indentationString = getIndentationString(indentation, options); if (lineAdded) { // new line is added before the token by the formatting rules // insert indentation string at the very beginning of the token recordReplace(pos, 0, indentationString); } else { var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos); if (indentation !== tokenStart.character) { var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile); recordReplace(startLinePosition, tokenStart.character, indentationString); } } } function indentMultilineComment(commentRange, indentation, firstLineIsIndented) { // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; var parts; if (startLine === endLine) { if (!firstLineIsIndented) { // treat as single line comment insertIndentation(commentRange.pos, indentation, /*lineAdded*/ false); } return; } else { parts = []; var startPos = commentRange.pos; for (var line = startLine; line < endLine; ++line) { var endOfLine = ts.getEndLinePosition(line, sourceFile); parts.push({ pos: startPos, end: endOfLine }); startPos = ts.getStartPositionOfLine(line + 1, sourceFile); } parts.push({ pos: startPos, end: commentRange.end }); } var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); if (indentation === nonWhitespaceColumnInFirstPart.column) { return; } var startIndex = 0; if (firstLineIsIndented) { startIndex = 1; startLine++; } // shift all parts on the delta size var delta = indentation - nonWhitespaceColumnInFirstPart.column; for (var i = startIndex, len = parts.length; i < len; ++i, ++startLine) { var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceCharacterAndColumn = i === 0 ? nonWhitespaceColumnInFirstPart : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); var newIndentation = nonWhitespaceCharacterAndColumn.column + delta; if (newIndentation > 0) { var indentationString = getIndentationString(newIndentation, options); recordReplace(startLinePos_1, nonWhitespaceCharacterAndColumn.character, indentationString); } else { recordDelete(startLinePos_1, nonWhitespaceCharacterAndColumn.character); } } } function trimTrailingWhitespacesForLines(line1, line2, range) { for (var line = line1; line < line2; ++line) { var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); var lineEndPosition = ts.getEndLinePosition(line, sourceFile); // do not trim whitespaces in comments or template expression if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { continue; } var pos = lineEndPosition; while (pos >= lineStartPosition && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { pos--; } if (pos !== lineEndPosition) { ts.Debug.assert(pos === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))); recordDelete(pos + 1, lineEndPosition - pos); } } } function newTextChange(start, len, newText) { return { span: ts.createTextSpan(start, len), newText: newText }; } function recordDelete(start, len) { if (len) { edits.push(newTextChange(start, len, "")); } } function recordReplace(start, len, newText) { if (len || newText) { edits.push(newTextChange(start, len, newText)); } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { var between; switch (rule.Operation.Action) { case 1 /* Ignore */: // no action required return; case 8 /* Delete */: if (previousRange.end !== currentRange.pos) { // delete characters starting from t1.end up to t2.pos exclusive recordDelete(previousRange.end, currentRange.pos - previousRange.end); } break; case 4 /* NewLine */: // exit early if we on different lines and rule cannot change number of newlines // if line1 and line2 are on subsequent lines then no edits are required - ok to exit // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines if (rule.Flag !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { return; } // edit should not be applied only if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); } break; case 2 /* Space */: // exit early if we on different lines and rule cannot change number of newlines if (rule.Flag !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { return; } var posDelta = currentRange.pos - previousRange.end; if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); } break; } } }
Start of the original range might fall inside the comment - scanner will not yield appropriate results This function will look for token that is located before the start of target range and return its end as start position for the scanner.
formatSpan
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos)) { if (inheritedIndentation !== -1 /* Unknown */) { return inheritedIndentation; } } else { var startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line; var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile); var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options); if (startLine !== parentStartLine || startPos === column) { return column; } } return -1 /* Unknown */; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
tryComputeIndentationForListItem
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; if (indentation === -1 /* Unknown */) { if (isSomeBlock(node.kind)) { // blocks should be indented in // - other blocks // - source file // - switch\default clauses if (isSomeBlock(parent.kind) || parent.kind === 248 /* SourceFile */ || parent.kind === 241 /* CaseClause */ || parent.kind === 242 /* DefaultClause */) { indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); } else { indentation = parentDynamicIndentation.getIndentation(); } } else { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { indentation = parentDynamicIndentation.getIndentation(); } else { indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); } } } var delta = formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent // - push children if either parent of node itself has non-zero delta indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta); } return { indentation: indentation, delta: delta }; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
computeIndentation
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getFirstNonDecoratorTokenOfNode(node) { if (node.modifiers && node.modifiers.length) { return node.modifiers[0].kind; } switch (node.kind) { case 214 /* ClassDeclaration */: return 73 /* ClassKeyword */; case 215 /* InterfaceDeclaration */: return 107 /* InterfaceKeyword */; case 213 /* FunctionDeclaration */: return 87 /* FunctionKeyword */; case 217 /* EnumDeclaration */: return 217 /* EnumDeclaration */; case 145 /* GetAccessor */: return 123 /* GetKeyword */; case 146 /* SetAccessor */: return 129 /* SetKeyword */; case 143 /* MethodDeclaration */: if (node.asteriskToken) { return 37 /* AsteriskToken */; } // fall-through case 141 /* PropertyDeclaration */: case 138 /* Parameter */: return node.name.kind; } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getFirstNonDecoratorTokenOfNode
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getDynamicIndentation(node, nodeStartLine, indentation, delta) { return { getIndentationForComment: function (kind, tokenIndentation) { switch (kind) { // preceding comment to the token that closes the indentation scope inherits the indentation from the scope // .. { // // comment // } case 16 /* CloseBraceToken */: case 20 /* CloseBracketToken */: case 18 /* CloseParenToken */: return indentation + delta; } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, getIndentationForToken: function (line, kind) { if (nodeStartLine !== line && node.decorators) { if (kind === getFirstNonDecoratorTokenOfNode(node)) { // if this token is the first token following the list of decorators, we do not need to indent return indentation; } } switch (kind) { // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent case 15 /* OpenBraceToken */: case 16 /* CloseBraceToken */: case 19 /* OpenBracketToken */: case 20 /* CloseBracketToken */: case 17 /* OpenParenToken */: case 18 /* CloseParenToken */: case 80 /* ElseKeyword */: case 104 /* WhileKeyword */: case 55 /* AtToken */: return indentation; default: // if token line equals to the line of containing node (this is a first token in the node) - use node indentation return nodeStartLine !== line ? indentation + delta : indentation; } }, getIndentation: function () { return indentation; }, getDelta: function () { return delta; }, recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent.kind, node.kind)) { if (lineAdded) { indentation += options.IndentSize; } else { indentation -= options.IndentSize; } if (formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */)) { delta = options.IndentSize; } else { delta = 0; } } } }; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getDynamicIndentation
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) { return; } var nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta); // a useful observations when tracking context node // / // [a] // / | \ // [b] [c] [d] // node 'a' is a context node for nodes 'b', 'c', 'd' // except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a' // this rule can be applied recursively to child nodes of 'a'. // // context node is set to parent node value after processing every child node // context node is set to parent of the token after processing every token var childContextNode = contextNode; // if there are any tokens that logically belong to node and interleave child nodes // such tokens will be consumed in processChildNode for for the child that follows them ts.forEachChild(node, function (child) { processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListElement*/ false); }, function (nodes) { processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); }); // proceed any tokens in the node that are located after child nodes while (formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(node); if (tokenInfo.token.end > node.end) { break; } consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation); } function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem) { var childStartPos = child.getStart(sourceFile); var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; var undecoratedChildStartLine = childStartLine; if (child.decorators) { undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; } // if child is a list item - try to get its indentation var childIndentationAmount = -1 /* Unknown */; if (isListItem) { childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation); if (childIndentationAmount !== -1 /* Unknown */) { inheritedIndentation = childIndentationAmount; } } // child node is outside the target range - do not dive inside if (!ts.rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) { return inheritedIndentation; } if (child.getFullWidth() === 0) { return inheritedIndentation; } while (formattingScanner.isOnToken()) { // proceed any parent tokens that are located prior to child.getStart() var tokenInfo = formattingScanner.readTokenInfo(node); if (tokenInfo.token.end > childStartPos) { // stop when formatting scanner advances past the beginning of the child break; } consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); } if (!formattingScanner.isOnToken()) { return inheritedIndentation; } if (ts.isToken(child)) { // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules var tokenInfo = formattingScanner.readTokenInfo(child); ts.Debug.assert(tokenInfo.token.end === child.end); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); return inheritedIndentation; } var effectiveParentStartLine = child.kind === 139 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; return inheritedIndentation; } function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { var listStartToken = getOpenTokenForList(parent, nodes); var listEndToken = getCloseTokenForOpenToken(listStartToken); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; if (listStartToken !== 0 /* Unknown */) { // introduce a new indentation scope for lists (including list start and end tokens) while (formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.end > nodes.pos) { // stop when formatting scanner moves past the beginning of node list break; } else if (tokenInfo.token.kind === listStartToken) { // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation); } else { // consume any tokens that precede the list as child elements of 'node' using its indentation scope consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation); } } } var inheritedIndentation = -1 /* Unknown */; for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { var child = nodes_6[_i]; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListElement*/ true); } if (listEndToken !== 0 /* Unknown */) { if (formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(parent); // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation); } } } } function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation) { ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); var indentToken = false; if (currentTokenInfo.leadingTrivia) { processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation); } var lineAdded; var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token); var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos); if (isTokenInRange) { var rangeHasError = rangeContainsError(currentTokenInfo.token); // save previousRange since processRange will overwrite this value with current one var savePreviousRange = previousRange; lineAdded = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); if (rangeHasError) { // do not indent comments\token if token range overlaps with some error indentToken = false; } else { if (lineAdded !== undefined) { indentToken = lineAdded; } else { // indent token only if end line of previous range does not match start line of the token var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line; indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine; } } } if (currentTokenInfo.trailingTrivia) { processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation); } if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind) : -1 /* Unknown */; if (currentTokenInfo.leadingTrivia) { var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation); var indentNextTokenOrTrivia = true; for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { var triviaItem = _a[_i]; if (!ts.rangeContainsRange(originalRange, triviaItem)) { continue; } switch (triviaItem.kind) { case 3 /* MultiLineCommentTrivia */: indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); indentNextTokenOrTrivia = false; break; case 2 /* SingleLineCommentTrivia */: if (indentNextTokenOrTrivia) { insertIndentation(triviaItem.pos, commentIndentation, /*lineAdded*/ false); indentNextTokenOrTrivia = false; } break; case 4 /* NewLineTrivia */: indentNextTokenOrTrivia = true; break; } } } // indent token only if is it is in target range and does not overlap with any error ranges if (tokenIndentation !== -1 /* Unknown */) { insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded); lastIndentedLine = tokenStart.line; indentationOnLastIndentedLine = tokenIndentation; } } formattingScanner.advance(); childContextNode = parent; } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
processNode
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem) { var childStartPos = child.getStart(sourceFile); var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; var undecoratedChildStartLine = childStartLine; if (child.decorators) { undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; } // if child is a list item - try to get its indentation var childIndentationAmount = -1 /* Unknown */; if (isListItem) { childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation); if (childIndentationAmount !== -1 /* Unknown */) { inheritedIndentation = childIndentationAmount; } } // child node is outside the target range - do not dive inside if (!ts.rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) { return inheritedIndentation; } if (child.getFullWidth() === 0) { return inheritedIndentation; } while (formattingScanner.isOnToken()) { // proceed any parent tokens that are located prior to child.getStart() var tokenInfo = formattingScanner.readTokenInfo(node); if (tokenInfo.token.end > childStartPos) { // stop when formatting scanner advances past the beginning of the child break; } consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); } if (!formattingScanner.isOnToken()) { return inheritedIndentation; } if (ts.isToken(child)) { // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules var tokenInfo = formattingScanner.readTokenInfo(child); ts.Debug.assert(tokenInfo.token.end === child.end); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); return inheritedIndentation; } var effectiveParentStartLine = child.kind === 139 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; return inheritedIndentation; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
processChildNode
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { var listStartToken = getOpenTokenForList(parent, nodes); var listEndToken = getCloseTokenForOpenToken(listStartToken); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; if (listStartToken !== 0 /* Unknown */) { // introduce a new indentation scope for lists (including list start and end tokens) while (formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.end > nodes.pos) { // stop when formatting scanner moves past the beginning of node list break; } else if (tokenInfo.token.kind === listStartToken) { // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation); } else { // consume any tokens that precede the list as child elements of 'node' using its indentation scope consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation); } } } var inheritedIndentation = -1 /* Unknown */; for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { var child = nodes_6[_i]; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListElement*/ true); } if (listEndToken !== 0 /* Unknown */) { if (formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(parent); // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation); } } } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
processChildNodes
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation) { ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); var indentToken = false; if (currentTokenInfo.leadingTrivia) { processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation); } var lineAdded; var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token); var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos); if (isTokenInRange) { var rangeHasError = rangeContainsError(currentTokenInfo.token); // save previousRange since processRange will overwrite this value with current one var savePreviousRange = previousRange; lineAdded = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); if (rangeHasError) { // do not indent comments\token if token range overlaps with some error indentToken = false; } else { if (lineAdded !== undefined) { indentToken = lineAdded; } else { // indent token only if end line of previous range does not match start line of the token var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line; indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine; } } } if (currentTokenInfo.trailingTrivia) { processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation); } if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind) : -1 /* Unknown */; if (currentTokenInfo.leadingTrivia) { var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation); var indentNextTokenOrTrivia = true; for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { var triviaItem = _a[_i]; if (!ts.rangeContainsRange(originalRange, triviaItem)) { continue; } switch (triviaItem.kind) { case 3 /* MultiLineCommentTrivia */: indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); indentNextTokenOrTrivia = false; break; case 2 /* SingleLineCommentTrivia */: if (indentNextTokenOrTrivia) { insertIndentation(triviaItem.pos, commentIndentation, /*lineAdded*/ false); indentNextTokenOrTrivia = false; } break; case 4 /* NewLineTrivia */: indentNextTokenOrTrivia = true; break; } } } // indent token only if is it is in target range and does not overlap with any error ranges if (tokenIndentation !== -1 /* Unknown */) { insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded); lastIndentedLine = tokenStart.line; indentationOnLastIndentedLine = tokenIndentation; } } formattingScanner.advance(); childContextNode = parent; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
consumeTokenAndAdvanceScanner
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function processTrivia(trivia, parent, contextNode, dynamicIndentation) { for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) { var triviaItem = trivia_1[_i]; if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); } } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
processTrivia
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAdded; if (!rangeHasError && !previousRangeHasError) { if (!previousRange) { // trim whitespaces starting from the beginning of the span up to the current line var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); } else { lineAdded = processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation); } } previousRange = range; previousParent = parent; previousRangeStartLine = rangeStart.line; previousRangeHasError = rangeHasError; return lineAdded; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
processRange
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode); var rule = rulesProvider.getRulesMap().GetRule(formattingContext); var trimTrailingWhitespaces; var lineAdded; if (rule) { applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); if (rule.Operation.Action & (2 /* Space */ | 8 /* Delete */) && currentStartLine !== previousStartLine) { lineAdded = false; // Handle the case where the next line is moved to be the end of this line. // In this case we don't indent the next line in the next pass. if (currentParent.getStart(sourceFile) === currentItem.pos) { dynamicIndentation.recomputeIndentation(/*lineAdded*/ false); } } else if (rule.Operation.Action & 4 /* NewLine */ && currentStartLine === previousStartLine) { lineAdded = true; // Handle the case where token2 is moved to the new line. // In this case we indent token2 in the next pass but we set // sameLineIndent flag to notify the indenter that the indentation is within the line. if (currentParent.getStart(sourceFile) === currentItem.pos) { dynamicIndentation.recomputeIndentation(/*lineAdded*/ true); } } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespaces = (rule.Operation.Action & (4 /* NewLine */ | 2 /* Space */)) && rule.Flag !== 1 /* CanDeleteNewLines */; } else { trimTrailingWhitespaces = true; } if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) { // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem); } return lineAdded; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
processPair
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function insertIndentation(pos, indentation, lineAdded) { var indentationString = getIndentationString(indentation, options); if (lineAdded) { // new line is added before the token by the formatting rules // insert indentation string at the very beginning of the token recordReplace(pos, 0, indentationString); } else { var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos); if (indentation !== tokenStart.character) { var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile); recordReplace(startLinePosition, tokenStart.character, indentationString); } } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
insertIndentation
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function indentMultilineComment(commentRange, indentation, firstLineIsIndented) { // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; var parts; if (startLine === endLine) { if (!firstLineIsIndented) { // treat as single line comment insertIndentation(commentRange.pos, indentation, /*lineAdded*/ false); } return; } else { parts = []; var startPos = commentRange.pos; for (var line = startLine; line < endLine; ++line) { var endOfLine = ts.getEndLinePosition(line, sourceFile); parts.push({ pos: startPos, end: endOfLine }); startPos = ts.getStartPositionOfLine(line + 1, sourceFile); } parts.push({ pos: startPos, end: commentRange.end }); } var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); if (indentation === nonWhitespaceColumnInFirstPart.column) { return; } var startIndex = 0; if (firstLineIsIndented) { startIndex = 1; startLine++; } // shift all parts on the delta size var delta = indentation - nonWhitespaceColumnInFirstPart.column; for (var i = startIndex, len = parts.length; i < len; ++i, ++startLine) { var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceCharacterAndColumn = i === 0 ? nonWhitespaceColumnInFirstPart : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); var newIndentation = nonWhitespaceCharacterAndColumn.column + delta; if (newIndentation > 0) { var indentationString = getIndentationString(newIndentation, options); recordReplace(startLinePos_1, nonWhitespaceCharacterAndColumn.character, indentationString); } else { recordDelete(startLinePos_1, nonWhitespaceCharacterAndColumn.character); } } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
indentMultilineComment
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function trimTrailingWhitespacesForLines(line1, line2, range) { for (var line = line1; line < line2; ++line) { var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); var lineEndPosition = ts.getEndLinePosition(line, sourceFile); // do not trim whitespaces in comments or template expression if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { continue; } var pos = lineEndPosition; while (pos >= lineStartPosition && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { pos--; } if (pos !== lineEndPosition) { ts.Debug.assert(pos === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))); recordDelete(pos + 1, lineEndPosition - pos); } } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
trimTrailingWhitespacesForLines
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function newTextChange(start, len, newText) { return { span: ts.createTextSpan(start, len), newText: newText }; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
newTextChange
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function recordDelete(start, len) { if (len) { edits.push(newTextChange(start, len, "")); } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
recordDelete
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function recordReplace(start, len, newText) { if (len || newText) { edits.push(newTextChange(start, len, newText)); } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
recordReplace
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { var between; switch (rule.Operation.Action) { case 1 /* Ignore */: // no action required return; case 8 /* Delete */: if (previousRange.end !== currentRange.pos) { // delete characters starting from t1.end up to t2.pos exclusive recordDelete(previousRange.end, currentRange.pos - previousRange.end); } break; case 4 /* NewLine */: // exit early if we on different lines and rule cannot change number of newlines // if line1 and line2 are on subsequent lines then no edits are required - ok to exit // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines if (rule.Flag !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { return; } // edit should not be applied only if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); } break; case 2 /* Space */: // exit early if we on different lines and rule cannot change number of newlines if (rule.Flag !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { return; } var posDelta = currentRange.pos - previousRange.end; if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); } break; } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
applyRuleEdits
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isSomeBlock(kind) { switch (kind) { case 192 /* Block */: case 219 /* ModuleBlock */: return true; } return false; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
isSomeBlock
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getOpenTokenForList(node, list) { switch (node.kind) { case 144 /* Constructor */: case 213 /* FunctionDeclaration */: case 173 /* FunctionExpression */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 174 /* ArrowFunction */: if (node.typeParameters === list) { return 25 /* LessThanToken */; } else if (node.parameters === list) { return 17 /* OpenParenToken */; } break; case 168 /* CallExpression */: case 169 /* NewExpression */: if (node.typeArguments === list) { return 25 /* LessThanToken */; } else if (node.arguments === list) { return 17 /* OpenParenToken */; } break; case 151 /* TypeReference */: if (node.typeArguments === list) { return 25 /* LessThanToken */; } } return 0 /* Unknown */; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getOpenTokenForList
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getCloseTokenForOpenToken(kind) { switch (kind) { case 17 /* OpenParenToken */: return 18 /* CloseParenToken */; case 25 /* LessThanToken */: return 27 /* GreaterThanToken */; } return 0 /* Unknown */; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getCloseTokenForOpenToken
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getIndentationString(indentation, options) { // reset interned strings if FormatCodeOptions were changed var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); if (resetInternedStrings) { internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize }; internedTabsIndentation = internedSpacesIndentation = undefined; } if (!options.ConvertTabsToSpaces) { var tabs = Math.floor(indentation / options.TabSize); var spaces = indentation - tabs * options.TabSize; var tabString; if (!internedTabsIndentation) { internedTabsIndentation = []; } if (internedTabsIndentation[tabs] === undefined) { internedTabsIndentation[tabs] = tabString = repeat('\t', tabs); } else { tabString = internedTabsIndentation[tabs]; } return spaces ? tabString + repeat(" ", spaces) : tabString; } else { var spacesString; var quotient = Math.floor(indentation / options.IndentSize); var remainder = indentation % options.IndentSize; if (!internedSpacesIndentation) { internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { spacesString = repeat(" ", options.IndentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { spacesString = internedSpacesIndentation[quotient]; } return remainder ? spacesString + repeat(" ", remainder) : spacesString; } function repeat(value, count) { var s = ""; for (var i = 0; i < count; ++i) { s += value; } return s; } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getIndentationString
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function repeat(value, count) { var s = ""; for (var i = 0; i < count; ++i) { s += value; } return s; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
repeat
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getIndentation(position, sourceFile, options) { if (position > sourceFile.text.length) { return 0; // past EOF } // no indentation when the indent style is set to none, // so we can return fast if (options.IndentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); if (!precedingToken) { return 0; } // no indentation in string \regex\template literals var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind); if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) { return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; // indentation is first non-whitespace character in a previous line // for block indentation, we should look for a line which contains something that's not // whitespace. if (options.IndentStyle === ts.IndentStyle.Block) { // move backwards until we find a line with a non-whitespace character, // then find the first non-whitespace character for that line. var current_1 = position; while (current_1 > 0) { var char = sourceFile.text.charCodeAt(current_1); if (!ts.isWhiteSpace(char) && !ts.isLineBreak(char)) { break; } current_1--; } var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); } if (precedingToken.kind === 24 /* CommaToken */ && precedingToken.parent.kind !== 181 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation; } } // try to find node that can contribute to indentation and includes 'position' starting from 'precedingToken' // if such node is found - compute initial indentation for 'position' inside this node var previous; var current = precedingToken; var currentStart; var indentationDelta; while (current) { if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current.kind, previous ? previous.kind : 0 /* Unknown */)) { currentStart = getStartLineAndCharacterForNode(current, sourceFile); if (nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile)) { indentationDelta = 0; } else { indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; } break; } // check if current node is a list item - if yes, take indentation from it var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + options.IndentSize; } previous = current; current = current.parent; } if (!current) { // no parent was found - return 0 to be indented on the level of SourceFile return 0; } return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options); }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getIndentation
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options); }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getIndentationForNode
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; // walk upwards and collect indentations for pairs of parent-child nodes // indentation is not added if parent and child nodes start on the same line or if parent is IfStatement and child starts on the same line with 'else clause' while (parent) { var useActualIndentation = true; if (ignoreActualIndentationRange) { var start = current.getStart(sourceFile); useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end; } if (useActualIndentation) { // check if current node is a list item - if yes, take indentation from it var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } } parentStart = getParentStart(parent, current, sourceFile); var parentAndChildShareLine = parentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { // try to fetch actual indentation for current node from source text var actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line if (shouldIndentChildNode(parent.kind, current.kind) && !parentAndChildShareLine) { indentationDelta += options.IndentSize; } current = parent; currentStart = parentStart; parent = current.parent; } return indentationDelta; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getIndentationForNodeWorker
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getParentStart(parent, child, sourceFile) { var containingList = getContainingList(child, sourceFile); if (containingList) { return sourceFile.getLineAndCharacterOfPosition(containingList.pos); } return sourceFile.getLineAndCharacterOfPosition(parent.getStart(sourceFile)); }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getParentStart
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) { var nextToken = ts.findNextToken(precedingToken, current); if (!nextToken) { return false; } if (nextToken.kind === 15 /* OpenBraceToken */) { // open braces are always indented at the parent level return true; } else if (nextToken.kind === 16 /* CloseBraceToken */) { // close braces are indented at the parent level if they are located on the same line with cursor // this means that if new line will be added at $ position, this case will be indented // class A { // $ // } /// and this one - not // class A { // $} var nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line; return lineAtPosition === nextTokenStartLine; } return false; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
nextTokenIsCurlyBraceOnSameLineAsCursor
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getStartLineAndCharacterForNode(n, sourceFile) { return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getStartLineAndCharacterForNode
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { if (parent.kind === 196 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 80 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; return elseKeywordStartLine === childStartLine; } return false; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
childStartsOnTheSameLineWithElseInIfStatement
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { case 151 /* TypeReference */: if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd())) { return node.parent.typeArguments; } break; case 165 /* ObjectLiteralExpression */: return node.parent.properties; case 164 /* ArrayLiteralExpression */: return node.parent.elements; case 213 /* FunctionDeclaration */: case 173 /* FunctionExpression */: case 174 /* ArrowFunction */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 147 /* CallSignature */: case 148 /* ConstructSignature */: { var start = node.getStart(sourceFile); if (node.parent.typeParameters && ts.rangeContainsStartEnd(node.parent.typeParameters, start, node.getEnd())) { return node.parent.typeParameters; } if (ts.rangeContainsStartEnd(node.parent.parameters, start, node.getEnd())) { return node.parent.parameters; } break; } case 169 /* NewExpression */: case 168 /* CallExpression */: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { return node.parent.typeArguments; } if (node.parent.arguments && ts.rangeContainsStartEnd(node.parent.arguments, start, node.getEnd())) { return node.parent.arguments; } break; } } } return undefined; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getContainingList
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getActualIndentationForListItem(node, sourceFile, options) { var containingList = getContainingList(node, sourceFile); return containingList ? getActualIndentationFromList(containingList) : -1 /* Unknown */; function getActualIndentationFromList(list) { var index = ts.indexOf(list, node); return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1 /* Unknown */; } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getActualIndentationForListItem
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getActualIndentationFromList(list) { var index = ts.indexOf(list, node); return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1 /* Unknown */; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getActualIndentationFromList
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { // actual indentation should not be used when: // - node is close parenthesis - this is the end of the expression if (node.kind === 18 /* CloseParenToken */) { return -1 /* Unknown */; } if (node.parent && (node.parent.kind === 168 /* CallExpression */ || node.parent.kind === 169 /* NewExpression */) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { return -1 /* Unknown */; } var fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end); var startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) { return -1 /* Unknown */; } return findColumnForFirstNonWhitespaceCharacterInLine(fullCallOrNewExpressionEnd, sourceFile, options); } return -1 /* Unknown */; function getStartingExpression(node) { while (true) { switch (node.kind) { case 168 /* CallExpression */: case 169 /* NewExpression */: case 166 /* PropertyAccessExpression */: case 167 /* ElementAccessExpression */: node = node.expression; break; default: return node; } } } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getLineIndentationWhenExpressionIsInMultiLine
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getStartingExpression(node) { while (true) { switch (node.kind) { case 168 /* CallExpression */: case 169 /* NewExpression */: case 166 /* PropertyAccessExpression */: case 167 /* ElementAccessExpression */: node = node.expression; break; default: return node; } } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
getStartingExpression
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function deriveActualIndentationFromList(list, index, sourceFile, options) { ts.Debug.assert(index >= 0 && index < list.length); var node = list[index]; // walk toward the start of the list starting from current node and check if the line is the same for all items. // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); for (var i = index - 1; i >= 0; --i) { if (list[i].kind === 24 /* CommaToken */) { continue; } // skip list items that ends on the same line with the current list element var prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line; if (prevEndLine !== lineAndCharacter.line) { return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options); } lineAndCharacter = getStartLineAndCharacterForNode(list[i], sourceFile); } return -1 /* Unknown */; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
deriveActualIndentationFromList
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options) { var lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0); return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options); }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
findColumnForFirstNonWhitespaceCharacterInLine
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function findFirstNonWhitespaceColumn(startPos, endPos, sourceFile, options) { return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
findFirstNonWhitespaceColumn
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function nodeContentIsAlwaysIndented(kind) { switch (kind) { case 195 /* ExpressionStatement */: case 214 /* ClassDeclaration */: case 186 /* ClassExpression */: case 215 /* InterfaceDeclaration */: case 217 /* EnumDeclaration */: case 216 /* TypeAliasDeclaration */: case 164 /* ArrayLiteralExpression */: case 192 /* Block */: case 219 /* ModuleBlock */: case 165 /* ObjectLiteralExpression */: case 155 /* TypeLiteral */: case 157 /* TupleType */: case 220 /* CaseBlock */: case 242 /* DefaultClause */: case 241 /* CaseClause */: case 172 /* ParenthesizedExpression */: case 166 /* PropertyAccessExpression */: case 168 /* CallExpression */: case 169 /* NewExpression */: case 193 /* VariableStatement */: case 211 /* VariableDeclaration */: case 227 /* ExportAssignment */: case 204 /* ReturnStatement */: case 182 /* ConditionalExpression */: case 162 /* ArrayBindingPattern */: case 161 /* ObjectBindingPattern */: case 233 /* JsxElement */: case 234 /* JsxSelfClosingElement */: case 142 /* MethodSignature */: case 147 /* CallSignature */: case 148 /* ConstructSignature */: case 138 /* Parameter */: case 152 /* FunctionType */: case 153 /* ConstructorType */: case 160 /* ParenthesizedType */: case 170 /* TaggedTemplateExpression */: case 178 /* AwaitExpression */: return true; } return false; }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
nodeContentIsAlwaysIndented
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function shouldIndentChildNode(parent, child) { if (nodeContentIsAlwaysIndented(parent)) { return true; } switch (parent) { case 197 /* DoStatement */: case 198 /* WhileStatement */: case 200 /* ForInStatement */: case 201 /* ForOfStatement */: case 199 /* ForStatement */: case 196 /* IfStatement */: case 213 /* FunctionDeclaration */: case 173 /* FunctionExpression */: case 143 /* MethodDeclaration */: case 174 /* ArrowFunction */: case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: return child !== 192 /* Block */; default: return false; } }
Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
shouldIndentChildNode
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function StringScriptSnapshot(text) { this.text = text; }
The version of the language service API
StringScriptSnapshot
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function fromString(text) { return new StringScriptSnapshot(text); }
The version of the language service API
fromString
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function createNode(kind, pos, end, flags, parent) { var node = new NodeObject(kind, pos, end); node.flags = flags; node.parent = parent; return node; }
The version of the language service API
createNode
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function NodeObject(kind, pos, end) { this.kind = kind; this.pos = pos; this.end = end; this.flags = 0 /* None */; this.parent = undefined; }
The version of the language service API
NodeObject
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
processNode = function (node) { if (pos < node.pos) { pos = _this.addSyntheticNodes(children, pos, node.pos); } children.push(node); pos = node.end; }
The version of the language service API
processNode
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
processNodes = function (nodes) { if (pos < nodes.pos) { pos = _this.addSyntheticNodes(children, pos, nodes.pos); } children.push(_this.createSyntaxList(nodes)); pos = nodes.end; }
The version of the language service API
processNodes
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function SymbolObject(flags, name) { this.flags = flags; this.name = name; }
The version of the language service API
SymbolObject
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { var documentationComment = []; var docComments = getJsDocCommentsSeparatedByNewLines(); ts.forEach(docComments, function (docComment) { if (documentationComment.length) { documentationComment.push(ts.lineBreakPart()); } documentationComment.push(docComment); }); return documentationComment; function getJsDocCommentsSeparatedByNewLines() { var paramTag = "@param"; var jsDocCommentParts = []; ts.forEach(declarations, function (declaration, indexOfDeclaration) { // Make sure we are collecting doc comment from declaration once, // In case of union property there might be same declaration multiple times // which only varies in type parameter // Eg. let a: Array<string> | Array<number>; a.length // The property length will have two declarations of property length coming // from Array<T> - Array<string> and Array<number> if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); // If it is parameter - try and get the jsDoc comment with @param tag from function declaration's jsDoc comments if (canUseParsedParamTagComments && declaration.kind === 138 /* Parameter */) { ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), function (jsDocCommentTextRange) { var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedParamJsDocComment) { ts.addRange(jsDocCommentParts, cleanedParamJsDocComment); } }); } // If this is left side of dotted module declaration, there is no doc comments associated with this node if (declaration.kind === 218 /* ModuleDeclaration */ && declaration.body.kind === 218 /* ModuleDeclaration */) { return; } // If this is dotted module name, get the doc comments from the parent while (declaration.kind === 218 /* ModuleDeclaration */ && declaration.parent.kind === 218 /* ModuleDeclaration */) { declaration = declaration.parent; } // Get the cleaned js doc comment text from the declaration ts.forEach(getJsDocCommentTextRange(declaration.kind === 211 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedJsDocComment) { ts.addRange(jsDocCommentParts, cleanedJsDocComment); } }); } }); return jsDocCommentParts; function getJsDocCommentTextRange(node, sourceFile) { return ts.map(ts.getJsDocComments(node, sourceFile), function (jsDocComment) { return { pos: jsDocComment.pos + "/*".length, end: jsDocComment.end - "*/".length // Trim off comment end indicator }; }); } function consumeWhiteSpacesOnTheLine(pos, end, sourceFile, maxSpacesToRemove) { if (maxSpacesToRemove !== undefined) { end = Math.min(end, pos + maxSpacesToRemove); } for (; pos < end; pos++) { var ch = sourceFile.text.charCodeAt(pos); if (!ts.isWhiteSpace(ch) || ts.isLineBreak(ch)) { // Either found lineBreak or non whiteSpace return pos; } } return end; } function consumeLineBreaks(pos, end, sourceFile) { while (pos < end && ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { pos++; } return pos; } function isName(pos, end, sourceFile, name) { return pos + name.length < end && sourceFile.text.substr(pos, name.length) === name && (ts.isWhiteSpace(sourceFile.text.charCodeAt(pos + name.length)) || ts.isLineBreak(sourceFile.text.charCodeAt(pos + name.length))); } function isParamTag(pos, end, sourceFile) { // If it is @param tag return isName(pos, end, sourceFile, paramTag); } function pushDocCommentLineText(docComments, text, blankLineCount) { // Add the empty lines in between texts while (blankLineCount--) { docComments.push(ts.textPart("")); } docComments.push(ts.textPart(text)); } function getCleanedJsDocComment(pos, end, sourceFile) { var spacesToRemoveAfterAsterisk; var docComments = []; var blankLineCount = 0; var isInParamTag = false; while (pos < end) { var docCommentTextOfLine = ""; // First consume leading white space pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile); // If the comment starts with '*' consume the spaces on this line if (pos < end && sourceFile.text.charCodeAt(pos) === 42 /* asterisk */) { var lineStartPos = pos + 1; pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, spacesToRemoveAfterAsterisk); // Set the spaces to remove after asterisk as margin if not already set if (spacesToRemoveAfterAsterisk === undefined && pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { spacesToRemoveAfterAsterisk = pos - lineStartPos; } } else if (spacesToRemoveAfterAsterisk === undefined) { spacesToRemoveAfterAsterisk = 0; } // Analyse text on this line while (pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { var ch = sourceFile.text.charAt(pos); if (ch === "@") { // If it is @param tag if (isParamTag(pos, end, sourceFile)) { isInParamTag = true; pos += paramTag.length; continue; } else { isInParamTag = false; } } // Add the ch to doc text if we arent in param tag if (!isInParamTag) { docCommentTextOfLine += ch; } // Scan next character pos++; } // Continue with next line pos = consumeLineBreaks(pos, end, sourceFile); if (docCommentTextOfLine) { pushDocCommentLineText(docComments, docCommentTextOfLine, blankLineCount); blankLineCount = 0; } else if (!isInParamTag && docComments.length) { // This is blank line when there is text already parsed blankLineCount++; } } return docComments; } function getCleanedParamJsDocComment(pos, end, sourceFile) { var paramHelpStringMargin; var paramDocComments = []; while (pos < end) { if (isParamTag(pos, end, sourceFile)) { var blankLineCount = 0; var recordedParamTag = false; // Consume leading spaces pos = consumeWhiteSpaces(pos + paramTag.length); if (pos >= end) { break; } // Ignore type expression if (sourceFile.text.charCodeAt(pos) === 123 /* openBrace */) { pos++; for (var curlies = 1; pos < end; pos++) { var charCode = sourceFile.text.charCodeAt(pos); // { character means we need to find another } to match the found one if (charCode === 123 /* openBrace */) { curlies++; continue; } // } char if (charCode === 125 /* closeBrace */) { curlies--; if (curlies === 0) { // We do not have any more } to match the type expression is ignored completely pos++; break; } else { // there are more { to be matched with } continue; } } // Found start of another tag if (charCode === 64 /* at */) { break; } } // Consume white spaces pos = consumeWhiteSpaces(pos); if (pos >= end) { break; } } // Parameter name if (isName(pos, end, sourceFile, name)) { // Found the parameter we are looking for consume white spaces pos = consumeWhiteSpaces(pos + name.length); if (pos >= end) { break; } var paramHelpString = ""; var firstLineParamHelpStringPos = pos; while (pos < end) { var ch = sourceFile.text.charCodeAt(pos); // at line break, set this comment line text and go to next line if (ts.isLineBreak(ch)) { if (paramHelpString) { pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); paramHelpString = ""; blankLineCount = 0; recordedParamTag = true; } else if (recordedParamTag) { blankLineCount++; } // Get the pos after cleaning start of the line setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos); continue; } // Done scanning param help string - next tag found if (ch === 64 /* at */) { break; } paramHelpString += sourceFile.text.charAt(pos); // Go to next character pos++; } // If there is param help text, add it top the doc comments if (paramHelpString) { pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); } paramHelpStringMargin = undefined; } // If this is the start of another tag, continue with the loop in seach of param tag with symbol name if (sourceFile.text.charCodeAt(pos) === 64 /* at */) { continue; } } // Next character pos++; } return paramDocComments; function consumeWhiteSpaces(pos) { while (pos < end && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { pos++; } return pos; } function setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos) { // Get the pos after consuming line breaks pos = consumeLineBreaks(pos, end, sourceFile); if (pos >= end) { return; } if (paramHelpStringMargin === undefined) { paramHelpStringMargin = sourceFile.getLineAndCharacterOfPosition(firstLineParamHelpStringPos).character; } // Now consume white spaces max var startOfLinePos = pos; pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile, paramHelpStringMargin); if (pos >= end) { return; } var consumedSpaces = pos - startOfLinePos; if (consumedSpaces < paramHelpStringMargin) { var ch = sourceFile.text.charCodeAt(pos); if (ch === 42 /* asterisk */) { // Consume more spaces after asterisk pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, paramHelpStringMargin - consumedSpaces - 1); } } } } } }
The version of the language service API
getJsDocCommentsFromDeclarations
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getJsDocCommentsSeparatedByNewLines() { var paramTag = "@param"; var jsDocCommentParts = []; ts.forEach(declarations, function (declaration, indexOfDeclaration) { // Make sure we are collecting doc comment from declaration once, // In case of union property there might be same declaration multiple times // which only varies in type parameter // Eg. let a: Array<string> | Array<number>; a.length // The property length will have two declarations of property length coming // from Array<T> - Array<string> and Array<number> if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); // If it is parameter - try and get the jsDoc comment with @param tag from function declaration's jsDoc comments if (canUseParsedParamTagComments && declaration.kind === 138 /* Parameter */) { ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), function (jsDocCommentTextRange) { var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedParamJsDocComment) { ts.addRange(jsDocCommentParts, cleanedParamJsDocComment); } }); } // If this is left side of dotted module declaration, there is no doc comments associated with this node if (declaration.kind === 218 /* ModuleDeclaration */ && declaration.body.kind === 218 /* ModuleDeclaration */) { return; } // If this is dotted module name, get the doc comments from the parent while (declaration.kind === 218 /* ModuleDeclaration */ && declaration.parent.kind === 218 /* ModuleDeclaration */) { declaration = declaration.parent; } // Get the cleaned js doc comment text from the declaration ts.forEach(getJsDocCommentTextRange(declaration.kind === 211 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedJsDocComment) { ts.addRange(jsDocCommentParts, cleanedJsDocComment); } }); } }); return jsDocCommentParts; function getJsDocCommentTextRange(node, sourceFile) { return ts.map(ts.getJsDocComments(node, sourceFile), function (jsDocComment) { return { pos: jsDocComment.pos + "/*".length, end: jsDocComment.end - "*/".length // Trim off comment end indicator }; }); } function consumeWhiteSpacesOnTheLine(pos, end, sourceFile, maxSpacesToRemove) { if (maxSpacesToRemove !== undefined) { end = Math.min(end, pos + maxSpacesToRemove); } for (; pos < end; pos++) { var ch = sourceFile.text.charCodeAt(pos); if (!ts.isWhiteSpace(ch) || ts.isLineBreak(ch)) { // Either found lineBreak or non whiteSpace return pos; } } return end; } function consumeLineBreaks(pos, end, sourceFile) { while (pos < end && ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { pos++; } return pos; } function isName(pos, end, sourceFile, name) { return pos + name.length < end && sourceFile.text.substr(pos, name.length) === name && (ts.isWhiteSpace(sourceFile.text.charCodeAt(pos + name.length)) || ts.isLineBreak(sourceFile.text.charCodeAt(pos + name.length))); } function isParamTag(pos, end, sourceFile) { // If it is @param tag return isName(pos, end, sourceFile, paramTag); } function pushDocCommentLineText(docComments, text, blankLineCount) { // Add the empty lines in between texts while (blankLineCount--) { docComments.push(ts.textPart("")); } docComments.push(ts.textPart(text)); } function getCleanedJsDocComment(pos, end, sourceFile) { var spacesToRemoveAfterAsterisk; var docComments = []; var blankLineCount = 0; var isInParamTag = false; while (pos < end) { var docCommentTextOfLine = ""; // First consume leading white space pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile); // If the comment starts with '*' consume the spaces on this line if (pos < end && sourceFile.text.charCodeAt(pos) === 42 /* asterisk */) { var lineStartPos = pos + 1; pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, spacesToRemoveAfterAsterisk); // Set the spaces to remove after asterisk as margin if not already set if (spacesToRemoveAfterAsterisk === undefined && pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { spacesToRemoveAfterAsterisk = pos - lineStartPos; } } else if (spacesToRemoveAfterAsterisk === undefined) { spacesToRemoveAfterAsterisk = 0; } // Analyse text on this line while (pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { var ch = sourceFile.text.charAt(pos); if (ch === "@") { // If it is @param tag if (isParamTag(pos, end, sourceFile)) { isInParamTag = true; pos += paramTag.length; continue; } else { isInParamTag = false; } } // Add the ch to doc text if we arent in param tag if (!isInParamTag) { docCommentTextOfLine += ch; } // Scan next character pos++; } // Continue with next line pos = consumeLineBreaks(pos, end, sourceFile); if (docCommentTextOfLine) { pushDocCommentLineText(docComments, docCommentTextOfLine, blankLineCount); blankLineCount = 0; } else if (!isInParamTag && docComments.length) { // This is blank line when there is text already parsed blankLineCount++; } } return docComments; } function getCleanedParamJsDocComment(pos, end, sourceFile) { var paramHelpStringMargin; var paramDocComments = []; while (pos < end) { if (isParamTag(pos, end, sourceFile)) { var blankLineCount = 0; var recordedParamTag = false; // Consume leading spaces pos = consumeWhiteSpaces(pos + paramTag.length); if (pos >= end) { break; } // Ignore type expression if (sourceFile.text.charCodeAt(pos) === 123 /* openBrace */) { pos++; for (var curlies = 1; pos < end; pos++) { var charCode = sourceFile.text.charCodeAt(pos); // { character means we need to find another } to match the found one if (charCode === 123 /* openBrace */) { curlies++; continue; } // } char if (charCode === 125 /* closeBrace */) { curlies--; if (curlies === 0) { // We do not have any more } to match the type expression is ignored completely pos++; break; } else { // there are more { to be matched with } continue; } } // Found start of another tag if (charCode === 64 /* at */) { break; } } // Consume white spaces pos = consumeWhiteSpaces(pos); if (pos >= end) { break; } } // Parameter name if (isName(pos, end, sourceFile, name)) { // Found the parameter we are looking for consume white spaces pos = consumeWhiteSpaces(pos + name.length); if (pos >= end) { break; } var paramHelpString = ""; var firstLineParamHelpStringPos = pos; while (pos < end) { var ch = sourceFile.text.charCodeAt(pos); // at line break, set this comment line text and go to next line if (ts.isLineBreak(ch)) { if (paramHelpString) { pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); paramHelpString = ""; blankLineCount = 0; recordedParamTag = true; } else if (recordedParamTag) { blankLineCount++; } // Get the pos after cleaning start of the line setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos); continue; } // Done scanning param help string - next tag found if (ch === 64 /* at */) { break; } paramHelpString += sourceFile.text.charAt(pos); // Go to next character pos++; } // If there is param help text, add it top the doc comments if (paramHelpString) { pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); } paramHelpStringMargin = undefined; } // If this is the start of another tag, continue with the loop in seach of param tag with symbol name if (sourceFile.text.charCodeAt(pos) === 64 /* at */) { continue; } } // Next character pos++; } return paramDocComments; function consumeWhiteSpaces(pos) { while (pos < end && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { pos++; } return pos; } function setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos) { // Get the pos after consuming line breaks pos = consumeLineBreaks(pos, end, sourceFile); if (pos >= end) { return; } if (paramHelpStringMargin === undefined) { paramHelpStringMargin = sourceFile.getLineAndCharacterOfPosition(firstLineParamHelpStringPos).character; } // Now consume white spaces max var startOfLinePos = pos; pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile, paramHelpStringMargin); if (pos >= end) { return; } var consumedSpaces = pos - startOfLinePos; if (consumedSpaces < paramHelpStringMargin) { var ch = sourceFile.text.charCodeAt(pos); if (ch === 42 /* asterisk */) { // Consume more spaces after asterisk pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, paramHelpStringMargin - consumedSpaces - 1); } } } } }
The version of the language service API
getJsDocCommentsSeparatedByNewLines
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getJsDocCommentTextRange(node, sourceFile) { return ts.map(ts.getJsDocComments(node, sourceFile), function (jsDocComment) { return { pos: jsDocComment.pos + "/*".length, end: jsDocComment.end - "*/".length // Trim off comment end indicator }; }); }
The version of the language service API
getJsDocCommentTextRange
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function consumeWhiteSpacesOnTheLine(pos, end, sourceFile, maxSpacesToRemove) { if (maxSpacesToRemove !== undefined) { end = Math.min(end, pos + maxSpacesToRemove); } for (; pos < end; pos++) { var ch = sourceFile.text.charCodeAt(pos); if (!ts.isWhiteSpace(ch) || ts.isLineBreak(ch)) { // Either found lineBreak or non whiteSpace return pos; } } return end; }
The version of the language service API
consumeWhiteSpacesOnTheLine
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function consumeLineBreaks(pos, end, sourceFile) { while (pos < end && ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { pos++; } return pos; }
The version of the language service API
consumeLineBreaks
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isName(pos, end, sourceFile, name) { return pos + name.length < end && sourceFile.text.substr(pos, name.length) === name && (ts.isWhiteSpace(sourceFile.text.charCodeAt(pos + name.length)) || ts.isLineBreak(sourceFile.text.charCodeAt(pos + name.length))); }
The version of the language service API
isName
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isParamTag(pos, end, sourceFile) { // If it is @param tag return isName(pos, end, sourceFile, paramTag); }
The version of the language service API
isParamTag
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function pushDocCommentLineText(docComments, text, blankLineCount) { // Add the empty lines in between texts while (blankLineCount--) { docComments.push(ts.textPart("")); } docComments.push(ts.textPart(text)); }
The version of the language service API
pushDocCommentLineText
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getCleanedJsDocComment(pos, end, sourceFile) { var spacesToRemoveAfterAsterisk; var docComments = []; var blankLineCount = 0; var isInParamTag = false; while (pos < end) { var docCommentTextOfLine = ""; // First consume leading white space pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile); // If the comment starts with '*' consume the spaces on this line if (pos < end && sourceFile.text.charCodeAt(pos) === 42 /* asterisk */) { var lineStartPos = pos + 1; pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, spacesToRemoveAfterAsterisk); // Set the spaces to remove after asterisk as margin if not already set if (spacesToRemoveAfterAsterisk === undefined && pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { spacesToRemoveAfterAsterisk = pos - lineStartPos; } } else if (spacesToRemoveAfterAsterisk === undefined) { spacesToRemoveAfterAsterisk = 0; } // Analyse text on this line while (pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { var ch = sourceFile.text.charAt(pos); if (ch === "@") { // If it is @param tag if (isParamTag(pos, end, sourceFile)) { isInParamTag = true; pos += paramTag.length; continue; } else { isInParamTag = false; } } // Add the ch to doc text if we arent in param tag if (!isInParamTag) { docCommentTextOfLine += ch; } // Scan next character pos++; } // Continue with next line pos = consumeLineBreaks(pos, end, sourceFile); if (docCommentTextOfLine) { pushDocCommentLineText(docComments, docCommentTextOfLine, blankLineCount); blankLineCount = 0; } else if (!isInParamTag && docComments.length) { // This is blank line when there is text already parsed blankLineCount++; } } return docComments; }
The version of the language service API
getCleanedJsDocComment
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getCleanedParamJsDocComment(pos, end, sourceFile) { var paramHelpStringMargin; var paramDocComments = []; while (pos < end) { if (isParamTag(pos, end, sourceFile)) { var blankLineCount = 0; var recordedParamTag = false; // Consume leading spaces pos = consumeWhiteSpaces(pos + paramTag.length); if (pos >= end) { break; } // Ignore type expression if (sourceFile.text.charCodeAt(pos) === 123 /* openBrace */) { pos++; for (var curlies = 1; pos < end; pos++) { var charCode = sourceFile.text.charCodeAt(pos); // { character means we need to find another } to match the found one if (charCode === 123 /* openBrace */) { curlies++; continue; } // } char if (charCode === 125 /* closeBrace */) { curlies--; if (curlies === 0) { // We do not have any more } to match the type expression is ignored completely pos++; break; } else { // there are more { to be matched with } continue; } } // Found start of another tag if (charCode === 64 /* at */) { break; } } // Consume white spaces pos = consumeWhiteSpaces(pos); if (pos >= end) { break; } } // Parameter name if (isName(pos, end, sourceFile, name)) { // Found the parameter we are looking for consume white spaces pos = consumeWhiteSpaces(pos + name.length); if (pos >= end) { break; } var paramHelpString = ""; var firstLineParamHelpStringPos = pos; while (pos < end) { var ch = sourceFile.text.charCodeAt(pos); // at line break, set this comment line text and go to next line if (ts.isLineBreak(ch)) { if (paramHelpString) { pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); paramHelpString = ""; blankLineCount = 0; recordedParamTag = true; } else if (recordedParamTag) { blankLineCount++; } // Get the pos after cleaning start of the line setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos); continue; } // Done scanning param help string - next tag found if (ch === 64 /* at */) { break; } paramHelpString += sourceFile.text.charAt(pos); // Go to next character pos++; } // If there is param help text, add it top the doc comments if (paramHelpString) { pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); } paramHelpStringMargin = undefined; } // If this is the start of another tag, continue with the loop in seach of param tag with symbol name if (sourceFile.text.charCodeAt(pos) === 64 /* at */) { continue; } } // Next character pos++; } return paramDocComments; function consumeWhiteSpaces(pos) { while (pos < end && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { pos++; } return pos; } function setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos) { // Get the pos after consuming line breaks pos = consumeLineBreaks(pos, end, sourceFile); if (pos >= end) { return; } if (paramHelpStringMargin === undefined) { paramHelpStringMargin = sourceFile.getLineAndCharacterOfPosition(firstLineParamHelpStringPos).character; } // Now consume white spaces max var startOfLinePos = pos; pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile, paramHelpStringMargin); if (pos >= end) { return; } var consumedSpaces = pos - startOfLinePos; if (consumedSpaces < paramHelpStringMargin) { var ch = sourceFile.text.charCodeAt(pos); if (ch === 42 /* asterisk */) { // Consume more spaces after asterisk pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, paramHelpStringMargin - consumedSpaces - 1); } } } }
The version of the language service API
getCleanedParamJsDocComment
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function consumeWhiteSpaces(pos) { while (pos < end && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { pos++; } return pos; }
The version of the language service API
consumeWhiteSpaces
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos) { // Get the pos after consuming line breaks pos = consumeLineBreaks(pos, end, sourceFile); if (pos >= end) { return; } if (paramHelpStringMargin === undefined) { paramHelpStringMargin = sourceFile.getLineAndCharacterOfPosition(firstLineParamHelpStringPos).character; } // Now consume white spaces max var startOfLinePos = pos; pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile, paramHelpStringMargin); if (pos >= end) { return; } var consumedSpaces = pos - startOfLinePos; if (consumedSpaces < paramHelpStringMargin) { var ch = sourceFile.text.charCodeAt(pos); if (ch === 42 /* asterisk */) { // Consume more spaces after asterisk pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, paramHelpStringMargin - consumedSpaces - 1); } } }
The version of the language service API
setPosForParamHelpStringOnNextLine
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function TypeObject(checker, flags) { this.checker = checker; this.flags = flags; }
The version of the language service API
TypeObject
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function SignatureObject(checker) { this.checker = checker; }
The version of the language service API
SignatureObject
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function SourceFileObject(kind, pos, end) { _super.call(this, kind, pos, end); }
The version of the language service API
SourceFileObject
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function addDeclaration(declaration) { var name = getDeclarationName(declaration); if (name) { var declarations = getDeclarations(name); declarations.push(declaration); } }
The version of the language service API
addDeclaration
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getDeclarations(name) { return ts.getProperty(result, name) || (result[name] = []); }
The version of the language service API
getDeclarations
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getDeclarationName(declaration) { if (declaration.name) { var result_2 = getTextOfIdentifierOrLiteral(declaration.name); if (result_2 !== undefined) { return result_2; } if (declaration.name.kind === 136 /* ComputedPropertyName */) { var expr = declaration.name.expression; if (expr.kind === 166 /* PropertyAccessExpression */) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); } } return undefined; }
The version of the language service API
getDeclarationName
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getTextOfIdentifierOrLiteral(node) { if (node) { if (node.kind === 69 /* Identifier */ || node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { return node.text; } } return undefined; }
The version of the language service API
getTextOfIdentifierOrLiteral
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function visit(node) { switch (node.kind) { case 213 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { var declarations = getDeclarations(declarationName); var lastDeclaration = ts.lastOrUndefined(declarations); // Check whether this declaration belongs to an "overload group". if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) { // Overwrite the last declaration if it was an overload // and this one is an implementation. if (functionDeclaration.body && !lastDeclaration.body) { declarations[declarations.length - 1] = functionDeclaration; } } else { declarations.push(functionDeclaration); } ts.forEachChild(node, visit); } break; case 214 /* ClassDeclaration */: case 215 /* InterfaceDeclaration */: case 216 /* TypeAliasDeclaration */: case 217 /* EnumDeclaration */: case 218 /* ModuleDeclaration */: case 221 /* ImportEqualsDeclaration */: case 230 /* ExportSpecifier */: case 226 /* ImportSpecifier */: case 221 /* ImportEqualsDeclaration */: case 223 /* ImportClause */: case 224 /* NamespaceImport */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 155 /* TypeLiteral */: addDeclaration(node); // fall through case 144 /* Constructor */: case 193 /* VariableStatement */: case 212 /* VariableDeclarationList */: case 161 /* ObjectBindingPattern */: case 162 /* ArrayBindingPattern */: case 219 /* ModuleBlock */: ts.forEachChild(node, visit); break; case 192 /* Block */: if (ts.isFunctionBlock(node)) { ts.forEachChild(node, visit); } break; case 138 /* Parameter */: // Only consider properties defined as constructor parameters if (!(node.flags & 56 /* AccessibilityModifier */)) { break; } // fall through case 211 /* VariableDeclaration */: case 163 /* BindingElement */: if (ts.isBindingPattern(node.name)) { ts.forEachChild(node.name, visit); break; } case 247 /* EnumMember */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: addDeclaration(node); break; case 228 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; case 222 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: // import d from "mod"; if (importClause.name) { addDeclaration(importClause); } // Handle named bindings in imports e.g.: // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { ts.forEach(importClause.namedBindings.elements, visit); } } } break; } }
The version of the language service API
visit
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); } return ""; }
The version of the language service API
displayPartsToString
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isLocalVariableOrFunction(symbol) { if (symbol.parent) { return false; // This is exported symbol } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local if (declaration.kind === 173 /* FunctionExpression */) { return true; } if (declaration.kind !== 211 /* VariableDeclaration */ && declaration.kind !== 213 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent_8 = declaration.parent; !ts.isFunctionBlock(parent_8); parent_8 = parent_8.parent) { // Reached source file or module block if (parent_8.kind === 248 /* SourceFile */ || parent_8.kind === 219 /* ModuleBlock */) { return false; } } // parent is in function block return true; }); }
The version of the language service API
isLocalVariableOrFunction
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getDefaultCompilerOptions() { // Always default to "ScriptTarget.ES5" for the language service return { target: 1 /* ES5 */, module: 0 /* None */, jsx: 1 /* Preserve */ }; }
The version of the language service API
getDefaultCompilerOptions
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT