Skip to content

Commit aa67b16

Browse files
authored
Add undefined to Symbol.declarations' type (microsoft#42975)
* Add undefined to Symbol.declarations' type Symbol.declarations now has type `Declaration[] | undefined`. I made a mistake somewhere in the checker related to JS checking, so there are quite a few test failures right now. * undo clever change to getDeclaringConstructor * Address PR comments 1. More early-returns. 2. More line breaks.
1 parent 2a49cf7 commit aa67b16

25 files changed

+364
-309
lines changed

src/compiler/binder.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -3266,7 +3266,7 @@ namespace ts {
32663266
if (node.name) {
32673267
setParent(node.name, node);
32683268
}
3269-
file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], Diagnostics.Duplicate_identifier_0, symbolName(prototypeSymbol)));
3269+
file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations![0], Diagnostics.Duplicate_identifier_0, symbolName(prototypeSymbol)));
32703270
}
32713271
symbol.exports!.set(prototypeSymbol.escapedName, prototypeSymbol);
32723272
prototypeSymbol.parent = symbol;

src/compiler/builderState.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -166,14 +166,17 @@ namespace ts {
166166

167167
// From ambient modules
168168
for (const ambientModule of program.getTypeChecker().getAmbientModules()) {
169-
if (ambientModule.declarations.length > 1) {
169+
if (ambientModule.declarations && ambientModule.declarations.length > 1) {
170170
addReferenceFromAmbientModule(ambientModule);
171171
}
172172
}
173173

174174
return referencedFiles;
175175

176176
function addReferenceFromAmbientModule(symbol: Symbol) {
177+
if (!symbol.declarations) {
178+
return;
179+
}
177180
// Add any file other than our own as reference
178181
for (const declaration of symbol.declarations) {
179182
const declarationSourceFile = getSourceFileOfNode(declaration);

src/compiler/checker.ts

+293-250
Large diffs are not rendered by default.

src/compiler/core.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ namespace ts {
292292
return -1;
293293
}
294294

295-
export function countWhere<T>(array: readonly T[], predicate: (x: T, i: number) => boolean): number {
295+
export function countWhere<T>(array: readonly T[] | undefined, predicate: (x: T, i: number) => boolean): number {
296296
let count = 0;
297297
if (array) {
298298
for (let i = 0; i < array.length; i++) {

src/compiler/moduleSpecifiers.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,7 @@ namespace ts.moduleSpecifiers {
382382
}
383383

384384
function tryGetModuleNameFromAmbientModule(moduleSymbol: Symbol, checker: TypeChecker): string | undefined {
385-
const decl = find(moduleSymbol.declarations,
385+
const decl = moduleSymbol.declarations?.find(
386386
d => isNonGlobalAmbientModule(d) && (!isExternalModuleAugmentation(d) || !isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(d.name)))
387387
) as (ModuleDeclaration & { name: StringLiteral }) | undefined;
388388
if (decl) {

src/compiler/transformers/declarations.ts

+8-6
Original file line numberDiff line numberDiff line change
@@ -206,13 +206,15 @@ namespace ts {
206206
}
207207

208208
function reportNonlocalAugmentation(containingFile: SourceFile, parentSymbol: Symbol, symbol: Symbol) {
209-
const primaryDeclaration = find(parentSymbol.declarations, d => getSourceFileOfNode(d) === containingFile)!;
209+
const primaryDeclaration = parentSymbol.declarations?.find(d => getSourceFileOfNode(d) === containingFile)!;
210210
const augmentingDeclarations = filter(symbol.declarations, d => getSourceFileOfNode(d) !== containingFile);
211-
for (const augmentations of augmentingDeclarations) {
212-
context.addDiagnostic(addRelatedInfo(
213-
createDiagnosticForNode(augmentations, Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized),
214-
createDiagnosticForNode(primaryDeclaration, Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file)
215-
));
211+
if (augmentingDeclarations) {
212+
for (const augmentations of augmentingDeclarations) {
213+
context.addDiagnostic(addRelatedInfo(
214+
createDiagnosticForNode(augmentations, Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized),
215+
createDiagnosticForNode(primaryDeclaration, Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file)
216+
));
217+
}
216218
}
217219
}
218220

src/compiler/types.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -4714,7 +4714,7 @@ namespace ts {
47144714
export interface Symbol {
47154715
flags: SymbolFlags; // Symbol flags
47164716
escapedName: __String; // Name of symbol
4717-
declarations: Declaration[]; // Declarations associated with this symbol
4717+
declarations?: Declaration[]; // Declarations associated with this symbol
47184718
valueDeclaration: Declaration; // First value declaration of the symbol
47194719
members?: SymbolTable; // Class, interface or object literal instance members
47204720
exports?: SymbolTable; // Module exports

src/compiler/utilities.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -767,7 +767,7 @@ namespace ts {
767767
}
768768

769769
export function getNonAugmentationDeclaration(symbol: Symbol) {
770-
return find(symbol.declarations, d => !isExternalModuleAugmentation(d) && !(isModuleDeclaration(d) && isGlobalScopeAugmentation(d)));
770+
return symbol.declarations?.find(d => !isExternalModuleAugmentation(d) && !(isModuleDeclaration(d) && isGlobalScopeAugmentation(d)));
771771
}
772772

773773
export function isEffectiveExternalModule(node: SourceFile, compilerOptions: CompilerOptions) {
@@ -4888,15 +4888,15 @@ namespace ts {
48884888
}
48894889

48904890
export function getLocalSymbolForExportDefault(symbol: Symbol) {
4891-
if (!isExportDefaultSymbol(symbol)) return undefined;
4891+
if (!isExportDefaultSymbol(symbol) || !symbol.declarations) return undefined;
48924892
for (const decl of symbol.declarations) {
48934893
if (decl.localSymbol) return decl.localSymbol;
48944894
}
48954895
return undefined;
48964896
}
48974897

48984898
function isExportDefaultSymbol(symbol: Symbol): boolean {
4899-
return symbol && length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations[0], ModifierFlags.Default);
4899+
return symbol && length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations![0], ModifierFlags.Default);
49004900
}
49014901

49024902
/** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
@@ -5445,7 +5445,7 @@ namespace ts {
54455445
}
54465446

54475447
export function getClassLikeDeclarationOfSymbol(symbol: Symbol): ClassLikeDeclaration | undefined {
5448-
return find(symbol.declarations, isClassLike);
5448+
return symbol.declarations?.find(isClassLike);
54495449
}
54505450

54515451
export function getObjectFlags(type: Type): ObjectFlags {

src/harness/fourslashImpl.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1003,8 +1003,8 @@ namespace FourSlash {
10031003

10041004
private verifySymbol(symbol: ts.Symbol, declarationRanges: Range[]) {
10051005
const { declarations } = symbol;
1006-
if (declarations.length !== declarationRanges.length) {
1007-
this.raiseError(`Expected to get ${declarationRanges.length} declarations, got ${declarations.length}`);
1006+
if (declarations?.length !== declarationRanges.length) {
1007+
this.raiseError(`Expected to get ${declarationRanges.length} declarations, got ${declarations?.length}`);
10081008
}
10091009

10101010
ts.zipWith(declarations, declarationRanges, (decl, range) => {

src/services/callHierarchy.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ namespace ts.CallHierarchy {
181181
const indices = indicesOf(symbol.declarations);
182182
const keys = map(symbol.declarations, decl => ({ file: decl.getSourceFile().fileName, pos: decl.pos }));
183183
indices.sort((a, b) => compareStringsCaseSensitive(keys[a].file, keys[b].file) || keys[a].pos - keys[b].pos);
184-
const sortedDeclarations = map(indices, i => symbol.declarations[i]);
184+
const sortedDeclarations = map(indices, i => symbol.declarations![i]);
185185
let lastDecl: CallHierarchyDeclaration | undefined;
186186
for (const decl of sortedDeclarations) {
187187
if (isValidCallHierarchyDeclaration(decl)) {

src/services/codefixes/convertFunctionToEs6Class.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ namespace ts.codefix {
6161
// all static members are stored in the "exports" array of symbol
6262
if (symbol.exports) {
6363
symbol.exports.forEach(member => {
64-
if (member.name === "prototype") {
64+
if (member.name === "prototype" && member.declarations) {
6565
const firstDeclaration = member.declarations[0];
6666
// only one "x.prototype = { ... }" will pass
6767
if (member.declarations.length === 1 &&

src/services/codefixes/generateAccessors.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,7 @@ namespace ts.codefix {
262262
const superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression);
263263
if (!superSymbol) break;
264264
const symbol = superSymbol.flags & SymbolFlags.Alias ? checker.getAliasedSymbol(superSymbol) : superSymbol;
265-
const superDecl = find(symbol.declarations, isClassLike);
265+
const superDecl = symbol.declarations && find(symbol.declarations, isClassLike);
266266
if (!superDecl) break;
267267
res.push(superDecl);
268268
decl = superDecl;

src/services/completions.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -890,7 +890,7 @@ namespace ts.Completions {
890890
}
891891

892892
function isModuleSymbol(symbol: Symbol): boolean {
893-
return symbol.declarations.some(d => d.kind === SyntaxKind.SourceFile);
893+
return !!symbol.declarations?.some(d => d.kind === SyntaxKind.SourceFile);
894894
}
895895

896896
function getCompletionData(
@@ -1240,7 +1240,7 @@ namespace ts.Completions {
12401240
const isValidAccess: (symbol: Symbol) => boolean =
12411241
isNamespaceName
12421242
// At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion.
1243-
? symbol => !!(symbol.flags & SymbolFlags.Namespace) && !symbol.declarations.every(d => d.parent === node.parent)
1243+
? symbol => !!(symbol.flags & SymbolFlags.Namespace) && !symbol.declarations?.every(d => d.parent === node.parent)
12441244
: isRhsOfImportDeclaration ?
12451245
// Any kind is allowed when dotting off namespace in internal import equals declaration
12461246
symbol => isValidTypeAccess(symbol) || isValidValueAccess(symbol) :

src/services/findAllReferences.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -839,7 +839,7 @@ namespace ts.FindAllReferences {
839839
}
840840

841841
const exported = symbol.exports!.get(InternalSymbolName.ExportEquals);
842-
if (exported) {
842+
if (exported?.declarations) {
843843
for (const decl of exported.declarations) {
844844
const sourceFile = decl.getSourceFile();
845845
if (sourceFilesSet.has(sourceFile.fileName)) {
@@ -916,7 +916,7 @@ namespace ts.FindAllReferences {
916916
const result: SymbolAndEntries[] = [];
917917
const state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : SpecialSearchKind.None, checker, cancellationToken, searchMeaning, options, result);
918918

919-
const exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : find(symbol.declarations, isExportSpecifier);
919+
const exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) || !symbol.declarations ? undefined : find(symbol.declarations, isExportSpecifier);
920920
if (exportSpecifier) {
921921
// When renaming at an export specifier, rename the export and not the thing being exported.
922922
getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true);

src/services/getEditsForFileRename.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ namespace ts {
146146
importLiteral => {
147147
const importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral);
148148
// No need to update if it's an ambient module^M
149-
if (importedModuleSymbol && importedModuleSymbol.declarations.some(d => isAmbientModule(d))) return undefined;
149+
if (importedModuleSymbol?.declarations && importedModuleSymbol.declarations.some(d => isAmbientModule(d))) return undefined;
150150

151151
const toImport = oldFromNew !== undefined
152152
// If we're at the new location (file was already renamed), need to redo module resolution starting from the old location.
@@ -185,7 +185,7 @@ namespace ts {
185185
): ToImport | undefined {
186186
if (importedModuleSymbol) {
187187
// `find` should succeed because we checked for ambient modules before calling this function.
188-
const oldFileName = find(importedModuleSymbol.declarations, isSourceFile)!.fileName;
188+
const oldFileName = find(importedModuleSymbol.declarations!, isSourceFile)!.fileName;
189189
const newFileName = oldToNew(oldFileName);
190190
return newFileName === undefined ? { newFileName: oldFileName, updated: false } : { newFileName, updated: true };
191191
}

src/services/goToDefinition.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ namespace ts.GoToDefinition {
5151
// assignment. This case and others are handled by the following code.
5252
if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) {
5353
const shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration);
54-
const definitions = shorthandSymbol ? shorthandSymbol.declarations.map(decl => createDefinitionInfo(decl, typeChecker, shorthandSymbol, node)) : emptyArray;
54+
const definitions = shorthandSymbol?.declarations ? shorthandSymbol.declarations.map(decl => createDefinitionInfo(decl, typeChecker, shorthandSymbol, node)) : emptyArray;
5555
return concatenate(definitions, getDefinitionFromObjectLiteralElement(typeChecker, node) || emptyArray);
5656
}
5757

@@ -206,7 +206,7 @@ namespace ts.GoToDefinition {
206206
// get the aliased symbol instead. This allows for goto def on an import e.g.
207207
// import {A, B} from "mod";
208208
// to jump to the implementation directly.
209-
if (symbol && symbol.flags & SymbolFlags.Alias && shouldSkipAlias(node, symbol.declarations[0])) {
209+
if (symbol?.declarations && symbol.flags & SymbolFlags.Alias && shouldSkipAlias(node, symbol.declarations[0])) {
210210
const aliased = checker.getAliasedSymbol(symbol);
211211
if (aliased.declarations) {
212212
return aliased;
@@ -254,7 +254,7 @@ namespace ts.GoToDefinition {
254254
// Applicable only if we are in a new expression, or we are on a constructor declaration
255255
// and in either case the symbol has a construct signature definition, i.e. class
256256
if (symbol.flags & SymbolFlags.Class && !(symbol.flags & (SymbolFlags.Function | SymbolFlags.Variable)) && (isNewExpressionTarget(node) || node.kind === SyntaxKind.ConstructorKeyword)) {
257-
const cls = find(filteredDeclarations, isClassLike) || Debug.fail("Expected declaration to have at least one class-like declaration");
257+
const cls = find(filteredDeclarations!, isClassLike) || Debug.fail("Expected declaration to have at least one class-like declaration");
258258
return getSignatureDefinition(cls.members, /*selectConstructors*/ true);
259259
}
260260
}

src/services/importTracker.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,11 @@ namespace ts.FindAllReferences {
6262
}
6363

6464
// Module augmentations may use this module's exports without importing it.
65-
for (const decl of exportingModuleSymbol.declarations) {
66-
if (isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) {
67-
addIndirectUser(decl);
65+
if (exportingModuleSymbol.declarations) {
66+
for (const decl of exportingModuleSymbol.declarations) {
67+
if (isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) {
68+
addIndirectUser(decl);
69+
}
6870
}
6971
}
7072

@@ -468,7 +470,7 @@ namespace ts.FindAllReferences {
468470
if (parent.kind === SyntaxKind.PropertyAccessExpression) {
469471
// When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use.
470472
// So check that we are at the declaration.
471-
return symbol.declarations.some(d => d === parent) && isBinaryExpression(grandParent)
473+
return symbol.declarations?.some(d => d === parent) && isBinaryExpression(grandParent)
472474
? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false)
473475
: undefined;
474476
}

src/services/refactors/convertOverloadListToSingleSignature.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -201,10 +201,10 @@ ${newComment.split("\n").map(c => ` * ${c}`).join("\n")}
201201
if (!every(decls, d => getSourceFileOfNode(d) === file)) {
202202
return;
203203
}
204-
if (!isConvertableSignatureDeclaration(decls[0])) {
204+
if (!isConvertableSignatureDeclaration(decls![0])) {
205205
return;
206206
}
207-
const kindOne = decls[0].kind;
207+
const kindOne = decls![0].kind;
208208
if (!every(decls, d => d.kind === kindOne)) {
209209
return;
210210
}

src/services/refactors/convertParamsToDestructuredObject.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ namespace ts.refactor.convertParamsToDestructuredObject {
360360
if (isObjectLiteralExpression(functionDeclaration.parent)) {
361361
const contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker);
362362
// don't offer the refactor when there are multiple signatures since we won't know which ones the user wants to change
363-
return contextualSymbol?.declarations.length === 1 && isSingleImplementation(functionDeclaration, checker);
363+
return contextualSymbol?.declarations?.length === 1 && isSingleImplementation(functionDeclaration, checker);
364364
}
365365
return isSingleImplementation(functionDeclaration, checker);
366366
case SyntaxKind.Constructor:

src/services/refactors/extractType.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ namespace ts.refactor {
145145
if (isTypeReferenceNode(node)) {
146146
if (isIdentifier(node.typeName)) {
147147
const symbol = checker.resolveName(node.typeName.text, node.typeName, SymbolFlags.TypeParameter, /* excludeGlobals */ true);
148-
if (symbol) {
148+
if (symbol?.declarations) {
149149
const declaration = cast(first(symbol.declarations), isTypeParameterDeclaration);
150150
if (rangeContainsSkipTrivia(statement, declaration, file) && !rangeContainsSkipTrivia(selection, declaration, file)) {
151151
pushIfUnique(result, declaration);

src/services/refactors/moveToNewFile.ts

+3
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,9 @@ namespace ts.refactor {
443443
const oldFileNamedImports: string[] = [];
444444
const markSeenTop = nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`.
445445
newFileImportsFromOldFile.forEach(symbol => {
446+
if (!symbol.declarations) {
447+
return;
448+
}
446449
for (const decl of symbol.declarations) {
447450
if (!isTopLevelDeclaration(decl)) continue;
448451
const name = nameOfTopLevelDeclaration(decl);

src/services/rename.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ namespace ts.Rename {
6060
return getRenameInfoError(Diagnostics.You_cannot_rename_a_module_via_a_global_import);
6161
}
6262

63-
const moduleSourceFile = find(moduleSymbol.declarations, isSourceFile);
63+
const moduleSourceFile = moduleSymbol.declarations && find(moduleSymbol.declarations, isSourceFile);
6464
if (!moduleSourceFile) return undefined;
6565
const withoutIndex = endsWith(node.text, "/index") || endsWith(node.text, "/index.js") ? undefined : tryRemoveSuffix(removeFileExtension(moduleSourceFile.fileName), "/index");
6666
const name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex;

0 commit comments

Comments
 (0)