mirror of
https://github.com/microsoft/TypeScript.git
synced 2026-11-18 20:11:14 +00:00
Merge branch 'master' into referencesDogfood_1
This commit is contained in:
commit
df95de3231
120 files changed
+3082
-1867
No files matched your search
@@ -22,10 +22,20 @@ namespace ts.DocumentHighlights {
|
||||
}
|
||||
|
||||
function getSemanticDocumentHighlights(position: number, node: Node, program: Program, cancellationToken: CancellationToken, sourceFilesToSearch: ReadonlyArray<SourceFile>): DocumentHighlights[] | undefined {
|
||||
const referenceEntries = FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken);
|
||||
const sourceFilesSet = arrayToSet(sourceFilesToSearch, f => f.fileName);
|
||||
const referenceEntries = FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ undefined, sourceFilesSet);
|
||||
if (!referenceEntries) return undefined;
|
||||
const map = arrayToMultiMap(referenceEntries.map(FindAllReferences.toHighlightSpan), e => e.fileName, e => e.span);
|
||||
return arrayFrom(map.entries(), ([fileName, highlightSpans]) => ({ fileName, highlightSpans }));
|
||||
return arrayFrom(map.entries(), ([fileName, highlightSpans]) => {
|
||||
if (!sourceFilesSet.has(fileName)) {
|
||||
Debug.assert(program.redirectTargetsSet.has(fileName));
|
||||
const redirectTarget = program.getSourceFile(fileName);
|
||||
const redirect = find(sourceFilesToSearch, f => f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget)!;
|
||||
fileName = redirect.fileName;
|
||||
Debug.assert(sourceFilesSet.has(fileName));
|
||||
}
|
||||
return { fileName, highlightSpans };
|
||||
});
|
||||
}
|
||||
|
||||
function getSyntacticDocumentHighlights(node: Node, sourceFile: SourceFile): DocumentHighlights[] {
|
||||
|
||||
@@ -41,7 +41,7 @@ namespace ts.FindAllReferences {
|
||||
|
||||
export function findReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray<SourceFile>, sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined {
|
||||
const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
|
||||
const referencedSymbols = Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, /*options*/ {});
|
||||
const referencedSymbols = Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken);
|
||||
const checker = program.getTypeChecker();
|
||||
return !referencedSymbols || !referencedSymbols.length ? undefined : mapDefined<SymbolAndEntries, ReferencedSymbol>(referencedSymbols, ({ definition, references }) =>
|
||||
// Only include referenced symbols that have a valid definition.
|
||||
@@ -86,8 +86,8 @@ namespace ts.FindAllReferences {
|
||||
return map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry);
|
||||
}
|
||||
|
||||
export function getReferenceEntriesForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray<SourceFile>, cancellationToken: CancellationToken, options: Options = {}): Entry[] | undefined {
|
||||
return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options));
|
||||
export function getReferenceEntriesForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray<SourceFile>, cancellationToken: CancellationToken, options: Options = {}, sourceFilesSet: ReadonlyMap<true> = arrayToSet(sourceFiles, f => f.fileName)): Entry[] | undefined {
|
||||
return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet));
|
||||
}
|
||||
|
||||
function flattenEntries(referenceSymbols: SymbolAndEntries[]): Entry[] {
|
||||
@@ -229,10 +229,10 @@ namespace ts.FindAllReferences {
|
||||
/* @internal */
|
||||
namespace ts.FindAllReferences.Core {
|
||||
/** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */
|
||||
export function getReferencedSymbolsForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray<SourceFile>, cancellationToken: CancellationToken, options: Options = {}): SymbolAndEntries[] | undefined {
|
||||
export function getReferencedSymbolsForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray<SourceFile>, cancellationToken: CancellationToken, options: Options = {}, sourceFilesSet: ReadonlyMap<true> = arrayToSet(sourceFiles, f => f.fileName)): SymbolAndEntries[] | undefined {
|
||||
if (isSourceFile(node)) {
|
||||
const reference = GoToDefinition.getReferenceAtPosition(node, position, program);
|
||||
return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles);
|
||||
return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles, sourceFilesSet);
|
||||
}
|
||||
|
||||
if (!options.implementations) {
|
||||
@@ -252,10 +252,10 @@ namespace ts.FindAllReferences.Core {
|
||||
}
|
||||
|
||||
if (symbol.flags & SymbolFlags.Module && isModuleReferenceLocation(node)) {
|
||||
return getReferencedSymbolsForModule(program, symbol, sourceFiles);
|
||||
return getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet);
|
||||
}
|
||||
|
||||
return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options);
|
||||
return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options);
|
||||
}
|
||||
|
||||
function isModuleReferenceLocation(node: Node): boolean {
|
||||
@@ -275,7 +275,7 @@ namespace ts.FindAllReferences.Core {
|
||||
}
|
||||
}
|
||||
|
||||
function getReferencedSymbolsForModule(program: Program, symbol: Symbol, sourceFiles: ReadonlyArray<SourceFile>): SymbolAndEntries[] {
|
||||
function getReferencedSymbolsForModule(program: Program, symbol: Symbol, sourceFiles: ReadonlyArray<SourceFile>, sourceFilesSet: ReadonlyMap<true>): SymbolAndEntries[] {
|
||||
Debug.assert(!!symbol.valueDeclaration);
|
||||
|
||||
const references = findModuleReferences(program, sourceFiles, symbol).map<Entry>(reference => {
|
||||
@@ -297,7 +297,9 @@ namespace ts.FindAllReferences.Core {
|
||||
// Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.)
|
||||
break;
|
||||
case SyntaxKind.ModuleDeclaration:
|
||||
references.push({ type: "node", node: (decl as ModuleDeclaration).name });
|
||||
if (sourceFilesSet.has(decl.getSourceFile().fileName)) {
|
||||
references.push({ type: "node", node: (decl as ModuleDeclaration).name });
|
||||
}
|
||||
break;
|
||||
default:
|
||||
Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
|
||||
@@ -337,14 +339,14 @@ namespace ts.FindAllReferences.Core {
|
||||
}
|
||||
|
||||
/** Core find-all-references algorithm for a normal symbol. */
|
||||
function getReferencedSymbolsForSymbol(symbol: Symbol, node: Node, sourceFiles: ReadonlyArray<SourceFile>, checker: TypeChecker, cancellationToken: CancellationToken, options: Options): SymbolAndEntries[] {
|
||||
function getReferencedSymbolsForSymbol(symbol: Symbol, node: Node, sourceFiles: ReadonlyArray<SourceFile>, sourceFilesSet: ReadonlyMap<true>, checker: TypeChecker, cancellationToken: CancellationToken, options: Options): SymbolAndEntries[] {
|
||||
symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
|
||||
|
||||
// Compute the meaning from the location and the symbol it references
|
||||
const searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol);
|
||||
|
||||
const result: SymbolAndEntries[] = [];
|
||||
const state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result);
|
||||
const state = new State(sourceFiles, sourceFilesSet, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result);
|
||||
|
||||
if (node.kind === SyntaxKind.DefaultKeyword) {
|
||||
addReference(node, symbol, state);
|
||||
@@ -467,10 +469,9 @@ namespace ts.FindAllReferences.Core {
|
||||
*/
|
||||
readonly markSeenReExportRHS = nodeSeenTracker();
|
||||
|
||||
private readonly includedSourceFiles: Map<true>;
|
||||
|
||||
constructor(
|
||||
readonly sourceFiles: ReadonlyArray<SourceFile>,
|
||||
readonly sourceFilesSet: ReadonlyMap<true>,
|
||||
/** True if we're searching for constructor references. */
|
||||
readonly specialSearchKind: SpecialSearchKind,
|
||||
readonly checker: TypeChecker,
|
||||
@@ -478,17 +479,16 @@ namespace ts.FindAllReferences.Core {
|
||||
readonly searchMeaning: SemanticMeaning,
|
||||
readonly options: Options,
|
||||
private readonly result: Push<SymbolAndEntries>) {
|
||||
this.includedSourceFiles = arrayToSet(sourceFiles, s => s.fileName);
|
||||
}
|
||||
|
||||
includesSourceFile(sourceFile: SourceFile): boolean {
|
||||
return this.includedSourceFiles.has(sourceFile.fileName);
|
||||
return this.sourceFilesSet.has(sourceFile.fileName);
|
||||
}
|
||||
|
||||
private importTracker: ImportTracker | undefined;
|
||||
/** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */
|
||||
getImportSearches(exportSymbol: Symbol, exportInfo: ExportInfo): ImportsResult {
|
||||
if (!this.importTracker) this.importTracker = createImportTracker(this.sourceFiles, this.checker, this.cancellationToken);
|
||||
if (!this.importTracker) this.importTracker = createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken);
|
||||
return this.importTracker(exportSymbol, exportInfo, this.options.isForRename);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,10 +12,10 @@ namespace ts.FindAllReferences {
|
||||
export type ImportTracker = (exportSymbol: Symbol, exportInfo: ExportInfo, isForRename: boolean) => ImportsResult;
|
||||
|
||||
/** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily. */
|
||||
export function createImportTracker(sourceFiles: ReadonlyArray<SourceFile>, checker: TypeChecker, cancellationToken: CancellationToken): ImportTracker {
|
||||
export function createImportTracker(sourceFiles: ReadonlyArray<SourceFile>, sourceFilesSet: ReadonlyMap<true>, checker: TypeChecker, cancellationToken: CancellationToken): ImportTracker {
|
||||
const allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken);
|
||||
return (exportSymbol, exportInfo, isForRename) => {
|
||||
const { directImports, indirectUsers } = getImportersForExport(sourceFiles, allDirectImports, exportInfo, checker, cancellationToken);
|
||||
const { directImports, indirectUsers } = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken);
|
||||
return { indirectUsers, ...getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename) };
|
||||
};
|
||||
}
|
||||
@@ -39,6 +39,7 @@ namespace ts.FindAllReferences {
|
||||
/** Returns import statements that directly reference the exporting module, and a list of files that may access the module through a namespace. */
|
||||
function getImportersForExport(
|
||||
sourceFiles: ReadonlyArray<SourceFile>,
|
||||
sourceFilesSet: ReadonlyMap<true>,
|
||||
allDirectImports: Map<ImporterOrCallExpression[]>,
|
||||
{ exportingModuleSymbol, exportKind }: ExportInfo,
|
||||
checker: TypeChecker,
|
||||
@@ -62,7 +63,7 @@ namespace ts.FindAllReferences {
|
||||
|
||||
// Module augmentations may use this module's exports without importing it.
|
||||
for (const decl of exportingModuleSymbol.declarations) {
|
||||
if (isExternalModuleAugmentation(decl)) {
|
||||
if (isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) {
|
||||
addIndirectUser(decl);
|
||||
}
|
||||
}
|
||||
|
||||
+11
-14
@@ -10,6 +10,7 @@ namespace ts.NavigateTo {
|
||||
|
||||
export function getNavigateToItems(sourceFiles: ReadonlyArray<SourceFile>, checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number, excludeDtsFiles: boolean): NavigateToItem[] {
|
||||
const patternMatcher = createPatternMatcher(searchValue);
|
||||
if (!patternMatcher) return emptyArray;
|
||||
let rawItems: RawNavigateToItem[] = [];
|
||||
|
||||
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
|
||||
@@ -35,28 +36,24 @@ namespace ts.NavigateTo {
|
||||
function getItemsFromNamedDeclaration(patternMatcher: PatternMatcher, name: string, declarations: ReadonlyArray<Declaration>, checker: TypeChecker, fileName: string, rawItems: Push<RawNavigateToItem>): void {
|
||||
// First do a quick check to see if the name of the declaration matches the
|
||||
// last portion of the (possibly) dotted name they're searching for.
|
||||
const matches = patternMatcher.getMatchesForLastSegmentOfPattern(name);
|
||||
|
||||
if (!matches) {
|
||||
const match = patternMatcher.getMatchForLastSegmentOfPattern(name);
|
||||
if (!match) {
|
||||
return; // continue to next named declarations
|
||||
}
|
||||
|
||||
for (const declaration of declarations) {
|
||||
if (!shouldKeepItem(declaration, checker)) {
|
||||
continue;
|
||||
}
|
||||
if (!shouldKeepItem(declaration, checker)) continue;
|
||||
|
||||
// It was a match! If the pattern has dots in it, then also see if the
|
||||
// declaration container matches as well.
|
||||
let containerMatches = matches;
|
||||
if (patternMatcher.patternContainsDots) {
|
||||
containerMatches = patternMatcher.getMatches(getContainers(declaration), name);
|
||||
if (!containerMatches) {
|
||||
continue;
|
||||
const fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name);
|
||||
if (fullMatch) {
|
||||
rawItems.push({ name, fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration });
|
||||
}
|
||||
}
|
||||
|
||||
rawItems.push({ name, fileName, matchKind: Math.min(...matches.map(m => m.kind)), isCaseSensitive: matches.every(m => m.isCaseSensitive), declaration });
|
||||
else {
|
||||
// If the pattern has dots in it, then also see if the declaration container matches as well.
|
||||
rawItems.push({ name, fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,12 +33,12 @@ namespace ts {
|
||||
// this will return a successful match, having only tested "SK" against "SyntaxKind". At
|
||||
// that point a call can be made to 'getMatches("SyntaxKind", "ts.compiler")', with the
|
||||
// work to create 'ts.compiler' only being done once the first match succeeded.
|
||||
getMatchesForLastSegmentOfPattern(candidate: string): PatternMatch[];
|
||||
getMatchForLastSegmentOfPattern(candidate: string): PatternMatch | undefined;
|
||||
|
||||
// Fully checks a candidate, with an dotted container, against the search pattern.
|
||||
// The candidate must match the last part of the search pattern, and the dotted container
|
||||
// must match the preceding segments of the pattern.
|
||||
getMatches(candidateContainers: string[], candidate: string): PatternMatch[] | undefined;
|
||||
getFullMatch(candidateContainers: ReadonlyArray<string>, candidate: string): PatternMatch | undefined;
|
||||
|
||||
// Whether or not the pattern contained dots or not. Clients can use this to determine
|
||||
// If they should call getMatches, or if getMatchesForLastSegmentOfPattern is sufficient.
|
||||
@@ -97,31 +97,25 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
|
||||
export function createPatternMatcher(pattern: string): PatternMatcher {
|
||||
export function createPatternMatcher(pattern: string): PatternMatcher | undefined {
|
||||
// We'll often see the same candidate string many times when searching (For example, when
|
||||
// we see the name of a module that is used everywhere, or the name of an overload). As
|
||||
// such, we cache the information we compute about the candidate for the life of this
|
||||
// pattern matcher so we don't have to compute it multiple times.
|
||||
const stringToWordSpans = createMap<TextSpan[]>();
|
||||
|
||||
pattern = pattern.trim();
|
||||
|
||||
const dotSeparatedSegments = pattern.split(".").map(p => createSegment(p.trim()));
|
||||
const invalidPattern = dotSeparatedSegments.length === 0 || forEach(dotSeparatedSegments, segmentIsInvalid);
|
||||
const dotSeparatedSegments = pattern.trim().split(".").map(p => createSegment(p.trim()));
|
||||
// A segment is considered invalid if we couldn't find any words in it.
|
||||
if (dotSeparatedSegments.some(segment => !segment.subWordTextChunks.length)) return undefined;
|
||||
|
||||
return {
|
||||
getMatches: (containers, candidate) => skipMatch(candidate) ? undefined : getMatches(containers, candidate, dotSeparatedSegments, stringToWordSpans),
|
||||
getMatchesForLastSegmentOfPattern: candidate => skipMatch(candidate) ? undefined : matchSegment(candidate, lastOrUndefined(dotSeparatedSegments), stringToWordSpans),
|
||||
getFullMatch: (containers, candidate) => getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans),
|
||||
getMatchForLastSegmentOfPattern: candidate => matchSegment(candidate, last(dotSeparatedSegments), stringToWordSpans),
|
||||
patternContainsDots: dotSeparatedSegments.length > 1
|
||||
};
|
||||
|
||||
// Quick checks so we can bail out when asked to match a candidate.
|
||||
function skipMatch(candidate: string) {
|
||||
return invalidPattern || !candidate;
|
||||
}
|
||||
}
|
||||
|
||||
function getMatches(candidateContainers: ReadonlyArray<string>, candidate: string, dotSeparatedSegments: ReadonlyArray<Segment>, stringToWordSpans: Map<TextSpan[]>): PatternMatch[] | undefined {
|
||||
function getFullMatch(candidateContainers: ReadonlyArray<string>, candidate: string, dotSeparatedSegments: ReadonlyArray<Segment>, stringToWordSpans: Map<TextSpan[]>): PatternMatch | undefined {
|
||||
// First, check that the last part of the dot separated pattern matches the name of the
|
||||
// candidate. If not, then there's no point in proceeding and doing the more
|
||||
// expensive work.
|
||||
@@ -140,29 +134,13 @@ namespace ts {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// So far so good. Now break up the container for the candidate and check if all
|
||||
// the dotted parts match up correctly.
|
||||
const totalMatch = candidateMatch;
|
||||
|
||||
let bestMatch: PatternMatch | undefined;
|
||||
for (let i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1;
|
||||
i >= 0;
|
||||
i -= 1, j -= 1) {
|
||||
|
||||
const segment = dotSeparatedSegments[i];
|
||||
const containerName = candidateContainers[j];
|
||||
|
||||
const containerMatch = matchSegment(containerName, segment, stringToWordSpans);
|
||||
if (!containerMatch) {
|
||||
// This container didn't match the pattern piece. So there's no match at all.
|
||||
return undefined;
|
||||
}
|
||||
|
||||
addRange(totalMatch, containerMatch);
|
||||
bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans));
|
||||
}
|
||||
|
||||
// Success, this symbol's full name matched against the dotted name the user was asking
|
||||
// about.
|
||||
return totalMatch;
|
||||
return bestMatch;
|
||||
}
|
||||
|
||||
function getWordSpans(word: string, stringToWordSpans: Map<TextSpan[]>): TextSpan[] {
|
||||
@@ -225,7 +203,7 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function matchSegment(candidate: string, segment: Segment, stringToWordSpans: Map<TextSpan[]>): PatternMatch[] {
|
||||
function matchSegment(candidate: string, segment: Segment, stringToWordSpans: Map<TextSpan[]>): PatternMatch {
|
||||
// First check if the segment matches as is. This is also useful if the segment contains
|
||||
// characters we would normally strip when splitting into parts that we also may want to
|
||||
// match in the candidate. For example if the segment is "@int" and the candidate is
|
||||
@@ -235,9 +213,7 @@ namespace ts {
|
||||
// multi-word segment.
|
||||
if (every(segment.totalTextChunk.text, ch => ch !== CharacterCodes.space && ch !== CharacterCodes.asterisk)) {
|
||||
const match = matchTextChunk(candidate, segment.totalTextChunk, stringToWordSpans);
|
||||
if (match) {
|
||||
return [match];
|
||||
}
|
||||
if (match) return match;
|
||||
}
|
||||
|
||||
// The logic for pattern matching is now as follows:
|
||||
@@ -277,20 +253,19 @@ namespace ts {
|
||||
// Only if all words have some sort of match is the pattern considered matched.
|
||||
|
||||
const subWordTextChunks = segment.subWordTextChunks;
|
||||
let matches: PatternMatch[];
|
||||
|
||||
let bestMatch: PatternMatch | undefined;
|
||||
for (const subWordTextChunk of subWordTextChunks) {
|
||||
// Try to match the candidate with this word
|
||||
const result = matchTextChunk(candidate, subWordTextChunk, stringToWordSpans);
|
||||
if (!result) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
matches = matches || [];
|
||||
matches.push(result);
|
||||
bestMatch = betterMatch(bestMatch, matchTextChunk(candidate, subWordTextChunk, stringToWordSpans));
|
||||
}
|
||||
return bestMatch;
|
||||
}
|
||||
|
||||
return matches;
|
||||
function betterMatch(a: PatternMatch | undefined, b: PatternMatch | undefined): PatternMatch {
|
||||
return min(a, b, compareMatches);
|
||||
}
|
||||
function compareMatches(a: PatternMatch | undefined, b: PatternMatch | undefined): Comparison {
|
||||
return a === undefined ? Comparison.GreaterThan : b === undefined ? Comparison.LessThan
|
||||
: compareValues(a.kind, b.kind) || compareBooleans(!a.isCaseSensitive, !b.isCaseSensitive);
|
||||
}
|
||||
|
||||
function partStartsWith(candidate: string, candidateSpan: TextSpan, pattern: string, ignoreCase: boolean, patternSpan: TextSpan = { start: 0, length: pattern.length }): boolean {
|
||||
@@ -381,11 +356,6 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
|
||||
// A segment is considered invalid if we couldn't find any words in it.
|
||||
function segmentIsInvalid(segment: Segment) {
|
||||
return segment.subWordTextChunks.length === 0;
|
||||
}
|
||||
|
||||
function isUpperCaseLetter(ch: number) {
|
||||
// Fast check for the ascii range.
|
||||
if (ch >= CharacterCodes.A && ch <= CharacterCodes.Z) {
|
||||
|
||||
@@ -698,14 +698,6 @@ namespace ts.refactor.extractSymbol {
|
||||
Global,
|
||||
}
|
||||
|
||||
function getUniqueName(baseName: string, fileText: string): string {
|
||||
let nameText = baseName;
|
||||
for (let i = 1; stringContains(fileText, nameText); i++) {
|
||||
nameText = `${baseName}_${i}`;
|
||||
}
|
||||
return nameText;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of 'extractRange' operation for a specific scope.
|
||||
* Stores either a list of changes that should be applied to extract a range or a list of errors
|
||||
@@ -1126,37 +1118,6 @@ namespace ts.refactor.extractSymbol {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The index of the (only) reference to the extracted symbol. We want the cursor
|
||||
* to be on the reference, rather than the declaration, because it's closer to where the
|
||||
* user was before extracting it.
|
||||
*/
|
||||
function getRenameLocation(edits: ReadonlyArray<FileTextChanges>, renameFilename: string, functionNameText: string, isDeclaredBeforeUse: boolean): number {
|
||||
let delta = 0;
|
||||
let lastPos = -1;
|
||||
for (const { fileName, textChanges } of edits) {
|
||||
Debug.assert(fileName === renameFilename);
|
||||
for (const change of textChanges) {
|
||||
const { span, newText } = change;
|
||||
const index = newText.indexOf(functionNameText);
|
||||
if (index !== -1) {
|
||||
lastPos = span.start + delta + index;
|
||||
|
||||
// If the reference comes first, return immediately.
|
||||
if (!isDeclaredBeforeUse) {
|
||||
return lastPos;
|
||||
}
|
||||
}
|
||||
delta += newText.length - span.length;
|
||||
}
|
||||
}
|
||||
|
||||
// If the declaration comes first, return the position of the last occurrence.
|
||||
Debug.assert(isDeclaredBeforeUse);
|
||||
Debug.assert(lastPos >= 0);
|
||||
return lastPos;
|
||||
}
|
||||
|
||||
function getFirstDeclaration(type: Type): Declaration | undefined {
|
||||
let firstDeclaration;
|
||||
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
/* @internal */
|
||||
namespace ts.refactor.generateGetAccessorAndSetAccessor {
|
||||
const actionName = "Generate 'get' and 'set' accessors";
|
||||
const actionDescription = Diagnostics.Generate_get_and_set_accessors.message;
|
||||
registerRefactor(actionName, { getEditsForAction, getAvailableActions });
|
||||
|
||||
type AcceptedDeclaration = ParameterDeclaration | PropertyDeclaration | PropertyAssignment;
|
||||
type AcceptedNameType = Identifier | StringLiteral;
|
||||
type ContainerDeclaration = ClassLikeDeclaration | ObjectLiteralExpression;
|
||||
|
||||
interface DeclarationInfo {
|
||||
container: ContainerDeclaration;
|
||||
isStatic: boolean;
|
||||
type: TypeNode | undefined;
|
||||
}
|
||||
|
||||
interface Info extends DeclarationInfo {
|
||||
declaration: AcceptedDeclaration;
|
||||
fieldName: AcceptedNameType;
|
||||
accessorName: AcceptedNameType;
|
||||
}
|
||||
|
||||
function getAvailableActions(context: RefactorContext): ApplicableRefactorInfo[] | undefined {
|
||||
const { file, startPosition } = context;
|
||||
if (!getConvertibleFieldAtPosition(file, startPosition)) return undefined;
|
||||
|
||||
return [{
|
||||
name: actionName,
|
||||
description: actionDescription,
|
||||
actions: [
|
||||
{
|
||||
name: actionName,
|
||||
description: actionDescription
|
||||
}
|
||||
]
|
||||
}];
|
||||
}
|
||||
|
||||
function getEditsForAction(context: RefactorContext, _actionName: string): RefactorEditInfo | undefined {
|
||||
const { file, startPosition } = context;
|
||||
|
||||
const fieldInfo = getConvertibleFieldAtPosition(file, startPosition);
|
||||
if (!fieldInfo) return undefined;
|
||||
|
||||
const isJS = isSourceFileJavaScript(file);
|
||||
const changeTracker = textChanges.ChangeTracker.fromContext(context);
|
||||
const { isStatic, fieldName, accessorName, type, container, declaration } = fieldInfo;
|
||||
|
||||
const isInClassLike = isClassLike(container);
|
||||
const accessorModifiers = getAccessorModifiers(isJS, declaration, isStatic, isInClassLike);
|
||||
const fieldModifiers = getFieldModifiers(isJS, isStatic, isInClassLike);
|
||||
|
||||
updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers, container);
|
||||
|
||||
const getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
|
||||
const setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
|
||||
|
||||
insertAccessor(changeTracker, file, getAccessor, declaration, container);
|
||||
insertAccessor(changeTracker, file, setAccessor, declaration, container);
|
||||
|
||||
const edits = changeTracker.getChanges();
|
||||
const renameFilename = file.fileName;
|
||||
const renameLocationOffset = isIdentifier(fieldName) ? 0 : -1;
|
||||
const renameLocation = renameLocationOffset + getRenameLocation(edits, renameFilename, fieldName.text, /*isDeclaredBeforeUse*/ false);
|
||||
return { renameFilename, renameLocation, edits };
|
||||
}
|
||||
|
||||
function isConvertableName (name: DeclarationName): name is AcceptedNameType {
|
||||
return isIdentifier(name) || isStringLiteral(name);
|
||||
}
|
||||
|
||||
function isAcceptedDeclaration(node: Node): node is AcceptedDeclaration {
|
||||
return isParameterPropertyDeclaration(node) || isPropertyDeclaration(node) || isPropertyAssignment(node);
|
||||
}
|
||||
|
||||
function createPropertyName (name: string, originalName: AcceptedNameType) {
|
||||
return isIdentifier(originalName) ? createIdentifier(name) : createLiteral(name);
|
||||
}
|
||||
|
||||
function createAccessorAccessExpression (fieldName: AcceptedNameType, isStatic: boolean, container: ContainerDeclaration) {
|
||||
const leftHead = isStatic ? (<ClassLikeDeclaration>container).name : createThis();
|
||||
return isIdentifier(fieldName) ? createPropertyAccess(leftHead, fieldName) : createElementAccess(leftHead, createLiteral(fieldName));
|
||||
}
|
||||
|
||||
function getAccessorModifiers(isJS: boolean, declaration: AcceptedDeclaration, isStatic: boolean, isClassLike: boolean): NodeArray<Modifier> | undefined {
|
||||
if (!isClassLike) return undefined;
|
||||
|
||||
if (!declaration.modifiers || getModifierFlags(declaration) & ModifierFlags.Private) {
|
||||
const modifiers = append<Modifier>(
|
||||
!isJS ? [createToken(SyntaxKind.PublicKeyword)] : undefined,
|
||||
isStatic ? createToken(SyntaxKind.StaticKeyword) : undefined
|
||||
);
|
||||
return modifiers && createNodeArray(modifiers);
|
||||
}
|
||||
return declaration.modifiers;
|
||||
}
|
||||
|
||||
function getFieldModifiers(isJS: boolean, isStatic: boolean, isClassLike: boolean): NodeArray<Modifier> | undefined {
|
||||
if (!isClassLike) return undefined;
|
||||
|
||||
const modifiers = append<Modifier>(
|
||||
!isJS ? [createToken(SyntaxKind.PrivateKeyword)] : undefined,
|
||||
isStatic ? createToken(SyntaxKind.StaticKeyword) : undefined
|
||||
);
|
||||
return modifiers && createNodeArray(modifiers);
|
||||
}
|
||||
|
||||
function getPropertyDeclarationInfo(propertyDeclaration: PropertyDeclaration): DeclarationInfo | undefined {
|
||||
if (!isClassLike(propertyDeclaration.parent) || !propertyDeclaration.parent.members) return undefined;
|
||||
|
||||
return {
|
||||
isStatic: hasStaticModifier(propertyDeclaration),
|
||||
type: propertyDeclaration.type,
|
||||
container: propertyDeclaration.parent
|
||||
};
|
||||
}
|
||||
|
||||
function getParameterPropertyDeclarationInfo(parameterDeclaration: ParameterDeclaration): DeclarationInfo | undefined {
|
||||
if (!isClassLike(parameterDeclaration.parent.parent) || !parameterDeclaration.parent.parent.members) return undefined;
|
||||
|
||||
return {
|
||||
isStatic: false,
|
||||
type: parameterDeclaration.type,
|
||||
container: parameterDeclaration.parent.parent
|
||||
};
|
||||
}
|
||||
|
||||
function getPropertyAssignmentDeclarationInfo(propertyAssignment: PropertyAssignment): DeclarationInfo | undefined {
|
||||
return {
|
||||
isStatic: false,
|
||||
type: undefined,
|
||||
container: propertyAssignment.parent
|
||||
};
|
||||
}
|
||||
|
||||
function getDeclarationInfo(declaration: AcceptedDeclaration) {
|
||||
if (isPropertyDeclaration(declaration)) {
|
||||
return getPropertyDeclarationInfo(declaration);
|
||||
}
|
||||
else if (isPropertyAssignment(declaration)) {
|
||||
return getPropertyAssignmentDeclarationInfo(declaration);
|
||||
}
|
||||
else {
|
||||
return getParameterPropertyDeclarationInfo(declaration);
|
||||
}
|
||||
}
|
||||
|
||||
function getConvertibleFieldAtPosition(file: SourceFile, startPosition: number): Info | undefined {
|
||||
const node = getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
|
||||
const declaration = findAncestor(node.parent, isAcceptedDeclaration);
|
||||
// make sure propertyDeclaration have AccessibilityModifier or Static Modifier
|
||||
const meaning = ModifierFlags.AccessibilityModifier | ModifierFlags.Static;
|
||||
if (!declaration || !isConvertableName(declaration.name) || (getModifierFlags(declaration) | meaning) !== meaning) return undefined;
|
||||
|
||||
const info = getDeclarationInfo(declaration);
|
||||
const fieldName = createPropertyName(getUniqueName(`_${declaration.name.text}`, file.text), declaration.name);
|
||||
suppressLeadingAndTrailingTrivia(fieldName);
|
||||
suppressLeadingAndTrailingTrivia(declaration);
|
||||
return {
|
||||
...info,
|
||||
declaration,
|
||||
fieldName,
|
||||
accessorName: createPropertyName(declaration.name.text, declaration.name)
|
||||
};
|
||||
}
|
||||
|
||||
function generateGetAccessor(fieldName: AcceptedNameType, accessorName: AcceptedNameType, type: TypeNode, modifiers: ModifiersArray | undefined, isStatic: boolean, container: ContainerDeclaration) {
|
||||
return createGetAccessor(
|
||||
/*decorators*/ undefined,
|
||||
modifiers,
|
||||
accessorName,
|
||||
/*parameters*/ undefined,
|
||||
type,
|
||||
createBlock([
|
||||
createReturn(
|
||||
createAccessorAccessExpression(fieldName, isStatic, container)
|
||||
)
|
||||
], /*multiLine*/ true)
|
||||
);
|
||||
}
|
||||
|
||||
function generateSetAccessor(fieldName: AcceptedNameType, accessorName: AcceptedNameType, type: TypeNode, modifiers: ModifiersArray | undefined, isStatic: boolean, container: ContainerDeclaration) {
|
||||
return createSetAccessor(
|
||||
/*decorators*/ undefined,
|
||||
modifiers,
|
||||
accessorName,
|
||||
[createParameter(
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
/*dotDotDotToken*/ undefined,
|
||||
createIdentifier("value"),
|
||||
/*questionToken*/ undefined,
|
||||
type
|
||||
)],
|
||||
createBlock([
|
||||
createStatement(
|
||||
createAssignment(
|
||||
createAccessorAccessExpression(fieldName, isStatic, container),
|
||||
createIdentifier("value")
|
||||
)
|
||||
)
|
||||
], /*multiLine*/ true)
|
||||
);
|
||||
}
|
||||
|
||||
function updatePropertyDeclaration(changeTracker: textChanges.ChangeTracker, file: SourceFile, declaration: PropertyDeclaration, fieldName: AcceptedNameType, modifiers: ModifiersArray | undefined) {
|
||||
const property = updateProperty(
|
||||
declaration,
|
||||
declaration.decorators,
|
||||
modifiers,
|
||||
fieldName,
|
||||
declaration.questionToken || declaration.exclamationToken,
|
||||
declaration.type,
|
||||
declaration.initializer
|
||||
);
|
||||
|
||||
changeTracker.replaceNode(file, declaration, property);
|
||||
}
|
||||
|
||||
function updateParameterPropertyDeclaration(changeTracker: textChanges.ChangeTracker, file: SourceFile, declaration: ParameterDeclaration, fieldName: AcceptedNameType, modifiers: ModifiersArray | undefined, classLikeContainer: ClassLikeDeclaration) {
|
||||
const property = createProperty(
|
||||
declaration.decorators,
|
||||
modifiers,
|
||||
fieldName,
|
||||
declaration.questionToken,
|
||||
declaration.type,
|
||||
declaration.initializer
|
||||
);
|
||||
|
||||
changeTracker.insertNodeAtClassStart(file, classLikeContainer, property);
|
||||
changeTracker.deleteNodeInList(file, declaration);
|
||||
}
|
||||
|
||||
function updatePropertyAssignmentDeclaration (changeTracker: textChanges.ChangeTracker, file: SourceFile, declaration: PropertyAssignment, fieldName: AcceptedNameType) {
|
||||
const assignment = updatePropertyAssignment(declaration, fieldName, declaration.initializer);
|
||||
changeTracker.replacePropertyAssignment(file, declaration, assignment);
|
||||
}
|
||||
|
||||
function updateFieldDeclaration(changeTracker: textChanges.ChangeTracker, file: SourceFile, declaration: AcceptedDeclaration, fieldName: AcceptedNameType, modifiers: ModifiersArray | undefined, container: ContainerDeclaration) {
|
||||
if (isPropertyDeclaration(declaration)) {
|
||||
updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers);
|
||||
}
|
||||
else if (isPropertyAssignment(declaration)) {
|
||||
updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName);
|
||||
}
|
||||
else {
|
||||
updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, <ClassLikeDeclaration>container);
|
||||
}
|
||||
}
|
||||
|
||||
function insertAccessor(changeTracker: textChanges.ChangeTracker, file: SourceFile, accessor: AccessorDeclaration, declaration: AcceptedDeclaration, container: ContainerDeclaration) {
|
||||
isParameterPropertyDeclaration(declaration)
|
||||
? changeTracker.insertNodeAtClassStart(file, <ClassLikeDeclaration>container, accessor)
|
||||
: changeTracker.insertNodeAfter(file, declaration, accessor);
|
||||
}
|
||||
}
|
||||
@@ -1663,20 +1663,17 @@ namespace ts {
|
||||
|
||||
/// References and Occurrences
|
||||
function getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] {
|
||||
const canonicalFileName = getCanonicalFileName(normalizeSlashes(fileName));
|
||||
return flatMap(getDocumentHighlights(fileName, position, [fileName]), entry => entry.highlightSpans.map<ReferenceEntry>(highlightSpan => {
|
||||
Debug.assert(getCanonicalFileName(normalizeSlashes(entry.fileName)) === canonicalFileName); // Get occurrences only supports reporting occurrences for the file queried.
|
||||
return {
|
||||
fileName: entry.fileName,
|
||||
textSpan: highlightSpan.textSpan,
|
||||
isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference,
|
||||
isDefinition: false,
|
||||
isInString: highlightSpan.isInString,
|
||||
};
|
||||
}));
|
||||
return flatMap(getDocumentHighlights(fileName, position, [fileName]), entry => entry.highlightSpans.map<ReferenceEntry>(highlightSpan => ({
|
||||
fileName: entry.fileName,
|
||||
textSpan: highlightSpan.textSpan,
|
||||
isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference,
|
||||
isDefinition: false,
|
||||
isInString: highlightSpan.isInString,
|
||||
})));
|
||||
}
|
||||
|
||||
function getDocumentHighlights(fileName: string, position: number, filesToSearch: ReadonlyArray<string>): DocumentHighlights[] {
|
||||
Debug.assert(contains(filesToSearch, fileName));
|
||||
synchronizeHostData();
|
||||
const sourceFilesToSearch = map(filesToSearch, f => Debug.assertDefined(program.getSourceFile(f)));
|
||||
const sourceFile = getValidSourceFile(fileName);
|
||||
|
||||
@@ -316,6 +316,12 @@ namespace ts.textChanges {
|
||||
return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
|
||||
}
|
||||
|
||||
public replacePropertyAssignment(sourceFile: SourceFile, oldNode: PropertyAssignment, newNode: PropertyAssignment) {
|
||||
return this.replaceNode(sourceFile, oldNode, newNode, {
|
||||
suffix: "," + this.newLineCharacter
|
||||
});
|
||||
}
|
||||
|
||||
private insertNodeAt(sourceFile: SourceFile, pos: number, newNode: Node, options: InsertNodeOptions = {}) {
|
||||
this.replaceRange(sourceFile, createTextRange(pos), newNode, options);
|
||||
}
|
||||
@@ -468,6 +474,9 @@ namespace ts.textChanges {
|
||||
else if (isVariableDeclaration(node)) {
|
||||
return { prefix: ", " };
|
||||
}
|
||||
else if (isPropertyAssignment(node)) {
|
||||
return { suffix: "," + this.newLineCharacter };
|
||||
}
|
||||
else if (isParameter(node)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -228,6 +228,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export interface UserPreferences {
|
||||
readonly disableSuggestions?: boolean;
|
||||
readonly quotePreference?: "double" | "single";
|
||||
readonly includeCompletionsForModuleExports?: boolean;
|
||||
readonly includeCompletionsWithInsertText?: boolean;
|
||||
|
||||
@@ -1526,4 +1526,45 @@ namespace ts {
|
||||
function getFirstChild(node: Node): Node | undefined {
|
||||
return node.forEachChild(child => child);
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function getUniqueName(baseName: string, fileText: string): string {
|
||||
let nameText = baseName;
|
||||
for (let i = 1; stringContains(fileText, nameText); i++) {
|
||||
nameText = `${baseName}_${i}`;
|
||||
}
|
||||
return nameText;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The index of the (only) reference to the extracted symbol. We want the cursor
|
||||
* to be on the reference, rather than the declaration, because it's closer to where the
|
||||
* user was before extracting it.
|
||||
*/
|
||||
/* @internal */
|
||||
export function getRenameLocation(edits: ReadonlyArray<FileTextChanges>, renameFilename: string, name: string, isDeclaredBeforeUse: boolean): number {
|
||||
let delta = 0;
|
||||
let lastPos = -1;
|
||||
for (const { fileName, textChanges } of edits) {
|
||||
Debug.assert(fileName === renameFilename);
|
||||
for (const change of textChanges) {
|
||||
const { span, newText } = change;
|
||||
const index = newText.indexOf(name);
|
||||
if (index !== -1) {
|
||||
lastPos = span.start + delta + index;
|
||||
|
||||
// If the reference comes first, return immediately.
|
||||
if (!isDeclaredBeforeUse) {
|
||||
return lastPos;
|
||||
}
|
||||
}
|
||||
delta += newText.length - span.length;
|
||||
}
|
||||
}
|
||||
|
||||
// If the declaration comes first, return the position of the last occurrence.
|
||||
Debug.assert(isDeclaredBeforeUse);
|
||||
Debug.assert(lastPos >= 0);
|
||||
return lastPos;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user