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 aggregate(node) { if (node.kind === 208 /* ThrowStatement */) { statementAccumulator.push(node); } else if (node.kind === 209 /* TryStatement */) { var tryStatement = node; if (tryStatement.catchClause) { aggregate(tryStatement.catchClause); } else { // Exceptions thrown within a try block lacking a catch clause // are "owned" in the current context. aggregate(tryStatement.tryBlock); } if (tryStatement.finallyBlock) { aggregate(tryStatement.finallyBlock); } } else if (!ts.isFunctionLike(node)) { ts.forEachChild(node, aggregate); } }
Aggregates all throw-statements within this node *without* crossing into function boundaries and try-blocks with catch-clauses.
aggregate
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function aggregateAllBreakAndContinueStatements(node) { var statementAccumulator = []; aggregate(node); return statementAccumulator; function aggregate(node) { if (node.kind === 203 /* BreakStatement */ || node.kind === 202 /* ContinueStatement */) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { ts.forEachChild(node, aggregate); } } }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
aggregateAllBreakAndContinueStatements
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function aggregate(node) { if (node.kind === 203 /* BreakStatement */ || node.kind === 202 /* ContinueStatement */) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { ts.forEachChild(node, aggregate); } }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
aggregate
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function ownsBreakOrContinueStatement(owner, statement) { var actualOwner = getBreakOrContinueOwner(statement); return actualOwner && actualOwner === owner; }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
ownsBreakOrContinueStatement
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getBreakOrContinueOwner(statement) { for (var node_2 = statement.parent; node_2; node_2 = node_2.parent) { switch (node_2.kind) { case 206 /* SwitchStatement */: if (statement.kind === 202 /* ContinueStatement */) { continue; } // Fall through. case 199 /* ForStatement */: case 200 /* ForInStatement */: case 201 /* ForOfStatement */: case 198 /* WhileStatement */: case 197 /* DoStatement */: if (!statement.label || isLabeledBy(node_2, statement.label.text)) { return node_2; } break; default: // Don't cross function boundaries. if (ts.isFunctionLike(node_2)) { return undefined; } break; } } return undefined; }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getBreakOrContinueOwner
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getModifierOccurrences(modifier, declaration) { var container = declaration.parent; // Make sure we only highlight the keyword when it makes sense to do so. if (ts.isAccessibilityModifier(modifier)) { if (!(container.kind === 214 /* ClassDeclaration */ || container.kind === 186 /* ClassExpression */ || (declaration.kind === 138 /* Parameter */ && hasKind(container, 144 /* Constructor */)))) { return undefined; } } else if (modifier === 113 /* StaticKeyword */) { if (!(container.kind === 214 /* ClassDeclaration */ || container.kind === 186 /* ClassExpression */)) { return undefined; } } else if (modifier === 82 /* ExportKeyword */ || modifier === 122 /* DeclareKeyword */) { if (!(container.kind === 219 /* ModuleBlock */ || container.kind === 248 /* SourceFile */)) { return undefined; } } else if (modifier === 115 /* AbstractKeyword */) { if (!(container.kind === 214 /* ClassDeclaration */ || declaration.kind === 214 /* ClassDeclaration */)) { return undefined; } } else { // unsupported modifier return undefined; } var keywords = []; var modifierFlag = getFlagFromModifier(modifier); var nodes; switch (container.kind) { case 219 /* ModuleBlock */: case 248 /* SourceFile */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */) { nodes = declaration.members.concat(declaration); } else { nodes = container.statements; } break; case 144 /* Constructor */: nodes = container.parameters.concat(container.parent.members); break; case 214 /* ClassDeclaration */: case 186 /* ClassExpression */: nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. if (modifierFlag & 56 /* AccessibilityModifier */) { var constructor = ts.forEach(container.members, function (member) { return member.kind === 144 /* Constructor */ && member; }); if (constructor) { nodes = nodes.concat(constructor.parameters); } } else if (modifierFlag & 128 /* Abstract */) { nodes = nodes.concat(container); } break; default: ts.Debug.fail("Invalid container kind."); } ts.forEach(nodes, function (node) { if (node.modifiers && node.flags & modifierFlag) { ts.forEach(node.modifiers, function (child) { return pushKeywordIf(keywords, child, modifier); }); } }); return ts.map(keywords, getHighlightSpanForNode); function getFlagFromModifier(modifier) { switch (modifier) { case 112 /* PublicKeyword */: return 8 /* Public */; case 110 /* PrivateKeyword */: return 16 /* Private */; case 111 /* ProtectedKeyword */: return 32 /* Protected */; case 113 /* StaticKeyword */: return 64 /* Static */; case 82 /* ExportKeyword */: return 2 /* Export */; case 122 /* DeclareKeyword */: return 4 /* Ambient */; case 115 /* AbstractKeyword */: return 128 /* Abstract */; default: ts.Debug.fail(); } } }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getModifierOccurrences
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getFlagFromModifier(modifier) { switch (modifier) { case 112 /* PublicKeyword */: return 8 /* Public */; case 110 /* PrivateKeyword */: return 16 /* Private */; case 111 /* ProtectedKeyword */: return 32 /* Protected */; case 113 /* StaticKeyword */: return 64 /* Static */; case 82 /* ExportKeyword */: return 2 /* Export */; case 122 /* DeclareKeyword */: return 4 /* Ambient */; case 115 /* AbstractKeyword */: return 128 /* Abstract */; default: ts.Debug.fail(); } }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getFlagFromModifier
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function pushKeywordIf(keywordList, token) { var expected = []; for (var _i = 2; _i < arguments.length; _i++) { expected[_i - 2] = arguments[_i]; } if (token && ts.contains(expected, token.kind)) { keywordList.push(token); return true; } return false; }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
pushKeywordIf
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getGetAndSetOccurrences(accessorDeclaration) { var keywords = []; tryPushAccessorKeyword(accessorDeclaration.symbol, 145 /* GetAccessor */); tryPushAccessorKeyword(accessorDeclaration.symbol, 146 /* SetAccessor */); return ts.map(keywords, getHighlightSpanForNode); function tryPushAccessorKeyword(accessorSymbol, accessorKind) { var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); if (accessor) { ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 123 /* GetKeyword */, 129 /* SetKeyword */); }); } } }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getGetAndSetOccurrences
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function tryPushAccessorKeyword(accessorSymbol, accessorKind) { var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); if (accessor) { ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 123 /* GetKeyword */, 129 /* SetKeyword */); }); } }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
tryPushAccessorKeyword
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getConstructorOccurrences(constructorDeclaration) { var declarations = constructorDeclaration.symbol.getDeclarations(); var keywords = []; ts.forEach(declarations, function (declaration) { ts.forEach(declaration.getChildren(), function (token) { return pushKeywordIf(keywords, token, 121 /* ConstructorKeyword */); }); }); return ts.map(keywords, getHighlightSpanForNode); }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getConstructorOccurrences
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getLoopBreakContinueOccurrences(loopNode) { var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 86 /* ForKeyword */, 104 /* WhileKeyword */, 79 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. if (loopNode.kind === 197 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 104 /* WhileKeyword */)) { break; } } } } var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); ts.forEach(breaksAndContinues, function (statement) { if (ownsBreakOrContinueStatement(loopNode, statement)) { pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */, 75 /* ContinueKeyword */); } }); return ts.map(keywords, getHighlightSpanForNode); }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getLoopBreakContinueOccurrences
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { case 199 /* ForStatement */: case 200 /* ForInStatement */: case 201 /* ForOfStatement */: case 197 /* DoStatement */: case 198 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); case 206 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } return undefined; }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getBreakOrContinueStatementOccurrences
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getSwitchCaseDefaultOccurrences(switchStatement) { var keywords = []; pushKeywordIf(keywords, switchStatement.getFirstToken(), 96 /* SwitchKeyword */); // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. ts.forEach(switchStatement.caseBlock.clauses, function (clause) { pushKeywordIf(keywords, clause.getFirstToken(), 71 /* CaseKeyword */, 77 /* DefaultKeyword */); var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); ts.forEach(breaksAndContinues, function (statement) { if (ownsBreakOrContinueStatement(switchStatement, statement)) { pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */); } }); }); return ts.map(keywords, getHighlightSpanForNode); }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getSwitchCaseDefaultOccurrences
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getTryCatchFinallyOccurrences(tryStatement) { var keywords = []; pushKeywordIf(keywords, tryStatement.getFirstToken(), 100 /* TryKeyword */); if (tryStatement.catchClause) { pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 72 /* CatchKeyword */); } if (tryStatement.finallyBlock) { var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); pushKeywordIf(keywords, finallyKeyword, 85 /* FinallyKeyword */); } return ts.map(keywords, getHighlightSpanForNode); }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getTryCatchFinallyOccurrences
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getThrowOccurrences(throwStatement) { var owner = getThrowStatementOwner(throwStatement); if (!owner) { return undefined; } var keywords = []; ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); }); // If the "owner" is a function, then we equate 'return' and 'throw' statements in their // ability to "jump out" of the function, and include occurrences for both. if (ts.isFunctionBlock(owner)) { ts.forEachReturnStatement(owner, function (returnStatement) { pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); }); } return ts.map(keywords, getHighlightSpanForNode); }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getThrowOccurrences
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); // If we didn't find a containing function with a block body, bail out. if (!(func && hasKind(func.body, 192 /* Block */))) { return undefined; } var keywords = []; ts.forEachReturnStatement(func.body, function (returnStatement) { pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); }); // Include 'throw' statements that do not occur within a try block. ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); }); return ts.map(keywords, getHighlightSpanForNode); }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getReturnOccurrences
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getIfElseOccurrences(ifStatement) { var keywords = []; // Traverse upwards through all parent if-statements linked by their else-branches. while (hasKind(ifStatement.parent, 196 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. while (ifStatement) { var children = ifStatement.getChildren(); pushKeywordIf(keywords, children[0], 88 /* IfKeyword */); // Generally the 'else' keyword is second-to-last, so we traverse backwards. for (var i = children.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, children[i], 80 /* ElseKeyword */)) { break; } } if (!hasKind(ifStatement.elseStatement, 196 /* IfStatement */)) { break; } ifStatement = ifStatement.elseStatement; } var result = []; // We'd like to highlight else/ifs together if they are only separated by whitespace // (i.e. the keywords are separated by no comments, no newlines). for (var i = 0; i < keywords.length; i++) { if (keywords[i].kind === 80 /* ElseKeyword */ && i < keywords.length - 1) { var elseKeyword = keywords[i]; var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. var shouldCombindElseAndIf = true; // Avoid recalculating getStart() by iterating backwards. for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { if (!ts.isWhiteSpace(sourceFile.text.charCodeAt(j))) { shouldCombindElseAndIf = false; break; } } if (shouldCombindElseAndIf) { result.push({ fileName: fileName, textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), kind: HighlightSpanKind.reference }); i++; // skip the next keyword continue; } } // Ordinary case: just highlight the keyword. result.push(getHighlightSpanForNode(keywords[i])); } return result; }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getIfElseOccurrences
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getOccurrencesAtPositionCore(fileName, position) { synchronizeHostData(); return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName])); function convertDocumentHighlights(documentHighlights) { if (!documentHighlights) { return undefined; } var result = []; for (var _i = 0, documentHighlights_1 = documentHighlights; _i < documentHighlights_1.length; _i++) { var entry = documentHighlights_1[_i]; for (var _a = 0, _b = entry.highlightSpans; _a < _b.length; _a++) { var highlightSpan = _b[_a]; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference }); } } return result; } }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getOccurrencesAtPositionCore
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function convertDocumentHighlights(documentHighlights) { if (!documentHighlights) { return undefined; } var result = []; for (var _i = 0, documentHighlights_1 = documentHighlights; _i < documentHighlights_1.length; _i++) { var entry = documentHighlights_1[_i]; for (var _a = 0, _b = entry.highlightSpans; _a < _b.length; _a++) { var highlightSpan = _b[_a]; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference }); } } return result; }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
convertDocumentHighlights
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function convertReferences(referenceSymbols) { if (!referenceSymbols) { return undefined; } var referenceEntries = []; for (var _i = 0, referenceSymbols_1 = referenceSymbols; _i < referenceSymbols_1.length; _i++) { var referenceSymbol = referenceSymbols_1[_i]; ts.addRange(referenceEntries, referenceSymbol.references); } return referenceEntries; }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
convertReferences
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function findRenameLocations(fileName, position, findInStrings, findInComments) { var referencedSymbols = findReferencedSymbols(fileName, position, findInStrings, findInComments); return convertReferences(referencedSymbols); }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
findRenameLocations
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getReferencesAtPosition(fileName, position) { var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); return convertReferences(referencedSymbols); }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getReferencesAtPosition
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function findReferences(fileName, position) { var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); // Only include referenced symbols that have a valid definition. return ts.filter(referencedSymbols, function (rs) { return !!rs.definition; }); }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
findReferences
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function findReferencedSymbols(fileName, position, findInStrings, findInComments) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, position); if (!node) { return undefined; } if (node.kind !== 69 /* Identifier */ && // TODO (drosen): This should be enabled in a later release - currently breaks rename. //node.kind !== SyntaxKind.ThisKeyword && //node.kind !== SyntaxKind.SuperKeyword && !isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && !isNameOfExternalModuleImportOrDeclaration(node)) { return undefined; } ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 8 /* NumericLiteral */ || node.kind === 9 /* StringLiteral */); return getReferencedSymbolsForNode(node, program.getSourceFiles(), findInStrings, findInComments); }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
findReferencedSymbols
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getReferencedSymbolsForNode(node, sourceFiles, findInStrings, findInComments) { var typeChecker = program.getTypeChecker(); // Labels if (isLabelName(node)) { if (isJumpStatementTarget(node)) { var labelDefinition = getTargetLabel(node.parent, node.text); // if we have a label definition, look within its statement for references, if not, then // the label is undefined and we have no results.. return labelDefinition ? getLabelReferencesInNode(labelDefinition.parent, labelDefinition) : undefined; } else { // it is a label definition and not a target, search within the parent labeledStatement return getLabelReferencesInNode(node.parent, node); } } if (node.kind === 97 /* ThisKeyword */) { return getReferencesForThisKeyword(node, sourceFiles); } if (node.kind === 95 /* SuperKeyword */) { return getReferencesForSuperKeyword(node); } var symbol = typeChecker.getSymbolAtLocation(node); // Could not find a symbol e.g. unknown identifier if (!symbol) { // Can't have references to something that we have no symbol for. return undefined; } var declarations = symbol.declarations; // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol if (!declarations || !declarations.length) { return undefined; } var result; // Compute the meaning from the location and the symbol it references var searchMeaning = getIntersectingMeaningFromDeclarations(getMeaningFromLocation(node), declarations); // Get the text to search for. // Note: if this is an external module symbol, the name doesn't include quotes. var declaredName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); // Maps from a symbol ID to the ReferencedSymbol entry in 'result'. var symbolToIndex = []; if (scope) { result = []; getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } else { var internedName = getInternedName(symbol, node, declarations); for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { var sourceFile = sourceFiles_2[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); if (ts.lookUp(nameTable, internedName)) { result = result || []; getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } } } return result; function getDefinition(symbol) { var info = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, node.getSourceFile(), getContainerNode(node), node); var name = ts.map(info.displayParts, function (p) { return p.text; }).join(""); var declarations = symbol.declarations; if (!declarations || declarations.length === 0) { return undefined; } return { containerKind: "", containerName: "", name: name, kind: info.symbolKind, fileName: declarations[0].getSourceFile().fileName, textSpan: ts.createTextSpan(declarations[0].getStart(), 0) }; } function isImportOrExportSpecifierImportSymbol(symbol) { return (symbol.flags & 8388608 /* Alias */) && ts.forEach(symbol.declarations, function (declaration) { return declaration.kind === 226 /* ImportSpecifier */ || declaration.kind === 230 /* ExportSpecifier */; }); } function getInternedName(symbol, location, declarations) { // If this is an export or import specifier it could have been renamed using the 'as' syntax. // If so we want to search for whatever under the cursor. if (ts.isImportOrExportSpecifierName(location)) { return location.getText(); } // Try to get the local symbol if we're dealing with an 'export default' // since that symbol has the "true" name. var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); symbol = localExportDefaultSymbol || symbol; return ts.stripQuotes(symbol.name); } /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can * probably be improved. * * @returns undefined if the scope cannot be determined, implying that * a reference to a symbol can occur anywhere. */ function getSymbolScope(symbol) { // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var valueDeclaration = symbol.valueDeclaration; if (valueDeclaration && (valueDeclaration.kind === 173 /* FunctionExpression */ || valueDeclaration.kind === 186 /* ClassExpression */)) { return valueDeclaration; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 16 /* Private */) ? d : undefined; }); if (privateDeclaration) { return ts.getAncestor(privateDeclaration, 214 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. // So consider it visibile outside its declaration scope. if (symbol.flags & 8388608 /* Alias */) { return undefined; } // if this symbol is visible from its parent container, e.g. exported, then bail out // if symbol correspond to the union property - bail out if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { return undefined; } var scope = undefined; var declarations = symbol.getDeclarations(); if (declarations) { for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { var declaration = declarations_8[_i]; var container = getContainerNode(declaration); if (!container) { return undefined; } if (scope && scope !== container) { // Different declarations have different containers, bail out return undefined; } if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; } // The search scope is the container node scope = container; } } return scope; } function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { var positions = []; /// TODO: Cache symbol existence for files to save text search // Also, need to make this work for unicode escapes. // Be resilient in the face of a symbol with no name or zero length name if (!symbolName || !symbolName.length) { return positions; } var text = sourceFile.text; var sourceLength = text.length; var symbolNameLength = symbolName.length; var position = text.indexOf(symbolName, start); while (position >= 0) { cancellationToken.throwIfCancellationRequested(); // If we are past the end, stop looking if (position > end) break; // We found a match. Make sure it's not part of a larger word (i.e. the char // before and after it have to be a non-identifier char). var endPosition = position + symbolNameLength; if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2 /* Latest */)) && (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2 /* Latest */))) { // Found a real match. Keep searching. positions.push(position); } position = text.indexOf(symbolName, position + symbolNameLength + 1); } return positions; } function getLabelReferencesInNode(container, targetLabel) { var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); if (!node || node.getWidth() !== labelName.length) { return; } // Only pick labels that are either the target label, or have a target that is the target label if (node === targetLabel || (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel)) { references.push(getReferenceEntryFromNode(node)); } }); var definition = { containerKind: "", containerName: "", fileName: targetLabel.getSourceFile().fileName, kind: ScriptElementKind.label, name: labelName, textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()) }; return [{ definition: definition, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { if (node) { // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node.kind) { case 69 /* Identifier */: return node.getWidth() === searchSymbolName.length; case 9 /* StringLiteral */: if (isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) { // For string literals we have two additional chars for the quotes return node.getWidth() === searchSymbolName.length + 2; } break; case 8 /* NumericLiteral */: if (isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { return node.getWidth() === searchSymbolName.length; } break; } } return false; } /** Search within node "container" for references for a search value, where the search value is defined as a * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). * searchLocation: a node where the search value */ function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { var sourceFile = container.getSourceFile(); var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*</; var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, container.getStart(), container.getEnd()); if (possiblePositions.length) { // Build the set of symbols to search for, initially it has only the current symbol var searchSymbols = populateSearchSymbolSet(searchSymbol, searchLocation); ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); if (!isValidReferencePosition(referenceLocation, searchText)) { // This wasn't the start of a token. Check to see if it might be a // match in a comment or string if that's what the caller is asking // for. if ((findInStrings && ts.isInString(sourceFile, position)) || (findInComments && isInNonReferenceComment(sourceFile, position))) { // In the case where we're looking inside comments/strings, we don't have // an actual definition. So just use 'undefined' here. Features like // 'Rename' won't care (as they ignore the definitions), and features like // 'FindReferences' will just filter out these results. result.push({ definition: undefined, references: [{ fileName: sourceFile.fileName, textSpan: ts.createTextSpan(position, searchText.length), isWriteAccess: false }] }); } return; } if (!(getMeaningFromLocation(referenceLocation) & searchMeaning)) { return; } var referenceSymbol = typeChecker.getSymbolAtLocation(referenceLocation); if (referenceSymbol) { var referenceSymbolDeclaration = referenceSymbol.valueDeclaration; var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); var relatedSymbol = getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation); if (relatedSymbol) { var referencedSymbol = getReferencedSymbol(relatedSymbol); referencedSymbol.references.push(getReferenceEntryFromNode(referenceLocation)); } else if (!(referenceSymbol.flags & 67108864 /* Transient */) && searchSymbols.indexOf(shorthandValueSymbol) >= 0) { var referencedSymbol = getReferencedSymbol(shorthandValueSymbol); referencedSymbol.references.push(getReferenceEntryFromNode(referenceSymbolDeclaration.name)); } } }); } return; function getReferencedSymbol(symbol) { var symbolId = ts.getSymbolId(symbol); var index = symbolToIndex[symbolId]; if (index === undefined) { index = result.length; symbolToIndex[symbolId] = index; result.push({ definition: getDefinition(symbol), references: [] }); } return result[index]; } function isInNonReferenceComment(sourceFile, position) { return ts.isInCommentHelper(sourceFile, position, isNonReferenceComment); function isNonReferenceComment(c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); } } } function getReferencesForSuperKeyword(superKeyword) { var searchSpaceNode = ts.getSuperContainer(superKeyword, /*includeFunctions*/ false); if (!searchSpaceNode) { return undefined; } // Whether 'super' occurs in a static context within a class. var staticFlag = 64 /* Static */; switch (searchSpaceNode.kind) { case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; default: return undefined; } var references = []; var sourceFile = searchSpaceNode.getSourceFile(); var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); if (!node || node.kind !== 95 /* SuperKeyword */) { return; } var container = ts.getSuperContainer(node, /*includeFunctions*/ false); // If we have a 'super' container, we must have an enclosing class. // Now make sure the owning class is the same as the search-space // and has the same static qualifier as the original 'super's owner. if (container && (64 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { references.push(getReferenceEntryFromNode(node)); } }); var definition = getDefinition(searchSpaceNode.symbol); return [{ definition: definition, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. var staticFlag = 64 /* Static */; switch (searchSpaceNode.kind) { case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // fall through case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; case 248 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // Fall through case 213 /* FunctionDeclaration */: case 173 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. default: return undefined; } var references = []; var possiblePositions; if (searchSpaceNode.kind === 248 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { var sourceFile = searchSpaceNode.getSourceFile(); possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } return [{ definition: { containerKind: "", containerName: "", fileName: node.getSourceFile().fileName, kind: ScriptElementKind.variableElement, name: "this", textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()) }, references: references }]; function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); if (!node || node.kind !== 97 /* ThisKeyword */) { return; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { case 173 /* FunctionExpression */: case 213 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; case 186 /* ClassExpression */: case 214 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 64 /* Static */) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; case 248 /* SourceFile */: if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; } }); } } function populateSearchSymbolSet(symbol, location) { // The search set contains at least the current symbol var result = [symbol]; // If the symbol is an alias, add what it alaises to the list if (isImportOrExportSpecifierImportSymbol(symbol)) { result.push(typeChecker.getAliasedSymbol(symbol)); } // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set if (isNameOfPropertyAssignment(location)) { ts.forEach(getPropertySymbolsFromContextualType(location), function (contextualSymbol) { ts.addRange(result, typeChecker.getRootSymbols(contextualSymbol)); }); /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service * should show both 'name' in 'obj' and 'name' in variable declaration * let name = "Foo"; * let obj = { name }; * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(location.parent); if (shorthandValueSymbol) { result.push(shorthandValueSymbol); } } // If this is a union property, add all the symbols from all its source symbols in all unioned types. // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { if (rootSymbol !== symbol) { result.push(rootSymbol); } // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result); } }); return result; } function getPropertySymbolsFromBaseTypes(symbol, propertyName, result) { if (symbol && symbol.flags & (32 /* Class */ | 64 /* Interface */)) { ts.forEach(symbol.getDeclarations(), function (declaration) { if (declaration.kind === 214 /* ClassDeclaration */) { getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } else if (declaration.kind === 215 /* InterfaceDeclaration */) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); } return; function getPropertySymbolFromTypeReference(typeReference) { if (typeReference) { var type = typeChecker.getTypeAtLocation(typeReference); if (type) { var propertySymbol = typeChecker.getPropertyOfType(type, propertyName); if (propertySymbol) { result.push(propertySymbol); } // Visit the typeReference as well to see if it directly or indirectly use that property getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result); } } } } function getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation) { if (searchSymbols.indexOf(referenceSymbol) >= 0) { return referenceSymbol; } // If the reference symbol is an alias, check if what it is aliasing is one of the search // symbols. if (isImportOrExportSpecifierImportSymbol(referenceSymbol)) { var aliasedSymbol = typeChecker.getAliasedSymbol(referenceSymbol); if (searchSymbols.indexOf(aliasedSymbol) >= 0) { return aliasedSymbol; } } // If the reference location is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this symbol to // compare to our searchSymbol if (isNameOfPropertyAssignment(referenceLocation)) { return ts.forEach(getPropertySymbolsFromContextualType(referenceLocation), function (contextualSymbol) { return ts.forEach(typeChecker.getRootSymbols(contextualSymbol), function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); }); } // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) // Or a union property, use its underlying unioned symbols return ts.forEach(typeChecker.getRootSymbols(referenceSymbol), function (rootSymbol) { // if it is in the list, then we are done if (searchSymbols.indexOf(rootSymbol) >= 0) { return rootSymbol; } // Finally, try all properties with the same name in any type the containing type extended or implemented, and // see if any is in the list if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { var result_3 = []; getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_3); return ts.forEach(result_3, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); } function getPropertySymbolsFromContextualType(node) { if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); var name_37 = node.text; if (contextualType) { if (contextualType.flags & 16384 /* Union */) { // This is a union type, first see if the property we are looking for is a union property (i.e. exists in all types) // if not, search the constituent types for the property var unionProperty = contextualType.getProperty(name_37); if (unionProperty) { return [unionProperty]; } else { var result_4 = []; ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name_37); if (symbol) { result_4.push(symbol); } }); return result_4; } } else { var symbol_1 = contextualType.getProperty(name_37); if (symbol_1) { return [symbol_1]; } } } } return undefined; } /** Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class * then we need to widen the search to include type positions as well. * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module) * do not intersect in any of the three spaces. */ function getIntersectingMeaningFromDeclarations(meaning, declarations) { if (declarations) { var lastIterationMeaning; do { // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module // intersects with the class in the value space. // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { var declaration = declarations_9[_i]; var declarationMeaning = getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; } } } while (meaning !== lastIterationMeaning); } return meaning; } }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getReferencedSymbolsForNode
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getDefinition(symbol) { var info = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, node.getSourceFile(), getContainerNode(node), node); var name = ts.map(info.displayParts, function (p) { return p.text; }).join(""); var declarations = symbol.declarations; if (!declarations || declarations.length === 0) { return undefined; } return { containerKind: "", containerName: "", name: name, kind: info.symbolKind, fileName: declarations[0].getSourceFile().fileName, textSpan: ts.createTextSpan(declarations[0].getStart(), 0) }; }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getDefinition
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isImportOrExportSpecifierImportSymbol(symbol) { return (symbol.flags & 8388608 /* Alias */) && ts.forEach(symbol.declarations, function (declaration) { return declaration.kind === 226 /* ImportSpecifier */ || declaration.kind === 230 /* ExportSpecifier */; }); }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
isImportOrExportSpecifierImportSymbol
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getInternedName(symbol, location, declarations) { // If this is an export or import specifier it could have been renamed using the 'as' syntax. // If so we want to search for whatever under the cursor. if (ts.isImportOrExportSpecifierName(location)) { return location.getText(); } // Try to get the local symbol if we're dealing with an 'export default' // since that symbol has the "true" name. var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); symbol = localExportDefaultSymbol || symbol; return ts.stripQuotes(symbol.name); }
For lack of a better name, this function takes a throw statement and returns the nearest ancestor that is a try-block (whose try statement has a catch clause), function-block, or source file.
getInternedName
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getSymbolScope(symbol) { // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var valueDeclaration = symbol.valueDeclaration; if (valueDeclaration && (valueDeclaration.kind === 173 /* FunctionExpression */ || valueDeclaration.kind === 186 /* ClassExpression */)) { return valueDeclaration; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 16 /* Private */) ? d : undefined; }); if (privateDeclaration) { return ts.getAncestor(privateDeclaration, 214 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. // So consider it visibile outside its declaration scope. if (symbol.flags & 8388608 /* Alias */) { return undefined; } // if this symbol is visible from its parent container, e.g. exported, then bail out // if symbol correspond to the union property - bail out if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { return undefined; } var scope = undefined; var declarations = symbol.getDeclarations(); if (declarations) { for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { var declaration = declarations_8[_i]; var container = getContainerNode(declaration); if (!container) { return undefined; } if (scope && scope !== container) { // Different declarations have different containers, bail out return undefined; } if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; } // The search scope is the container node scope = container; } } return scope; }
Determines the smallest scope in which a symbol may have named references. Note that not every construct has been accounted for. This function can probably be improved. @returns undefined if the scope cannot be determined, implying that a reference to a symbol can occur anywhere.
getSymbolScope
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { var positions = []; /// TODO: Cache symbol existence for files to save text search // Also, need to make this work for unicode escapes. // Be resilient in the face of a symbol with no name or zero length name if (!symbolName || !symbolName.length) { return positions; } var text = sourceFile.text; var sourceLength = text.length; var symbolNameLength = symbolName.length; var position = text.indexOf(symbolName, start); while (position >= 0) { cancellationToken.throwIfCancellationRequested(); // If we are past the end, stop looking if (position > end) break; // We found a match. Make sure it's not part of a larger word (i.e. the char // before and after it have to be a non-identifier char). var endPosition = position + symbolNameLength; if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2 /* Latest */)) && (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2 /* Latest */))) { // Found a real match. Keep searching. positions.push(position); } position = text.indexOf(symbolName, position + symbolNameLength + 1); } return positions; }
Determines the smallest scope in which a symbol may have named references. Note that not every construct has been accounted for. This function can probably be improved. @returns undefined if the scope cannot be determined, implying that a reference to a symbol can occur anywhere.
getPossibleSymbolReferencePositions
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getLabelReferencesInNode(container, targetLabel) { var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); if (!node || node.getWidth() !== labelName.length) { return; } // Only pick labels that are either the target label, or have a target that is the target label if (node === targetLabel || (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel)) { references.push(getReferenceEntryFromNode(node)); } }); var definition = { containerKind: "", containerName: "", fileName: targetLabel.getSourceFile().fileName, kind: ScriptElementKind.label, name: labelName, textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()) }; return [{ definition: definition, references: references }]; }
Determines the smallest scope in which a symbol may have named references. Note that not every construct has been accounted for. This function can probably be improved. @returns undefined if the scope cannot be determined, implying that a reference to a symbol can occur anywhere.
getLabelReferencesInNode
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isValidReferencePosition(node, searchSymbolName) { if (node) { // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node.kind) { case 69 /* Identifier */: return node.getWidth() === searchSymbolName.length; case 9 /* StringLiteral */: if (isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) { // For string literals we have two additional chars for the quotes return node.getWidth() === searchSymbolName.length + 2; } break; case 8 /* NumericLiteral */: if (isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { return node.getWidth() === searchSymbolName.length; } break; } } return false; }
Determines the smallest scope in which a symbol may have named references. Note that not every construct has been accounted for. This function can probably be improved. @returns undefined if the scope cannot be determined, implying that a reference to a symbol can occur anywhere.
isValidReferencePosition
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { var sourceFile = container.getSourceFile(); var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*</; var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, container.getStart(), container.getEnd()); if (possiblePositions.length) { // Build the set of symbols to search for, initially it has only the current symbol var searchSymbols = populateSearchSymbolSet(searchSymbol, searchLocation); ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); if (!isValidReferencePosition(referenceLocation, searchText)) { // This wasn't the start of a token. Check to see if it might be a // match in a comment or string if that's what the caller is asking // for. if ((findInStrings && ts.isInString(sourceFile, position)) || (findInComments && isInNonReferenceComment(sourceFile, position))) { // In the case where we're looking inside comments/strings, we don't have // an actual definition. So just use 'undefined' here. Features like // 'Rename' won't care (as they ignore the definitions), and features like // 'FindReferences' will just filter out these results. result.push({ definition: undefined, references: [{ fileName: sourceFile.fileName, textSpan: ts.createTextSpan(position, searchText.length), isWriteAccess: false }] }); } return; } if (!(getMeaningFromLocation(referenceLocation) & searchMeaning)) { return; } var referenceSymbol = typeChecker.getSymbolAtLocation(referenceLocation); if (referenceSymbol) { var referenceSymbolDeclaration = referenceSymbol.valueDeclaration; var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); var relatedSymbol = getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation); if (relatedSymbol) { var referencedSymbol = getReferencedSymbol(relatedSymbol); referencedSymbol.references.push(getReferenceEntryFromNode(referenceLocation)); } else if (!(referenceSymbol.flags & 67108864 /* Transient */) && searchSymbols.indexOf(shorthandValueSymbol) >= 0) { var referencedSymbol = getReferencedSymbol(shorthandValueSymbol); referencedSymbol.references.push(getReferenceEntryFromNode(referenceSymbolDeclaration.name)); } } }); } return; function getReferencedSymbol(symbol) { var symbolId = ts.getSymbolId(symbol); var index = symbolToIndex[symbolId]; if (index === undefined) { index = result.length; symbolToIndex[symbolId] = index; result.push({ definition: getDefinition(symbol), references: [] }); } return result[index]; } function isInNonReferenceComment(sourceFile, position) { return ts.isInCommentHelper(sourceFile, position, isNonReferenceComment); function isNonReferenceComment(c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); } } }
Search within node "container" for references for a search value, where the search value is defined as a tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). searchLocation: a node where the search value
getReferencesInNode
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getReferencedSymbol(symbol) { var symbolId = ts.getSymbolId(symbol); var index = symbolToIndex[symbolId]; if (index === undefined) { index = result.length; symbolToIndex[symbolId] = index; result.push({ definition: getDefinition(symbol), references: [] }); } return result[index]; }
Search within node "container" for references for a search value, where the search value is defined as a tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). searchLocation: a node where the search value
getReferencedSymbol
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isInNonReferenceComment(sourceFile, position) { return ts.isInCommentHelper(sourceFile, position, isNonReferenceComment); function isNonReferenceComment(c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); } }
Search within node "container" for references for a search value, where the search value is defined as a tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). searchLocation: a node where the search value
isInNonReferenceComment
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isNonReferenceComment(c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); }
Search within node "container" for references for a search value, where the search value is defined as a tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). searchLocation: a node where the search value
isNonReferenceComment
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getReferencesForSuperKeyword(superKeyword) { var searchSpaceNode = ts.getSuperContainer(superKeyword, /*includeFunctions*/ false); if (!searchSpaceNode) { return undefined; } // Whether 'super' occurs in a static context within a class. var staticFlag = 64 /* Static */; switch (searchSpaceNode.kind) { case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; default: return undefined; } var references = []; var sourceFile = searchSpaceNode.getSourceFile(); var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); if (!node || node.kind !== 95 /* SuperKeyword */) { return; } var container = ts.getSuperContainer(node, /*includeFunctions*/ false); // If we have a 'super' container, we must have an enclosing class. // Now make sure the owning class is the same as the search-space // and has the same static qualifier as the original 'super's owner. if (container && (64 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { references.push(getReferenceEntryFromNode(node)); } }); var definition = getDefinition(searchSpaceNode.symbol); return [{ definition: definition, references: references }]; }
Search within node "container" for references for a search value, where the search value is defined as a tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). searchLocation: a node where the search value
getReferencesForSuperKeyword
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. var staticFlag = 64 /* Static */; switch (searchSpaceNode.kind) { case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // fall through case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; case 248 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // Fall through case 213 /* FunctionDeclaration */: case 173 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. default: return undefined; } var references = []; var possiblePositions; if (searchSpaceNode.kind === 248 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { var sourceFile = searchSpaceNode.getSourceFile(); possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } return [{ definition: { containerKind: "", containerName: "", fileName: node.getSourceFile().fileName, kind: ScriptElementKind.variableElement, name: "this", textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()) }, references: references }]; function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); if (!node || node.kind !== 97 /* ThisKeyword */) { return; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { case 173 /* FunctionExpression */: case 213 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; case 186 /* ClassExpression */: case 214 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 64 /* Static */) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; case 248 /* SourceFile */: if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; } }); } }
Search within node "container" for references for a search value, where the search value is defined as a tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). searchLocation: a node where the search value
getReferencesForThisKeyword
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); if (!node || node.kind !== 97 /* ThisKeyword */) { return; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { case 173 /* FunctionExpression */: case 213 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; case 186 /* ClassExpression */: case 214 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 64 /* Static */) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; case 248 /* SourceFile */: if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; } }); }
Search within node "container" for references for a search value, where the search value is defined as a tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). searchLocation: a node where the search value
getThisReferencesInFile
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function populateSearchSymbolSet(symbol, location) { // The search set contains at least the current symbol var result = [symbol]; // If the symbol is an alias, add what it alaises to the list if (isImportOrExportSpecifierImportSymbol(symbol)) { result.push(typeChecker.getAliasedSymbol(symbol)); } // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set if (isNameOfPropertyAssignment(location)) { ts.forEach(getPropertySymbolsFromContextualType(location), function (contextualSymbol) { ts.addRange(result, typeChecker.getRootSymbols(contextualSymbol)); }); /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service * should show both 'name' in 'obj' and 'name' in variable declaration * let name = "Foo"; * let obj = { name }; * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(location.parent); if (shorthandValueSymbol) { result.push(shorthandValueSymbol); } } // If this is a union property, add all the symbols from all its source symbols in all unioned types. // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { if (rootSymbol !== symbol) { result.push(rootSymbol); } // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result); } }); return result; }
Search within node "container" for references for a search value, where the search value is defined as a tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). searchLocation: a node where the search value
populateSearchSymbolSet
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getPropertySymbolsFromBaseTypes(symbol, propertyName, result) { if (symbol && symbol.flags & (32 /* Class */ | 64 /* Interface */)) { ts.forEach(symbol.getDeclarations(), function (declaration) { if (declaration.kind === 214 /* ClassDeclaration */) { getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } else if (declaration.kind === 215 /* InterfaceDeclaration */) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); } return; function getPropertySymbolFromTypeReference(typeReference) { if (typeReference) { var type = typeChecker.getTypeAtLocation(typeReference); if (type) { var propertySymbol = typeChecker.getPropertyOfType(type, propertyName); if (propertySymbol) { result.push(propertySymbol); } // Visit the typeReference as well to see if it directly or indirectly use that property getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result); } } } }
Search within node "container" for references for a search value, where the search value is defined as a tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). searchLocation: a node where the search value
getPropertySymbolsFromBaseTypes
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getPropertySymbolFromTypeReference(typeReference) { if (typeReference) { var type = typeChecker.getTypeAtLocation(typeReference); if (type) { var propertySymbol = typeChecker.getPropertyOfType(type, propertyName); if (propertySymbol) { result.push(propertySymbol); } // Visit the typeReference as well to see if it directly or indirectly use that property getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result); } } }
Search within node "container" for references for a search value, where the search value is defined as a tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). searchLocation: a node where the search value
getPropertySymbolFromTypeReference
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation) { if (searchSymbols.indexOf(referenceSymbol) >= 0) { return referenceSymbol; } // If the reference symbol is an alias, check if what it is aliasing is one of the search // symbols. if (isImportOrExportSpecifierImportSymbol(referenceSymbol)) { var aliasedSymbol = typeChecker.getAliasedSymbol(referenceSymbol); if (searchSymbols.indexOf(aliasedSymbol) >= 0) { return aliasedSymbol; } } // If the reference location is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this symbol to // compare to our searchSymbol if (isNameOfPropertyAssignment(referenceLocation)) { return ts.forEach(getPropertySymbolsFromContextualType(referenceLocation), function (contextualSymbol) { return ts.forEach(typeChecker.getRootSymbols(contextualSymbol), function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); }); } // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) // Or a union property, use its underlying unioned symbols return ts.forEach(typeChecker.getRootSymbols(referenceSymbol), function (rootSymbol) { // if it is in the list, then we are done if (searchSymbols.indexOf(rootSymbol) >= 0) { return rootSymbol; } // Finally, try all properties with the same name in any type the containing type extended or implemented, and // see if any is in the list if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { var result_3 = []; getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_3); return ts.forEach(result_3, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); }
Search within node "container" for references for a search value, where the search value is defined as a tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). searchLocation: a node where the search value
getRelatedSymbol
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getPropertySymbolsFromContextualType(node) { if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); var name_37 = node.text; if (contextualType) { if (contextualType.flags & 16384 /* Union */) { // This is a union type, first see if the property we are looking for is a union property (i.e. exists in all types) // if not, search the constituent types for the property var unionProperty = contextualType.getProperty(name_37); if (unionProperty) { return [unionProperty]; } else { var result_4 = []; ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name_37); if (symbol) { result_4.push(symbol); } }); return result_4; } } else { var symbol_1 = contextualType.getProperty(name_37); if (symbol_1) { return [symbol_1]; } } } } return undefined; }
Search within node "container" for references for a search value, where the search value is defined as a tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). searchLocation: a node where the search value
getPropertySymbolsFromContextualType
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function containErrors(diagnostics) { return ts.forEach(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); }
A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment
containErrors
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getEmitOutput(fileName) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; function writeFile(fileName, data, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: data }); } var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped }; }
A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment
getEmitOutput
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function writeFile(fileName, data, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: data }); }
A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment
writeFile
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getMeaningFromDeclaration(node) { switch (node.kind) { case 138 /* Parameter */: case 211 /* VariableDeclaration */: case 163 /* BindingElement */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: case 245 /* PropertyAssignment */: case 246 /* ShorthandPropertyAssignment */: case 247 /* EnumMember */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 213 /* FunctionDeclaration */: case 173 /* FunctionExpression */: case 174 /* ArrowFunction */: case 244 /* CatchClause */: return 1 /* Value */; case 137 /* TypeParameter */: case 215 /* InterfaceDeclaration */: case 216 /* TypeAliasDeclaration */: case 155 /* TypeLiteral */: return 2 /* Type */; case 214 /* ClassDeclaration */: case 217 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; case 218 /* ModuleDeclaration */: if (node.name.kind === 9 /* StringLiteral */) { return 4 /* Namespace */ | 1 /* Value */; } else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) { return 4 /* Namespace */ | 1 /* Value */; } else { return 4 /* Namespace */; } case 225 /* NamedImports */: case 226 /* ImportSpecifier */: case 221 /* ImportEqualsDeclaration */: case 222 /* ImportDeclaration */: case 227 /* ExportAssignment */: case 228 /* ExportDeclaration */: return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; // An external module can be a Value case 248 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; }
A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment
getMeaningFromDeclaration
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isTypeReference(node) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } return node.parent.kind === 151 /* TypeReference */ || (node.parent.kind === 188 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || node.kind === 97 /* ThisKeyword */ && !ts.isExpression(node); }
A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment
isTypeReference
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); }
A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment
isNamespaceReference
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; if (root.parent.kind === 166 /* PropertyAccessExpression */) { while (root.parent && root.parent.kind === 166 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } if (!isLastClause && root.parent.kind === 188 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 243 /* HeritageClause */) { var decl = root.parent.parent.parent; return (decl.kind === 214 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || (decl.kind === 215 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); } return false; }
A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment
isPropertyAccessNamespaceReference
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; if (root.parent.kind === 135 /* QualifiedName */) { while (root.parent && root.parent.kind === 135 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } return root.parent.kind === 151 /* TypeReference */ && !isLastClause; }
A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment
isQualifiedNameNamespaceReference
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isInRightSideOfImport(node) { while (node.parent.kind === 135 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; }
A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment
isInRightSideOfImport
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getMeaningFromRightHandSideOfImportEquals(node) { ts.Debug.assert(node.kind === 69 /* Identifier */); // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace if (node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node && node.parent.parent.kind === 221 /* ImportEqualsDeclaration */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } return 4 /* Namespace */; }
A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment
getMeaningFromRightHandSideOfImportEquals
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getMeaningFromLocation(node) { if (node.parent.kind === 227 /* ExportAssignment */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } else if (isInRightSideOfImport(node)) { return getMeaningFromRightHandSideOfImportEquals(node); } else if (ts.isDeclarationName(node)) { return getMeaningFromDeclaration(node.parent); } else if (isTypeReference(node)) { return 2 /* Type */; } else if (isNamespaceReference(node)) { return 4 /* Namespace */; } else { return 1 /* Value */; } }
A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment
getMeaningFromLocation
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function processNode(node) { // Only walk into nodes that intersect the requested span. if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { var kind = node.kind; checkForClassificationCancellation(kind); if (kind === 69 /* Identifier */ && !ts.nodeIsMissing(node)) { var identifier = node; // Only bother calling into the typechecker if this is an identifier that // could possibly resolve to a type name. This makes classification run // in a third of the time it would normally take. if (classifiableNames[identifier.text]) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { var type = classifySymbol(symbol, getMeaningFromLocation(node)); if (type) { pushClassification(node.getStart(), node.getWidth(), type); } } } } ts.forEachChild(node, processNode); } }
Returns true if there exists a module that introduces entities on the value side.
processNode
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getClassificationTypeName(type) { switch (type) { case 1 /* comment */: return ClassificationTypeNames.comment; case 2 /* identifier */: return ClassificationTypeNames.identifier; case 3 /* keyword */: return ClassificationTypeNames.keyword; case 4 /* numericLiteral */: return ClassificationTypeNames.numericLiteral; case 5 /* operator */: return ClassificationTypeNames.operator; case 6 /* stringLiteral */: return ClassificationTypeNames.stringLiteral; case 8 /* whiteSpace */: return ClassificationTypeNames.whiteSpace; case 9 /* text */: return ClassificationTypeNames.text; case 10 /* punctuation */: return ClassificationTypeNames.punctuation; case 11 /* className */: return ClassificationTypeNames.className; case 12 /* enumName */: return ClassificationTypeNames.enumName; case 13 /* interfaceName */: return ClassificationTypeNames.interfaceName; case 14 /* moduleName */: return ClassificationTypeNames.moduleName; case 15 /* typeParameterName */: return ClassificationTypeNames.typeParameterName; case 16 /* typeAliasName */: return ClassificationTypeNames.typeAliasName; case 17 /* parameterName */: return ClassificationTypeNames.parameterName; case 18 /* docCommentTagName */: return ClassificationTypeNames.docCommentTagName; case 19 /* jsxOpenTagName */: return ClassificationTypeNames.jsxOpenTagName; case 20 /* jsxCloseTagName */: return ClassificationTypeNames.jsxCloseTagName; case 21 /* jsxSelfClosingTagName */: return ClassificationTypeNames.jsxSelfClosingTagName; } }
Returns true if there exists a module that introduces entities on the value side.
getClassificationTypeName
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function convertClassifications(classifications) { ts.Debug.assert(classifications.spans.length % 3 === 0); var dense = classifications.spans; var result = []; for (var i = 0, n = dense.length; i < n; i += 3) { result.push({ textSpan: ts.createTextSpan(dense[i], dense[i + 1]), classificationType: getClassificationTypeName(dense[i + 2]) }); } return result; }
Returns true if there exists a module that introduces entities on the value side.
convertClassifications
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getSyntacticClassifications(fileName, span) { return convertClassifications(getEncodedSyntacticClassifications(fileName, span)); }
Returns true if there exists a module that introduces entities on the value side.
getSyntacticClassifications
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getEncodedSyntacticClassifications(fileName, span) { // doesn't use compiler - no need to synchronize with host var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var spanStart = span.start; var spanLength = span.length; // Make a scanner we can get trivia from. var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia:*/ false, sourceFile.languageVariant, sourceFile.text); var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia:*/ false, sourceFile.languageVariant, sourceFile.text); var result = []; processElement(sourceFile); return { spans: result, endOfLineState: 0 /* None */ }; function pushClassification(start, length, type) { result.push(start); result.push(length); result.push(type); } function classifyLeadingTriviaAndGetTokenStart(token) { triviaScanner.setTextPos(token.pos); while (true) { var start = triviaScanner.getTextPos(); // only bother scanning if we have something that could be trivia. if (!ts.couldStartTrivia(sourceFile.text, start)) { return start; } var kind = triviaScanner.scan(); var end = triviaScanner.getTextPos(); var width = end - start; // The moment we get something that isn't trivia, then stop processing. if (!ts.isTrivia(kind)) { return start; } // Don't bother with newlines/whitespace. if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { continue; } // Only bother with the trivia if it at least intersects the span of interest. if (ts.isComment(kind)) { classifyComment(token, kind, start, width); // Classifying a comment might cause us to reuse the trivia scanner // (because of jsdoc comments). So after we classify the comment make // sure we set the scanner position back to where it needs to be. triviaScanner.setTextPos(end); continue; } if (kind === 7 /* ConflictMarkerTrivia */) { var text = sourceFile.text; var ch = text.charCodeAt(start); // for the <<<<<<< and >>>>>>> markers, we just add them in as comments // in the classification stream. if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { pushClassification(start, width, 1 /* comment */); continue; } // for the ======== add a comment for the first line, and then lex all // subsequent lines up until the end of the conflict marker. ts.Debug.assert(ch === 61 /* equals */); classifyDisabledMergeCode(text, start, end); } } } function classifyComment(token, kind, start, width) { if (kind === 3 /* MultiLineCommentTrivia */) { // See if this is a doc comment. If so, we'll classify certain portions of it // specially. var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDocComment) { docCommentAndDiagnostics.jsDocComment.parent = token; classifyJSDocComment(docCommentAndDiagnostics.jsDocComment); return; } } // Simple comment. Just add as is. pushCommentRange(start, width); } function pushCommentRange(start, width) { pushClassification(start, width, 1 /* comment */); } function classifyJSDocComment(docComment) { var pos = docComment.pos; for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { var tag = _a[_i]; // As we walk through each tag, classify the portion of text from the end of // the last tag (or the start of the entire doc comment) as 'comment'. if (tag.pos !== pos) { pushCommentRange(pos, tag.pos - pos); } pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); pos = tag.tagName.end; switch (tag.kind) { case 267 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; case 270 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); break; case 269 /* JSDocTypeTag */: processElement(tag.typeExpression); break; case 268 /* JSDocReturnTag */: processElement(tag.typeExpression); break; } pos = tag.end; } if (pos !== docComment.end) { pushCommentRange(pos, docComment.end - pos); } return; function processJSDocParameterTag(tag) { if (tag.preParameterName) { pushCommentRange(pos, tag.preParameterName.pos - pos); pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17 /* parameterName */); pos = tag.preParameterName.end; } if (tag.typeExpression) { pushCommentRange(pos, tag.typeExpression.pos - pos); processElement(tag.typeExpression); pos = tag.typeExpression.end; } if (tag.postParameterName) { pushCommentRange(pos, tag.postParameterName.pos - pos); pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17 /* parameterName */); pos = tag.postParameterName.end; } } } function processJSDocTemplateTag(tag) { for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { var child = _a[_i]; processElement(child); } } function classifyDisabledMergeCode(text, start, end) { // Classify the line that the ======= marker is on as a comment. Then just lex // all further tokens and add them to the result. for (var i = start; i < end; i++) { if (ts.isLineBreak(text.charCodeAt(i))) { break; } } pushClassification(start, i - start, 1 /* comment */); mergeConflictScanner.setTextPos(i); while (mergeConflictScanner.getTextPos() < end) { classifyDisabledCodeToken(); } } function classifyDisabledCodeToken() { var start = mergeConflictScanner.getTextPos(); var tokenKind = mergeConflictScanner.scan(); var end = mergeConflictScanner.getTextPos(); var type = classifyTokenType(tokenKind); if (type) { pushClassification(start, end - start, type); } } function classifyToken(token) { if (ts.nodeIsMissing(token)) { return; } var tokenStart = classifyLeadingTriviaAndGetTokenStart(token); var tokenWidth = token.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { var type = classifyTokenType(token.kind, token); if (type) { pushClassification(tokenStart, tokenWidth, type); } } } // for accurate classification, the actual token should be passed in. however, for // cases like 'disabled merge code' classification, we just get the token kind and // classify based on that instead. function classifyTokenType(tokenKind, token) { if (ts.isKeyword(tokenKind)) { return 3 /* keyword */; } // Special case < and > If they appear in a generic context they are punctuation, // not operators. if (tokenKind === 25 /* LessThanToken */ || tokenKind === 27 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then // we can effectively assume that a '<' and '>' belong to those lists. if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { return 10 /* punctuation */; } } if (ts.isPunctuation(tokenKind)) { if (token) { if (tokenKind === 56 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. if (token.parent.kind === 211 /* VariableDeclaration */ || token.parent.kind === 141 /* PropertyDeclaration */ || token.parent.kind === 138 /* Parameter */) { return 5 /* operator */; } } if (token.parent.kind === 181 /* BinaryExpression */ || token.parent.kind === 179 /* PrefixUnaryExpression */ || token.parent.kind === 180 /* PostfixUnaryExpression */ || token.parent.kind === 182 /* ConditionalExpression */) { return 5 /* operator */; } } return 10 /* punctuation */; } else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } else if (tokenKind === 9 /* StringLiteral */) { return 6 /* stringLiteral */; } else if (tokenKind === 10 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. return 6 /* stringLiteral */; } else if (ts.isTemplateLiteralKind(tokenKind)) { // TODO (drosen): we should *also* get another classification type for these literals. return 6 /* stringLiteral */; } else if (tokenKind === 69 /* Identifier */) { if (token) { switch (token.parent.kind) { case 214 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; case 137 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; case 215 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; case 217 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; case 218 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; case 138 /* Parameter */: if (token.parent.name === token) { return 17 /* parameterName */; } return; case 235 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } return; case 237 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } return; case 234 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } return; } } return 2 /* identifier */; } } function processElement(element) { if (!element) { return; } // Ignore nodes that don't intersect the original span to classify. if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { checkForClassificationCancellation(element.kind); var children = element.getChildren(sourceFile); for (var i = 0, n = children.length; i < n; i++) { var child = children[i]; if (ts.isToken(child)) { classifyToken(child); } else { // Recurse into our child nodes. processElement(child); } } } } }
Returns true if there exists a module that introduces entities on the value side.
getEncodedSyntacticClassifications
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function pushClassification(start, length, type) { result.push(start); result.push(length); result.push(type); }
Returns true if there exists a module that introduces entities on the value side.
pushClassification
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function classifyLeadingTriviaAndGetTokenStart(token) { triviaScanner.setTextPos(token.pos); while (true) { var start = triviaScanner.getTextPos(); // only bother scanning if we have something that could be trivia. if (!ts.couldStartTrivia(sourceFile.text, start)) { return start; } var kind = triviaScanner.scan(); var end = triviaScanner.getTextPos(); var width = end - start; // The moment we get something that isn't trivia, then stop processing. if (!ts.isTrivia(kind)) { return start; } // Don't bother with newlines/whitespace. if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { continue; } // Only bother with the trivia if it at least intersects the span of interest. if (ts.isComment(kind)) { classifyComment(token, kind, start, width); // Classifying a comment might cause us to reuse the trivia scanner // (because of jsdoc comments). So after we classify the comment make // sure we set the scanner position back to where it needs to be. triviaScanner.setTextPos(end); continue; } if (kind === 7 /* ConflictMarkerTrivia */) { var text = sourceFile.text; var ch = text.charCodeAt(start); // for the <<<<<<< and >>>>>>> markers, we just add them in as comments // in the classification stream. if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { pushClassification(start, width, 1 /* comment */); continue; } // for the ======== add a comment for the first line, and then lex all // subsequent lines up until the end of the conflict marker. ts.Debug.assert(ch === 61 /* equals */); classifyDisabledMergeCode(text, start, end); } } }
Returns true if there exists a module that introduces entities on the value side.
classifyLeadingTriviaAndGetTokenStart
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function classifyComment(token, kind, start, width) { if (kind === 3 /* MultiLineCommentTrivia */) { // See if this is a doc comment. If so, we'll classify certain portions of it // specially. var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDocComment) { docCommentAndDiagnostics.jsDocComment.parent = token; classifyJSDocComment(docCommentAndDiagnostics.jsDocComment); return; } } // Simple comment. Just add as is. pushCommentRange(start, width); }
Returns true if there exists a module that introduces entities on the value side.
classifyComment
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function pushCommentRange(start, width) { pushClassification(start, width, 1 /* comment */); }
Returns true if there exists a module that introduces entities on the value side.
pushCommentRange
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function classifyJSDocComment(docComment) { var pos = docComment.pos; for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { var tag = _a[_i]; // As we walk through each tag, classify the portion of text from the end of // the last tag (or the start of the entire doc comment) as 'comment'. if (tag.pos !== pos) { pushCommentRange(pos, tag.pos - pos); } pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); pos = tag.tagName.end; switch (tag.kind) { case 267 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; case 270 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); break; case 269 /* JSDocTypeTag */: processElement(tag.typeExpression); break; case 268 /* JSDocReturnTag */: processElement(tag.typeExpression); break; } pos = tag.end; } if (pos !== docComment.end) { pushCommentRange(pos, docComment.end - pos); } return; function processJSDocParameterTag(tag) { if (tag.preParameterName) { pushCommentRange(pos, tag.preParameterName.pos - pos); pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17 /* parameterName */); pos = tag.preParameterName.end; } if (tag.typeExpression) { pushCommentRange(pos, tag.typeExpression.pos - pos); processElement(tag.typeExpression); pos = tag.typeExpression.end; } if (tag.postParameterName) { pushCommentRange(pos, tag.postParameterName.pos - pos); pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17 /* parameterName */); pos = tag.postParameterName.end; } } }
Returns true if there exists a module that introduces entities on the value side.
classifyJSDocComment
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function processJSDocParameterTag(tag) { if (tag.preParameterName) { pushCommentRange(pos, tag.preParameterName.pos - pos); pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17 /* parameterName */); pos = tag.preParameterName.end; } if (tag.typeExpression) { pushCommentRange(pos, tag.typeExpression.pos - pos); processElement(tag.typeExpression); pos = tag.typeExpression.end; } if (tag.postParameterName) { pushCommentRange(pos, tag.postParameterName.pos - pos); pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17 /* parameterName */); pos = tag.postParameterName.end; } }
Returns true if there exists a module that introduces entities on the value side.
processJSDocParameterTag
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function processJSDocTemplateTag(tag) { for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { var child = _a[_i]; processElement(child); } }
Returns true if there exists a module that introduces entities on the value side.
processJSDocTemplateTag
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function classifyDisabledMergeCode(text, start, end) { // Classify the line that the ======= marker is on as a comment. Then just lex // all further tokens and add them to the result. for (var i = start; i < end; i++) { if (ts.isLineBreak(text.charCodeAt(i))) { break; } } pushClassification(start, i - start, 1 /* comment */); mergeConflictScanner.setTextPos(i); while (mergeConflictScanner.getTextPos() < end) { classifyDisabledCodeToken(); } }
Returns true if there exists a module that introduces entities on the value side.
classifyDisabledMergeCode
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function classifyDisabledCodeToken() { var start = mergeConflictScanner.getTextPos(); var tokenKind = mergeConflictScanner.scan(); var end = mergeConflictScanner.getTextPos(); var type = classifyTokenType(tokenKind); if (type) { pushClassification(start, end - start, type); } }
Returns true if there exists a module that introduces entities on the value side.
classifyDisabledCodeToken
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function classifyToken(token) { if (ts.nodeIsMissing(token)) { return; } var tokenStart = classifyLeadingTriviaAndGetTokenStart(token); var tokenWidth = token.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { var type = classifyTokenType(token.kind, token); if (type) { pushClassification(tokenStart, tokenWidth, type); } } }
Returns true if there exists a module that introduces entities on the value side.
classifyToken
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function classifyTokenType(tokenKind, token) { if (ts.isKeyword(tokenKind)) { return 3 /* keyword */; } // Special case < and > If they appear in a generic context they are punctuation, // not operators. if (tokenKind === 25 /* LessThanToken */ || tokenKind === 27 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then // we can effectively assume that a '<' and '>' belong to those lists. if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { return 10 /* punctuation */; } } if (ts.isPunctuation(tokenKind)) { if (token) { if (tokenKind === 56 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. if (token.parent.kind === 211 /* VariableDeclaration */ || token.parent.kind === 141 /* PropertyDeclaration */ || token.parent.kind === 138 /* Parameter */) { return 5 /* operator */; } } if (token.parent.kind === 181 /* BinaryExpression */ || token.parent.kind === 179 /* PrefixUnaryExpression */ || token.parent.kind === 180 /* PostfixUnaryExpression */ || token.parent.kind === 182 /* ConditionalExpression */) { return 5 /* operator */; } } return 10 /* punctuation */; } else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } else if (tokenKind === 9 /* StringLiteral */) { return 6 /* stringLiteral */; } else if (tokenKind === 10 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. return 6 /* stringLiteral */; } else if (ts.isTemplateLiteralKind(tokenKind)) { // TODO (drosen): we should *also* get another classification type for these literals. return 6 /* stringLiteral */; } else if (tokenKind === 69 /* Identifier */) { if (token) { switch (token.parent.kind) { case 214 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; case 137 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; case 215 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; case 217 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; case 218 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; case 138 /* Parameter */: if (token.parent.name === token) { return 17 /* parameterName */; } return; case 235 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } return; case 237 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } return; case 234 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } return; } } return 2 /* identifier */; } }
Returns true if there exists a module that introduces entities on the value side.
classifyTokenType
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function processElement(element) { if (!element) { return; } // Ignore nodes that don't intersect the original span to classify. if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { checkForClassificationCancellation(element.kind); var children = element.getChildren(sourceFile); for (var i = 0, n = children.length; i < n; i++) { var child = children[i]; if (ts.isToken(child)) { classifyToken(child); } else { // Recurse into our child nodes. processElement(child); } } } }
Returns true if there exists a module that introduces entities on the value side.
processElement
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getOutliningSpans(fileName) { // doesn't use compiler - no need to synchronize with host var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); return ts.OutliningElementsCollector.collectElements(sourceFile); }
Returns true if there exists a module that introduces entities on the value side.
getOutliningSpans
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getBraceMatchingAtPosition(fileName, position) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var result = []; var token = ts.getTouchingToken(sourceFile, position); if (token.getStart(sourceFile) === position) { var matchKind = getMatchingTokenKind(token); // Ensure that there is a corresponding token to match ours. if (matchKind) { var parentElement = token.parent; var childNodes = parentElement.getChildren(sourceFile); for (var _i = 0, childNodes_1 = childNodes; _i < childNodes_1.length; _i++) { var current = childNodes_1[_i]; if (current.kind === matchKind) { var range1 = ts.createTextSpan(token.getStart(sourceFile), token.getWidth(sourceFile)); var range2 = ts.createTextSpan(current.getStart(sourceFile), current.getWidth(sourceFile)); // We want to order the braces when we return the result. if (range1.start < range2.start) { result.push(range1, range2); } else { result.push(range2, range1); } break; } } } } return result; function getMatchingTokenKind(token) { switch (token.kind) { case 15 /* OpenBraceToken */: return 16 /* CloseBraceToken */; case 17 /* OpenParenToken */: return 18 /* CloseParenToken */; case 19 /* OpenBracketToken */: return 20 /* CloseBracketToken */; case 25 /* LessThanToken */: return 27 /* GreaterThanToken */; case 16 /* CloseBraceToken */: return 15 /* OpenBraceToken */; case 18 /* CloseParenToken */: return 17 /* OpenParenToken */; case 20 /* CloseBracketToken */: return 19 /* OpenBracketToken */; case 27 /* GreaterThanToken */: return 25 /* LessThanToken */; } return undefined; } }
Returns true if there exists a module that introduces entities on the value side.
getBraceMatchingAtPosition
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getMatchingTokenKind(token) { switch (token.kind) { case 15 /* OpenBraceToken */: return 16 /* CloseBraceToken */; case 17 /* OpenParenToken */: return 18 /* CloseParenToken */; case 19 /* OpenBracketToken */: return 20 /* CloseBracketToken */; case 25 /* LessThanToken */: return 27 /* GreaterThanToken */; case 16 /* CloseBraceToken */: return 15 /* OpenBraceToken */; case 18 /* CloseParenToken */: return 17 /* OpenParenToken */; case 20 /* CloseBracketToken */: return 19 /* OpenBracketToken */; case 27 /* GreaterThanToken */: return 25 /* LessThanToken */; } return undefined; }
Returns true if there exists a module that introduces entities on the value side.
getMatchingTokenKind
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getIndentationAtPosition(fileName, position, editorOptions) { var start = new Date().getTime(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); log("getIndentationAtPosition: getCurrentSourceFile: " + (new Date().getTime() - start)); start = new Date().getTime(); var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); log("getIndentationAtPosition: computeIndentation : " + (new Date().getTime() - start)); return result; }
Returns true if there exists a module that introduces entities on the value side.
getIndentationAtPosition
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); }
Returns true if there exists a module that introduces entities on the value side.
getFormattingEditsForRange
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); }
Returns true if there exists a module that introduces entities on the value side.
getFormattingEditsForDocument
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); if (key === "}") { return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); } else if (key === ";") { return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); } else if (key === "\n") { return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); } return []; }
Returns true if there exists a module that introduces entities on the value side.
getFormattingEditsAfterKeystroke
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getDocCommentTemplateAtPosition(fileName, position) { var start = new Date().getTime(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Check if in a context where we don't want to perform any insertion if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; } var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); var tokenStart = tokenAtPos.getStart(); if (!tokenAtPos || tokenStart < position) { return undefined; } // TODO: add support for: // - enums/enum members // - interfaces // - property declarations // - potentially property assignments var commentOwner; findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { case 213 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 144 /* Constructor */: case 214 /* ClassDeclaration */: case 193 /* VariableStatement */: break findOwner; case 248 /* SourceFile */: return undefined; case 218 /* ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. if (commentOwner.parent.kind === 218 /* ModuleDeclaration */) { return undefined; } break findOwner; } } if (!commentOwner || commentOwner.getStart() < position) { return undefined; } var parameters = getParametersForJsDocOwningNode(commentOwner); var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); // TODO: call a helper method instead once PR #4133 gets merged in. var newLine = host.getNewLine ? host.getNewLine() : "\r\n"; var docParams = ""; for (var i = 0, numParams = parameters.length; i < numParams; i++) { var currentName = parameters[i].name; var paramName = currentName.kind === 69 /* Identifier */ ? currentName.text : "param" + i; docParams += indentationStr + " * @param " + paramName + newLine; } // A doc comment consists of the following // * The opening comment line // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) // * the '@param'-tagged lines // * TODO: other tags. // * the closing comment line // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + docParams + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; }
Checks if position points to a valid position to add JSDoc comments, and if so, returns the appropriate template. Otherwise returns an empty string. Valid positions are - outside of comments, statements, and expressions, and - preceding a: - function/constructor/method declaration - class declarations - variable statements - namespace declarations Hosts should ideally check that: - The line is all whitespace up to 'position' before performing the insertion. - If the keystroke sequence "/\*\*" induced the call, we also check that the next non-whitespace character is '*', which (approximately) indicates whether we added the second '*' to complete an existing (JSDoc) comment. @param fileName The file in which to perform the check. @param position The (character-indexed) position in the file where the check should be performed.
getDocCommentTemplateAtPosition
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getParametersForJsDocOwningNode(commentOwner) { if (ts.isFunctionLike(commentOwner)) { return commentOwner.parameters; } if (commentOwner.kind === 193 /* VariableStatement */) { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; if (varDeclarations.length === 1 && varDeclarations[0].initializer) { return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer); } } return emptyArray; }
" + newLine + indentationStr + " * "; var result = preamble + newLine + docParams + indentationStr + "
getParametersForJsDocOwningNode
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getTodoComments(fileName, descriptors) { // Note: while getting todo comments seems like a syntactic operation, we actually // treat it as a semantic operation here. This is because we expect our host to call // this on every single file. If we treat this syntactically, then that will cause // us to populate and throw away the tree in our syntax tree cache for each file. By // treating this as a semantic operation, we can access any tree without throwing // anything away. synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); cancellationToken.throwIfCancellationRequested(); var fileContents = sourceFile.text; var result = []; if (descriptors.length > 0) { var regExp = getTodoCommentsRegExp(); var matchArray; while (matchArray = regExp.exec(fileContents)) { cancellationToken.throwIfCancellationRequested(); // If we got a match, here is what the match array will look like. Say the source text is: // // " // hack 1" // // The result array with the regexp: will be: // // ["// hack 1", "// ", "hack 1", undefined, "hack"] // // Here are the relevant capture groups: // 0) The full match for the entire regexp. // 1) The preamble to the message portion. // 2) The message portion. // 3...N) The descriptor that was matched - by index. 'undefined' for each // descriptor that didn't match. an actual value if it did match. // // i.e. 'undefined' in position 3 above means TODO(jason) didn't match. // "hack" in position 4 means HACK did match. var firstDescriptorCaptureIndex = 3; ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); var preamble = matchArray[1]; var matchPosition = matchArray.index + preamble.length; // OK, we have found a match in the file. This is only an acceptable match if // it is contained within a comment. var token = ts.getTokenAtPosition(sourceFile, matchPosition); if (!isInsideComment(sourceFile, token, matchPosition)) { continue; } var descriptor = undefined; for (var i = 0, n = descriptors.length; i < n; i++) { if (matchArray[i + firstDescriptorCaptureIndex]) { descriptor = descriptors[i]; } } ts.Debug.assert(descriptor !== undefined); // We don't want to match something like 'TODOBY', so we make sure a non // letter/digit follows the match. if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) { continue; } var message = matchArray[2]; result.push({ descriptor: descriptor, message: message, position: matchPosition }); } } return result; function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } function getTodoCommentsRegExp() { // NOTE: ?: means 'non-capture group'. It allows us to have groups without having to // filter them out later in the final result array. // TODO comments can appear in one of the following forms: // // 1) // TODO or /////////// TODO // // 2) /* TODO or /********** TODO // // 3) /* // * TODO // */ // // The following three regexps are used to match the start of the text up to the TODO // comment portion. var singleLineCommentStart = /(?:\/\/+\s*)/.source; var multiLineCommentStart = /(?:\/\*+\s*)/.source; var anyNumberOfSpacesAndAsterixesAtStartOfLine = /(?:^(?:\s|\*)*)/.source; // Match any of the above three TODO comment start regexps. // Note that the outermost group *is* a capture group. We want to capture the preamble // so that we can determine the starting position of the TODO comment match. var preamble = "(" + anyNumberOfSpacesAndAsterixesAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; // Takes the descriptors and forms a regexp that matches them as if they were literals. // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be: // // (?:(TODO\(jason\))|(HACK)) // // Note that the outermost group is *not* a capture group, but the innermost groups // *are* capture groups. By capturing the inner literals we can determine after // matching which descriptor we are dealing with. var literals = "(?:" + ts.map(descriptors, function (d) { return "(" + escapeRegExp(d.text) + ")"; }).join("|") + ")"; // After matching a descriptor literal, the following regexp matches the rest of the // text up to the end of the line (or */). var endOfLineOrEndOfComment = /(?:$|\*\/)/.source; var messageRemainder = /(?:.*?)/.source; // This is the portion of the match we'll return as part of the TODO comment result. We // match the literal portion up to the end of the line or end of comment. var messagePortion = "(" + literals + messageRemainder + ")"; var regExpString = preamble + messagePortion + endOfLineOrEndOfComment; // The final regexp will look like this: // /((?:\/\/+\s*)|(?:\/\*+\s*)|(?:^(?:\s|\*)*))((?:(TODO\(jason\))|(HACK))(?:.*?))(?:$|\*\/)/gim // The flags of the regexp are important here. // 'g' is so that we are doing a global search and can find matches several times // in the input. // // 'i' is for case insensitivity (We do this to match C# TODO comment code). // // 'm' is so we can find matches in a multi-line input. return new RegExp(regExpString, "gim"); } function isLetterOrDigit(char) { return (char >= 97 /* a */ && char <= 122 /* z */) || (char >= 65 /* A */ && char <= 90 /* Z */) || (char >= 48 /* _0 */ && char <= 57 /* _9 */); } }
Digs into an an initializer or RHS operand of an assignment operation to get the parameters of an apt signature corresponding to a function expression or a class expression. @param rightHandSide the expression which may contain an appropriate set of parameters @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'.
getTodoComments
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); }
Digs into an an initializer or RHS operand of an assignment operation to get the parameters of an apt signature corresponding to a function expression or a class expression. @param rightHandSide the expression which may contain an appropriate set of parameters @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'.
escapeRegExp
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getTodoCommentsRegExp() { // NOTE: ?: means 'non-capture group'. It allows us to have groups without having to // filter them out later in the final result array. // TODO comments can appear in one of the following forms: // // 1) // TODO or /////////// TODO // // 2) /* TODO or /********** TODO // // 3) /* // * TODO // */ // // The following three regexps are used to match the start of the text up to the TODO // comment portion. var singleLineCommentStart = /(?:\/\/+\s*)/.source; var multiLineCommentStart = /(?:\/\*+\s*)/.source; var anyNumberOfSpacesAndAsterixesAtStartOfLine = /(?:^(?:\s|\*)*)/.source; // Match any of the above three TODO comment start regexps. // Note that the outermost group *is* a capture group. We want to capture the preamble // so that we can determine the starting position of the TODO comment match. var preamble = "(" + anyNumberOfSpacesAndAsterixesAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; // Takes the descriptors and forms a regexp that matches them as if they were literals. // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be: // // (?:(TODO\(jason\))|(HACK)) // // Note that the outermost group is *not* a capture group, but the innermost groups // *are* capture groups. By capturing the inner literals we can determine after // matching which descriptor we are dealing with. var literals = "(?:" + ts.map(descriptors, function (d) { return "(" + escapeRegExp(d.text) + ")"; }).join("|") + ")"; // After matching a descriptor literal, the following regexp matches the rest of the // text up to the end of the line (or */). var endOfLineOrEndOfComment = /(?:$|\*\/)/.source; var messageRemainder = /(?:.*?)/.source; // This is the portion of the match we'll return as part of the TODO comment result. We // match the literal portion up to the end of the line or end of comment. var messagePortion = "(" + literals + messageRemainder + ")"; var regExpString = preamble + messagePortion + endOfLineOrEndOfComment; // The final regexp will look like this: // /((?:\/\/+\s*)|(?:\/\*+\s*)|(?:^(?:\s|\*)*))((?:(TODO\(jason\))|(HACK))(?:.*?))(?:$|\*\/)/gim // The flags of the regexp are important here. // 'g' is so that we are doing a global search and can find matches several times // in the input. // // 'i' is for case insensitivity (We do this to match C# TODO comment code). // // 'm' is so we can find matches in a multi-line input. return new RegExp(regExpString, "gim"); }
Digs into an an initializer or RHS operand of an assignment operation to get the parameters of an apt signature corresponding to a function expression or a class expression. @param rightHandSide the expression which may contain an appropriate set of parameters @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'.
getTodoCommentsRegExp
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { if (keyword2 === 123 /* GetKeyword */ || keyword2 === 129 /* SetKeyword */ || keyword2 === 121 /* ConstructorKeyword */ || keyword2 === 113 /* StaticKeyword */) { // Allow things like "public get", "public constructor" and "public static". // These are all legal. return true; } // Any other keyword following "public" is actually an identifier an not a real // keyword. return false; } // Assume any other keyword combination is legal. This can be refined in the future // if there are more cases we want the classifier to be better at. return true; }
Returns true if 'keyword2' can legally follow 'keyword1' in any language construct.
canFollow
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function convertClassifications(classifications, text) { var entries = []; var dense = classifications.spans; var lastEnd = 0; for (var i = 0, n = dense.length; i < n; i += 3) { var start = dense[i]; var length_3 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; if (whitespaceLength_1 > 0) { entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); } } entries.push({ length: length_3, classification: convertClassification(type) }); lastEnd = start + length_3; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { entries.push({ length: whitespaceLength, classification: TokenClass.Whitespace }); } return { entries: entries, finalLexState: classifications.endOfLineState }; }
Returns true if 'keyword2' can legally follow 'keyword1' in any language construct.
convertClassifications
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function convertClassification(type) { switch (type) { case 1 /* comment */: return TokenClass.Comment; case 3 /* keyword */: return TokenClass.Keyword; case 4 /* numericLiteral */: return TokenClass.NumberLiteral; case 5 /* operator */: return TokenClass.Operator; case 6 /* stringLiteral */: return TokenClass.StringLiteral; case 8 /* whiteSpace */: return TokenClass.Whitespace; case 10 /* punctuation */: return TokenClass.Punctuation; case 2 /* identifier */: case 11 /* className */: case 12 /* enumName */: case 13 /* interfaceName */: case 14 /* moduleName */: case 15 /* typeParameterName */: case 16 /* typeAliasName */: case 9 /* text */: case 17 /* parameterName */: default: return TokenClass.Identifier; } }
Returns true if 'keyword2' can legally follow 'keyword1' in any language construct.
convertClassification
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { return convertClassifications(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); }
Returns true if 'keyword2' can legally follow 'keyword1' in any language construct.
getClassificationsForLine
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { var offset = 0; var token = 0 /* Unknown */; var lastNonTriviaToken = 0 /* Unknown */; // Empty out the template stack for reuse. while (templateStack.length > 0) { templateStack.pop(); } // If we're in a string literal, then prepend: "\ // (and a newline). That way when we lex we'll think we're still in a string literal. // // If we're in a multiline comment, then prepend: /* // (and a newline). That way when we lex we'll think we're still in a multiline comment. switch (lexState) { case 3 /* InDoubleQuoteStringLiteral */: text = '"\\\n' + text; offset = 3; break; case 2 /* InSingleQuoteStringLiteral */: text = "'\\\n" + text; offset = 3; break; case 1 /* InMultiLineCommentTrivia */: text = "/*\n" + text; offset = 3; break; case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: text = "`\n" + text; offset = 2; break; case 5 /* InTemplateMiddleOrTail */: text = "}\n" + text; offset = 2; // fallthrough case 6 /* InTemplateSubstitutionPosition */: templateStack.push(12 /* TemplateHead */); break; } scanner.setText(text); var result = { endOfLineState: 0 /* None */, spans: [] }; // We can run into an unfortunate interaction between the lexical and syntactic classifier // when the user is typing something generic. Consider the case where the user types: // // Foo<number // // From the lexical classifier's perspective, 'number' is a keyword, and so the word will // be classified as such. However, from the syntactic classifier's tree-based perspective // this is simply an expression with the identifier 'number' on the RHS of the less than // token. So the classification will go back to being an identifier. The moment the user // types again, number will become a keyword, then an identifier, etc. etc. // // To try to avoid this problem, we avoid classifying contextual keywords as keywords // when the user is potentially typing something generic. We just can't do a good enough // job at the lexical level, and so well leave it up to the syntactic classifier to make // the determination. // // In order to determine if the user is potentially typing something generic, we use a // weak heuristic where we track < and > tokens. It's a weak heuristic, but should // work well enough in practice. var angleBracketStack = 0; do { token = scanner.scan(); if (!ts.isTrivia(token)) { if ((token === 39 /* SlashToken */ || token === 61 /* SlashEqualsToken */) && !noRegexTable[lastNonTriviaToken]) { if (scanner.reScanSlashToken() === 10 /* RegularExpressionLiteral */) { token = 10 /* RegularExpressionLiteral */; } } else if (lastNonTriviaToken === 21 /* DotToken */ && isKeyword(token)) { token = 69 /* Identifier */; } else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { // We have two keywords in a row. Only treat the second as a keyword if // it's a sequence that could legally occur in the language. Otherwise // treat it as an identifier. This way, if someone writes "private var" // we recognize that 'var' is actually an identifier here. token = 69 /* Identifier */; } else if (lastNonTriviaToken === 69 /* Identifier */ && token === 25 /* LessThanToken */) { // Could be the start of something generic. Keep track of that by bumping // up the current count of generic contexts we may be in. angleBracketStack++; } else if (token === 27 /* GreaterThanToken */ && angleBracketStack > 0) { // If we think we're currently in something generic, then mark that that // generic entity is complete. angleBracketStack--; } else if (token === 117 /* AnyKeyword */ || token === 130 /* StringKeyword */ || token === 128 /* NumberKeyword */ || token === 120 /* BooleanKeyword */ || token === 131 /* SymbolKeyword */) { if (angleBracketStack > 0 && !syntacticClassifierAbsent) { // If it looks like we're could be in something generic, don't classify this // as a keyword. We may just get overwritten by the syntactic classifier, // causing a noisy experience for the user. token = 69 /* Identifier */; } } else if (token === 12 /* TemplateHead */) { templateStack.push(token); } else if (token === 15 /* OpenBraceToken */) { // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { templateStack.push(token); } } else if (token === 16 /* CloseBraceToken */) { // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { var lastTemplateStackToken = ts.lastOrUndefined(templateStack); if (lastTemplateStackToken === 12 /* TemplateHead */) { token = scanner.reScanTemplateToken(); // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. if (token === 14 /* TemplateTail */) { templateStack.pop(); } else { ts.Debug.assert(token === 13 /* TemplateMiddle */, "Should have been a template middle. Was " + token); } } else { ts.Debug.assert(lastTemplateStackToken === 15 /* OpenBraceToken */, "Should have been an open brace. Was: " + token); templateStack.pop(); } } } lastNonTriviaToken = token; } processToken(); } while (token !== 1 /* EndOfFileToken */); return result; function processToken() { var start = scanner.getTokenPos(); var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { if (token === 9 /* StringLiteral */) { // Check to see if we finished up on a multiline string literal. var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { var lastCharIndex = tokenText.length - 1; var numBackslashes = 0; while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { numBackslashes++; } // If we have an odd number of backslashes, then the multiline string is unclosed if (numBackslashes & 1) { var quoteChar = tokenText.charCodeAt(0); result.endOfLineState = quoteChar === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */; } } } else if (token === 3 /* MultiLineCommentTrivia */) { // Check to see if the multiline comment was unclosed. if (scanner.isUnterminated()) { result.endOfLineState = 1 /* InMultiLineCommentTrivia */; } } else if (ts.isTemplateLiteralKind(token)) { if (scanner.isUnterminated()) { if (token === 14 /* TemplateTail */) { result.endOfLineState = 5 /* InTemplateMiddleOrTail */; } else if (token === 11 /* NoSubstitutionTemplateLiteral */) { result.endOfLineState = 4 /* InTemplateHeadOrNoSubstitutionTemplate */; } else { ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); } } } else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12 /* TemplateHead */) { result.endOfLineState = 6 /* InTemplateSubstitutionPosition */; } } } function addResult(start, end, classification) { if (classification === 8 /* whiteSpace */) { // Don't bother with whitespace classifications. They're not needed. return; } if (start === 0 && offset > 0) { // We're classifying the first token, and this was a case where we prepended // text. We should consider the start of this token to be at the start of // the original text. start += offset; } // All our tokens are in relation to the augmented text. Move them back to be // relative to the original text. start -= offset; end -= offset; var length = end - start; if (length > 0) { result.spans.push(start); result.spans.push(length); result.spans.push(classification); } } }
Returns true if 'keyword2' can legally follow 'keyword1' in any language construct.
getEncodedLexicalClassifications
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function processToken() { var start = scanner.getTokenPos(); var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { if (token === 9 /* StringLiteral */) { // Check to see if we finished up on a multiline string literal. var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { var lastCharIndex = tokenText.length - 1; var numBackslashes = 0; while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { numBackslashes++; } // If we have an odd number of backslashes, then the multiline string is unclosed if (numBackslashes & 1) { var quoteChar = tokenText.charCodeAt(0); result.endOfLineState = quoteChar === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */; } } } else if (token === 3 /* MultiLineCommentTrivia */) { // Check to see if the multiline comment was unclosed. if (scanner.isUnterminated()) { result.endOfLineState = 1 /* InMultiLineCommentTrivia */; } } else if (ts.isTemplateLiteralKind(token)) { if (scanner.isUnterminated()) { if (token === 14 /* TemplateTail */) { result.endOfLineState = 5 /* InTemplateMiddleOrTail */; } else if (token === 11 /* NoSubstitutionTemplateLiteral */) { result.endOfLineState = 4 /* InTemplateHeadOrNoSubstitutionTemplate */; } else { ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); } } } else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12 /* TemplateHead */) { result.endOfLineState = 6 /* InTemplateSubstitutionPosition */; } } }
Returns true if 'keyword2' can legally follow 'keyword1' in any language construct.
processToken
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function addResult(start, end, classification) { if (classification === 8 /* whiteSpace */) { // Don't bother with whitespace classifications. They're not needed. return; } if (start === 0 && offset > 0) { // We're classifying the first token, and this was a case where we prepended // text. We should consider the start of this token to be at the start of // the original text. start += offset; } // All our tokens are in relation to the augmented text. Move them back to be // relative to the original text. start -= offset; end -= offset; var length = end - start; if (length > 0) { result.spans.push(start); result.spans.push(length); result.spans.push(classification); } }
Returns true if 'keyword2' can legally follow 'keyword1' in any language construct.
addResult
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isBinaryExpressionOperatorToken(token) { switch (token) { case 37 /* AsteriskToken */: case 39 /* SlashToken */: case 40 /* PercentToken */: case 35 /* PlusToken */: case 36 /* MinusToken */: case 43 /* LessThanLessThanToken */: case 44 /* GreaterThanGreaterThanToken */: case 45 /* GreaterThanGreaterThanGreaterThanToken */: case 25 /* LessThanToken */: case 27 /* GreaterThanToken */: case 28 /* LessThanEqualsToken */: case 29 /* GreaterThanEqualsToken */: case 91 /* InstanceOfKeyword */: case 90 /* InKeyword */: case 116 /* AsKeyword */: case 30 /* EqualsEqualsToken */: case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: case 46 /* AmpersandToken */: case 48 /* CaretToken */: case 47 /* BarToken */: case 51 /* AmpersandAmpersandToken */: case 52 /* BarBarToken */: case 67 /* BarEqualsToken */: case 66 /* AmpersandEqualsToken */: case 68 /* CaretEqualsToken */: case 63 /* LessThanLessThanEqualsToken */: case 64 /* GreaterThanGreaterThanEqualsToken */: case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: case 57 /* PlusEqualsToken */: case 58 /* MinusEqualsToken */: case 59 /* AsteriskEqualsToken */: case 61 /* SlashEqualsToken */: case 62 /* PercentEqualsToken */: case 56 /* EqualsToken */: case 24 /* CommaToken */: return true; default: return false; } }
Returns true if 'keyword2' can legally follow 'keyword1' in any language construct.
isBinaryExpressionOperatorToken
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isPrefixUnaryExpressionOperatorToken(token) { switch (token) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: case 49 /* ExclamationToken */: case 41 /* PlusPlusToken */: case 42 /* MinusMinusToken */: return true; default: return false; } }
Returns true if 'keyword2' can legally follow 'keyword1' in any language construct.
isPrefixUnaryExpressionOperatorToken
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isKeyword(token) { return token >= 70 /* FirstKeyword */ && token <= 134 /* LastKeyword */; }
Returns true if 'keyword2' can legally follow 'keyword1' in any language construct.
isKeyword
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function classFromKind(token) { if (isKeyword(token)) { return 3 /* keyword */; } else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { return 5 /* operator */; } else if (token >= 15 /* FirstPunctuation */ && token <= 68 /* LastPunctuation */) { return 10 /* punctuation */; } switch (token) { case 8 /* NumericLiteral */: return 4 /* numericLiteral */; case 9 /* StringLiteral */: return 6 /* stringLiteral */; case 10 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; case 7 /* ConflictMarkerTrivia */: case 3 /* MultiLineCommentTrivia */: case 2 /* SingleLineCommentTrivia */: return 1 /* comment */; case 5 /* WhitespaceTrivia */: case 4 /* NewLineTrivia */: return 8 /* whiteSpace */; case 69 /* Identifier */: default: if (ts.isTemplateLiteralKind(token)) { return 6 /* stringLiteral */; } return 2 /* identifier */; } }
Returns true if 'keyword2' can legally follow 'keyword1' in any language construct.
classFromKind
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function initializeServices() { ts.objectAllocator = { getNodeConstructor: function () { return NodeObject; }, getSourceFileConstructor: function () { return SourceFileObject; }, getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, getSignatureConstructor: function () { return SignatureObject; } }; }
Get the path of the default library files (lib.d.ts) as distributed with the typescript node package. The functionality is not supported if the ts module is consumed outside of a node module.
initializeServices
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function spanInSourceFileAtLocation(sourceFile, position) { // Cannot set breakpoint in dts file if (sourceFile.flags & 4096 /* DeclarationFile */) { return undefined; } var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart()).line > lineOfPosition) { // Get previous token if the token is returned starts on new line // eg: let x =10; |--- cursor is here // let y = 10; // token at position will return let keyword on second line as the token but we would like to use // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); // Its a blank line if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) { return undefined; } } // Cannot set breakpoint in ambient declarations if (ts.isInAmbientContext(tokenAtLocation)) { return undefined; } // Get the span in the node based on its syntax return spanInNode(tokenAtLocation); function textSpan(startNode, endNode) { return ts.createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd()); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart()).line) { return spanInNode(node); } return spanInNode(otherwiseOnNode); } function spanInPreviousNode(node) { return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); } function spanInNextNode(node) { return spanInNode(ts.findNextToken(node, node.parent)); } function spanInNode(node) { if (node) { if (ts.isExpression(node)) { if (node.parent.kind === 197 /* DoStatement */) { // Set span as if on while keyword return spanInPreviousNode(node); } if (node.parent.kind === 199 /* ForStatement */) { // For now lets set the span on this expression, fix it later return textSpan(node); } if (node.parent.kind === 181 /* BinaryExpression */ && node.parent.operatorToken.kind === 24 /* CommaToken */) { // if this is comma expression, the breakpoint is possible in this expression return textSpan(node); } if (node.parent.kind === 174 /* ArrowFunction */ && node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); } } switch (node.kind) { case 193 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); case 211 /* VariableDeclaration */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: return spanInVariableDeclaration(node); case 138 /* Parameter */: return spanInParameterDeclaration(node); case 213 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 144 /* Constructor */: case 173 /* FunctionExpression */: case 174 /* ArrowFunction */: return spanInFunctionDeclaration(node); case 192 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // Fall through case 219 /* ModuleBlock */: return spanInBlock(node); case 244 /* CatchClause */: return spanInBlock(node.block); case 195 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); case 204 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); case 198 /* WhileStatement */: // Span on while(...) return textSpan(node, ts.findNextToken(node.expression, node)); case 197 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); case 210 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); case 196 /* IfStatement */: // set on if(..) span return textSpan(node, ts.findNextToken(node.expression, node)); case 207 /* LabeledStatement */: // span in statement return spanInNode(node.statement); case 203 /* BreakStatement */: case 202 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); case 199 /* ForStatement */: return spanInForStatement(node); case 200 /* ForInStatement */: case 201 /* ForOfStatement */: // span on for (a in ...) return textSpan(node, ts.findNextToken(node.expression, node)); case 206 /* SwitchStatement */: // span on switch(...) return textSpan(node, ts.findNextToken(node.expression, node)); case 241 /* CaseClause */: case 242 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); case 209 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); case 208 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); case 227 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); case 221 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); case 222 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); case 228 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); case 218 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } case 214 /* ClassDeclaration */: case 217 /* EnumDeclaration */: case 247 /* EnumMember */: case 168 /* CallExpression */: case 169 /* NewExpression */: // span on complete node return textSpan(node); case 205 /* WithStatement */: // span in statement return spanInNode(node.statement); // No breakpoint in interface, type alias case 215 /* InterfaceDeclaration */: case 216 /* TypeAliasDeclaration */: return undefined; // Tokens: case 23 /* SemicolonToken */: case 1 /* EndOfFileToken */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); case 24 /* CommaToken */: return spanInPreviousNode(node); case 15 /* OpenBraceToken */: return spanInOpenBraceToken(node); case 16 /* CloseBraceToken */: return spanInCloseBraceToken(node); case 17 /* OpenParenToken */: return spanInOpenParenToken(node); case 18 /* CloseParenToken */: return spanInCloseParenToken(node); case 54 /* ColonToken */: return spanInColonToken(node); case 27 /* GreaterThanToken */: case 25 /* LessThanToken */: return spanInGreaterThanOrLessThanToken(node); // Keywords: case 104 /* WhileKeyword */: return spanInWhileKeyword(node); case 80 /* ElseKeyword */: case 72 /* CatchKeyword */: case 85 /* FinallyKeyword */: return spanInNextNode(node); default: // If this is name of property assignment, set breakpoint in the initializer if (node.parent.kind === 245 /* PropertyAssignment */ && node.parent.name === node) { return spanInNode(node.parent.initializer); } // Breakpoint in type assertion goes to its operand if (node.parent.kind === 171 /* TypeAssertionExpression */ && node.parent.type === node) { return spanInNode(node.parent.expression); } // return type of function go to previous token if (ts.isFunctionLike(node.parent) && node.parent.type === node) { return spanInPreviousNode(node); } // Default go to parent to set the breakpoint return spanInNode(node.parent); } } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent if (variableDeclaration.parent.parent.kind === 200 /* ForInStatement */ || variableDeclaration.parent.parent.kind === 201 /* ForOfStatement */) { return spanInNode(variableDeclaration.parent.parent); } var isParentVariableStatement = variableDeclaration.parent.parent.kind === 193 /* VariableStatement */; var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 199 /* ForStatement */ && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); var declarations = isParentVariableStatement ? variableDeclaration.parent.parent.declarationList.declarations : isDeclarationOfForStatement ? variableDeclaration.parent.parent.initializer.declarations : undefined; // Breakpoint is possible in variableDeclaration only if there is initialization if (variableDeclaration.initializer || (variableDeclaration.flags & 2 /* Export */)) { if (declarations && declarations[0] === variableDeclaration) { if (isParentVariableStatement) { // First declaration - include let keyword return textSpan(variableDeclaration.parent, variableDeclaration); } else { ts.Debug.assert(isDeclarationOfForStatement); // Include let keyword from for statement declarations in the span return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); } } else { // Span only on this declaration return textSpan(variableDeclaration); } } else if (declarations && declarations[0] !== variableDeclaration) { // If we cant set breakpoint on this declaration, set it on previous one var indexOfCurrentDeclaration = ts.indexOf(declarations, variableDeclaration); return spanInVariableDeclaration(declarations[indexOfCurrentDeclaration - 1]); } } function canHaveSpanInParameterDeclaration(parameter) { // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier return !!parameter.initializer || parameter.dotDotDotToken !== undefined || !!(parameter.flags & 8 /* Public */) || !!(parameter.flags & 16 /* Private */); } function spanInParameterDeclaration(parameter) { if (canHaveSpanInParameterDeclaration(parameter)) { return textSpan(parameter); } else { var functionDeclaration = parameter.parent; var indexOfParameter = ts.indexOf(functionDeclaration.parameters, parameter); if (indexOfParameter) { // Not a first parameter, go to previous parameter return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); } else { // Set breakpoint in the function declaration body return spanInNode(functionDeclaration.body); } } } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return !!(functionDeclaration.flags & 2 /* Export */) || (functionDeclaration.parent.kind === 214 /* ClassDeclaration */ && functionDeclaration.kind !== 144 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature if (!functionDeclaration.body) { return undefined; } if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) { // Set the span on whole function declaration return textSpan(functionDeclaration); } // Set span in function body return spanInNode(functionDeclaration.body); } function spanInFunctionBlock(block) { var nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken(); if (canFunctionHaveSpanInWholeDeclaration(block.parent)) { return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock); } return spanInNode(nodeForSpanInBlock); } function spanInBlock(block) { switch (block.parent.kind) { case 218 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // Set on parent if on same line otherwise on first statement case 198 /* WhileStatement */: case 196 /* IfStatement */: case 200 /* ForInStatement */: case 201 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block case 199 /* ForStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } function spanInForStatement(forStatement) { if (forStatement.initializer) { if (forStatement.initializer.kind === 212 /* VariableDeclarationList */) { var variableDeclarationList = forStatement.initializer; if (variableDeclarationList.declarations.length > 0) { return spanInNode(variableDeclarationList.declarations[0]); } } else { return spanInNode(forStatement.initializer); } } if (forStatement.condition) { return textSpan(forStatement.condition); } if (forStatement.incrementor) { return textSpan(forStatement.incrementor); } } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { case 217 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); case 214 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); case 220 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node return spanInNode(node.parent); } function spanInCloseBraceToken(node) { switch (node.parent.kind) { case 219 /* ModuleBlock */: // If this is not instantiated module block no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } case 217 /* EnumDeclaration */: case 214 /* ClassDeclaration */: // Span on close brace token return textSpan(node); case 192 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // fall through. case 244 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); case 220 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); if (lastClause) { return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; // Default to parent node default: return spanInNode(node.parent); } } function spanInOpenParenToken(node) { if (node.parent.kind === 197 /* DoStatement */) { // Go to while keyword and do action instead return spanInPreviousNode(node); } // Default to parent node return spanInNode(node.parent); } function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { case 173 /* FunctionExpression */: case 213 /* FunctionDeclaration */: case 174 /* ArrowFunction */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 144 /* Constructor */: case 198 /* WhileStatement */: case 197 /* DoStatement */: case 199 /* ForStatement */: return spanInPreviousNode(node); // Default to parent node default: return spanInNode(node.parent); } } function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || node.parent.kind === 245 /* PropertyAssignment */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { if (node.parent.kind === 171 /* TypeAssertionExpression */) { return spanInNode(node.parent.expression); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { if (node.parent.kind === 197 /* DoStatement */) { // Set span on while expression return textSpan(node, ts.findNextToken(node.parent.expression, node.parent)); } // Default to parent node return spanInNode(node.parent); } } }
Get the breakpoint span in given sourceFile
spanInSourceFileAtLocation
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function textSpan(startNode, endNode) { return ts.createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd()); }
Get the breakpoint span in given sourceFile
textSpan
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart()).line) { return spanInNode(node); } return spanInNode(otherwiseOnNode); }
Get the breakpoint span in given sourceFile
spanInNodeIfStartsOnSameLine
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT