Skip to content

Commit 3e02a94

Browse files
authored
Merge pull request microsoft#567 from Microsoft/pgonzal/ae-trimming-5
[API Extractor] Initial implementation of member trimming
2 parents 0d9674e + dab2589 commit 3e02a94

21 files changed

Lines changed: 377 additions & 205 deletions

File tree

‎apps/api-extractor/src/generators/packageTypings/AstSymbol.ts‎

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ export interface IAstSymbolParameters {
1313
readonly localName: string;
1414
readonly astImport: AstImport | undefined;
1515
readonly nominal: boolean;
16+
readonly parentAstSymbol: AstSymbol | undefined;
1617
readonly rootAstSymbol: AstSymbol | undefined;
1718
}
1819

@@ -55,9 +56,25 @@ export class AstSymbol {
5556
*/
5657
public readonly nominal: boolean;
5758

58-
private readonly _astDeclarations: AstDeclaration[];
59+
/**
60+
* Returns the symbol of the parent of this AstSymbol, or undefined if there is no parent.
61+
* @remarks
62+
* If a symbol has multiple declarations, we assume (as an axiom) that their parent
63+
* declarations will belong to the same symbol. This means that the "parent" of a
64+
* symbol is a well-defined concept. However, the "children" of a symbol are not very
65+
* meaningful, because different declarations may have different nested members,
66+
* so we usually need to traverse declarations to find children.
67+
*/
68+
public readonly parentAstSymbol: AstSymbol | undefined;
5969

60-
private readonly _rootAstSymbol: AstSymbol;
70+
/**
71+
* Returns the symbol of the root of the AstDeclaration hierarchy.
72+
* @remarks
73+
* NOTE: If this AstSymbol is the root, then rootAstSymbol will point to itself.
74+
*/
75+
public readonly rootAstSymbol: AstSymbol;
76+
77+
private readonly _astDeclarations: AstDeclaration[];
6178

6279
// This flag is unused if this is not the root symbol.
6380
// Being "analyzed" is a property of the root symbol.
@@ -68,7 +85,8 @@ export class AstSymbol {
6885
this.localName = parameters.localName;
6986
this.astImport = parameters.astImport;
7087
this.nominal = parameters.nominal;
71-
this._rootAstSymbol = parameters.rootAstSymbol || this;
88+
this.parentAstSymbol = parameters.parentAstSymbol;
89+
this.rootAstSymbol = parameters.rootAstSymbol || this;
7290
this._astDeclarations = [];
7391
}
7492

@@ -93,13 +111,6 @@ export class AstSymbol {
93111
return this.rootAstSymbol._analyzed;
94112
}
95113

96-
/**
97-
* Returns the symbol of the root of the AstDeclaration hierarchy.
98-
*/
99-
public get rootAstSymbol(): AstSymbol {
100-
return this._rootAstSymbol;
101-
}
102-
103114
/**
104115
* Returns true if this symbol was imported from another package.
105116
*/
@@ -125,7 +136,7 @@ export class AstSymbol {
125136
* @internal
126137
*/
127138
public _notifyAnalyzed(): void {
128-
if (this.rootAstSymbol !== this) {
139+
if (this.parentAstSymbol) {
129140
throw new Error('Program Bug: _notifyAnalyzed() called for an AstSymbol which is not the root');
130141
}
131142
this._analyzed = true;

‎apps/api-extractor/src/generators/packageTypings/AstSymbolTable.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,7 @@ export class AstSymbolTable {
334334
// If D1 has a parent P1, then
335335
// - D2 will also have a parent P2; AND
336336
// - P1 and P2's symbol will be the same
337+
// - but P1 and P2 may be different (e.g. merged namespaces containing merged interfaces)
337338

338339
// Is there a parent AstSymbol? First we check to see if there is a parent declaration:
339340
const arbitaryParentDeclaration: ts.Node | undefined
@@ -355,6 +356,7 @@ export class AstSymbolTable {
355356
localName: followAliasesResult.localName,
356357
followedSymbol: followAliasesResult.followedSymbol,
357358
astImport: astImport,
359+
parentAstSymbol: parentAstSymbol,
358360
rootAstSymbol: parentAstSymbol ? parentAstSymbol.rootAstSymbol : undefined,
359361
nominal: nominal
360362
});

‎apps/api-extractor/src/generators/packageTypings/DtsEntry.ts‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
// See LICENSE in the project root for license information.
33

44
import { AstSymbol } from './AstSymbol';
5-
import { ReleaseTag } from '../../aedoc/ReleaseTag';
65

76
/**
87
* Constructor parameters for DtsEntry
@@ -11,7 +10,6 @@ export interface IDtsEntryParameters {
1110
readonly astSymbol: AstSymbol;
1211
readonly originalName: string;
1312
readonly exported: boolean;
14-
readonly releaseTag: ReleaseTag;
1513
}
1614

1715
/**
@@ -39,11 +37,6 @@ export class DtsEntry {
3937
*/
4038
public readonly exported: boolean;
4139

42-
/**
43-
* The ReleaseTag used for trimming
44-
*/
45-
public readonly releaseTag: ReleaseTag;
46-
4740
private _nameForEmit: string | undefined = undefined;
4841

4942
private _sortKey: string | undefined = undefined;
@@ -52,7 +45,6 @@ export class DtsEntry {
5245
this.astSymbol = parameters.astSymbol;
5346
this.originalName = parameters.originalName;
5447
this.exported = parameters.exported;
55-
this.releaseTag = parameters.releaseTag;
5648
}
5749

5850
/**

‎apps/api-extractor/src/generators/packageTypings/PackageTypingsGenerator.ts‎

Lines changed: 120 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,15 @@ import { Text } from '@microsoft/node-core-library';
1010
import { ExtractorContext } from '../../ExtractorContext';
1111
import { IndentedWriter } from '../../utils/IndentedWriter';
1212
import { TypeScriptHelpers } from '../../utils/TypeScriptHelpers';
13-
import { Span } from '../../utils/Span';
13+
import { Span, SpanModification } from '../../utils/Span';
1414
import { ReleaseTag } from '../../aedoc/ReleaseTag';
1515
import { AstSymbolTable } from './AstSymbolTable';
1616
import { AstEntryPoint } from './AstEntryPoint';
1717
import { AstSymbol } from './AstSymbol';
1818
import { AstImport } from './AstImport';
1919
import { DtsEntry } from './DtsEntry';
2020
import { AstDeclaration } from './AstDeclaration';
21+
import { SymbolAnalyzer } from './SymbolAnalyzer';
2122

2223
/**
2324
* Used with PackageTypingsGenerator.writeTypingsFile()
@@ -53,6 +54,7 @@ export class PackageTypingsGenerator {
5354
private _dtsEntries: DtsEntry[] = [];
5455
private _dtsEntriesByAstSymbol: Map<AstSymbol, DtsEntry> = new Map<AstSymbol, DtsEntry>();
5556
private _dtsEntriesBySymbol: Map<ts.Symbol, DtsEntry> = new Map<ts.Symbol, DtsEntry>();
57+
private _releaseTagByAstSymbol: Map<AstSymbol, ReleaseTag> = new Map<AstSymbol, ReleaseTag>();
5658

5759
/**
5860
* A list of names (e.g. "example-library") that should appear in a reference like this:
@@ -131,13 +133,10 @@ export class PackageTypingsGenerator {
131133
let dtsEntry: DtsEntry | undefined = this._dtsEntriesByAstSymbol.get(astSymbol);
132134

133135
if (!dtsEntry) {
134-
const releaseTag: ReleaseTag = this._getReleaseTagForSymbol(astSymbol.followedSymbol);
135-
136136
dtsEntry = new DtsEntry({
137137
astSymbol: astSymbol,
138138
originalName: exportedName || astSymbol.localName,
139-
exported: !!exportedName,
140-
releaseTag: releaseTag
139+
exported: !!exportedName
141140
});
142141

143142
this._dtsEntriesByAstSymbol.set(astSymbol, dtsEntry);
@@ -247,20 +246,22 @@ export class PackageTypingsGenerator {
247246
for (const dtsEntry of this._dtsEntries) {
248247
if (!dtsEntry.astSymbol.astImport) {
249248

250-
if (this._shouldIncludeReleaseTag(dtsEntry.releaseTag, dtsKind)) {
249+
const releaseTag: ReleaseTag = this._getReleaseTagForAstSymbol(dtsEntry.astSymbol);
250+
251+
if (this._shouldIncludeReleaseTag(releaseTag, dtsKind)) {
251252

252253
// Emit all the declarations for this entry
253254
for (const astDeclaration of dtsEntry.astSymbol.astDeclarations || []) {
254255

255256
indentedWriter.writeLine();
256257

257258
const span: Span = new Span(astDeclaration.declaration);
258-
this._modifySpan(span, dtsEntry);
259+
this._modifySpan(span, dtsEntry, astDeclaration, dtsKind);
259260
indentedWriter.writeLine(span.getModifiedText());
260261
}
261262
} else {
262263
indentedWriter.writeLine();
263-
indentedWriter.writeLine(`// Removed for this release type: ${dtsEntry.nameForEmit}`);
264+
indentedWriter.writeLine(`/* Excluded from this release type: ${dtsEntry.nameForEmit} */`);
264265
}
265266
}
266267
}
@@ -269,11 +270,12 @@ export class PackageTypingsGenerator {
269270
/**
270271
* Before writing out a declaration, _modifySpan() applies various fixups to make it nice.
271272
*/
272-
private _modifySpan(span: Span, dtsEntry: DtsEntry): void {
273+
private _modifySpan(span: Span, dtsEntry: DtsEntry, astDeclaration: AstDeclaration,
274+
dtsKind: PackageTypingsDtsKind): void {
275+
273276
const previousSpan: Span | undefined = span.previousSibling;
274277

275278
let recurseChildren: boolean = true;
276-
277279
switch (span.kind) {
278280
case ts.SyntaxKind.JSDocComment:
279281
// For now, we don't transform JSDoc comment nodes at all
@@ -295,7 +297,12 @@ export class PackageTypingsGenerator {
295297
case ts.SyntaxKind.TypeKeyword:
296298
case ts.SyntaxKind.FunctionKeyword:
297299
// Replace the stuff we possibly deleted above
298-
let replacedModifiers: string = 'declare ';
300+
let replacedModifiers: string = '';
301+
302+
// Add a declare statement for root declarations (but not for nested declarations)
303+
if (!astDeclaration.parent) {
304+
replacedModifiers += 'declare ';
305+
}
299306

300307
if (dtsEntry.exported) {
301308
replacedModifiers = 'export ' + replacedModifiers;
@@ -364,7 +371,47 @@ export class PackageTypingsGenerator {
364371

365372
if (recurseChildren) {
366373
for (const child of span.children) {
367-
this._modifySpan(child, dtsEntry);
374+
let childAstDeclaration: AstDeclaration = astDeclaration;
375+
376+
// Should we trim this node?
377+
let trimmed: boolean = false;
378+
if (SymbolAnalyzer.isAstDeclaration(child.kind)) {
379+
childAstDeclaration = this._astSymbolTable.getChildAstDeclarationByNode(child.node, astDeclaration);
380+
381+
const releaseTag: ReleaseTag = this._getReleaseTagForAstSymbol(childAstDeclaration.astSymbol);
382+
if (!this._shouldIncludeReleaseTag(releaseTag, dtsKind)) {
383+
const modification: SpanModification = child.modification;
384+
385+
// Yes, trim it and stop here
386+
const name: string = childAstDeclaration.astSymbol.localName;
387+
modification.omitChildren = true;
388+
389+
modification.prefix = `/* Excluded from this release type: ${name} */`;
390+
modification.suffix = '';
391+
392+
if (child.children.length > 0) {
393+
// If there are grandchildren, then keep the last grandchild's separator,
394+
// since it often has useful whitespace
395+
modification.suffix = child.children[child.children.length - 1].separator;
396+
}
397+
398+
if (child.nextSibling) {
399+
// If the thing we are trimming is followed by a comma, then trim the comma also.
400+
// An example would be an enum member.
401+
if (child.nextSibling.kind === ts.SyntaxKind.CommaToken) {
402+
// Keep its separator since it often has useful whitespace
403+
modification.suffix += child.nextSibling.separator;
404+
child.nextSibling.modification.skipAll();
405+
}
406+
}
407+
408+
trimmed = true;
409+
}
410+
}
411+
412+
if (!trimmed) {
413+
this._modifySpan(child, dtsEntry, childAstDeclaration, dtsKind);
414+
}
368415
}
369416
}
370417
}
@@ -383,46 +430,78 @@ export class PackageTypingsGenerator {
383430
throw new Error(`PackageTypingsDtsKind[dtsKind] is not implemented`);
384431
}
385432

433+
private _getReleaseTagForAstSymbol(astSymbol: AstSymbol): ReleaseTag {
434+
let releaseTag: ReleaseTag | undefined = this._releaseTagByAstSymbol.get(astSymbol);
435+
if (releaseTag) {
436+
return releaseTag;
437+
}
438+
439+
releaseTag = ReleaseTag.None;
440+
441+
let current: AstSymbol | undefined = astSymbol;
442+
while (current) {
443+
for (const astDeclaration of current.astDeclarations) {
444+
const declarationReleaseTag: ReleaseTag = this._getReleaseTagForDeclaration(astDeclaration.declaration);
445+
if (releaseTag !== ReleaseTag.None && declarationReleaseTag !== releaseTag) {
446+
// this._analyzeWarnings.push('WARNING: Conflicting release tags found for ' + symbol.name);
447+
break;
448+
}
449+
450+
releaseTag = declarationReleaseTag;
451+
}
452+
453+
if (releaseTag !== ReleaseTag.None) {
454+
break;
455+
}
456+
457+
current = current.parentAstSymbol;
458+
}
459+
460+
if (releaseTag === ReleaseTag.None) {
461+
releaseTag = ReleaseTag.Public; // public by default
462+
}
463+
464+
this._releaseTagByAstSymbol.set(astSymbol, releaseTag);
465+
466+
return releaseTag;
467+
}
468+
386469
// NOTE: THIS IS A TEMPORARY WORKAROUND.
387470
// In the near future we will overhaul the AEDoc parser to separate syntactic/semantic analysis,
388471
// at which point this will be wired up to the same ApiDocumentation layer used for the API Review files
389-
private _getReleaseTagForSymbol(symbol: ts.Symbol): ReleaseTag {
390-
const fullyFollowedSymbol: ts.Symbol = TypeScriptHelpers.followAliases(symbol, this._typeChecker);
391-
472+
private _getReleaseTagForDeclaration(declaration: ts.Node): ReleaseTag {
392473
let releaseTag: ReleaseTag = ReleaseTag.None;
393474

394475
// We don't want to match "bill@example.com". But we do want to match "/**@public*/".
395476
// So for now we require whitespace or a star before/after the string.
396477
const releaseTagRegExp: RegExp = /(?:\s|\*)@(internal|alpha|beta|public)(?:\s|\*)/g;
397478

398-
for (const declaration of fullyFollowedSymbol.declarations || []) {
399-
const sourceFileText: string = declaration.getSourceFile().text;
400-
401-
for (const commentRange of TypeScriptHelpers.getJSDocCommentRanges(declaration, sourceFileText) || []) {
402-
// NOTE: This string includes "/**"
403-
const comment: string = sourceFileText.substring(commentRange.pos, commentRange.end);
404-
405-
let match: RegExpMatchArray | null;
406-
while (match = releaseTagRegExp.exec(comment)) {
407-
let foundReleaseTag: ReleaseTag = ReleaseTag.None;
408-
switch (match[1]) {
409-
case 'internal':
410-
foundReleaseTag = ReleaseTag.Internal; break;
411-
case 'alpha':
412-
foundReleaseTag = ReleaseTag.Alpha; break;
413-
case 'beta':
414-
foundReleaseTag = ReleaseTag.Beta; break;
415-
case 'public':
416-
foundReleaseTag = ReleaseTag.Public; break;
417-
}
418-
419-
if (releaseTag !== ReleaseTag.None && foundReleaseTag !== releaseTag) {
420-
// this._analyzeWarnings.push('WARNING: Conflicting release tags found for ' + symbol.name);
421-
return releaseTag;
422-
}
479+
const sourceFileText: string = declaration.getSourceFile().text;
480+
481+
for (const commentRange of TypeScriptHelpers.getJSDocCommentRanges(declaration, sourceFileText) || []) {
482+
// NOTE: This string includes "/**"
483+
const comment: string = sourceFileText.substring(commentRange.pos, commentRange.end);
484+
485+
let match: RegExpMatchArray | null;
486+
while (match = releaseTagRegExp.exec(comment)) {
487+
let foundReleaseTag: ReleaseTag = ReleaseTag.None;
488+
switch (match[1]) {
489+
case 'internal':
490+
foundReleaseTag = ReleaseTag.Internal; break;
491+
case 'alpha':
492+
foundReleaseTag = ReleaseTag.Alpha; break;
493+
case 'beta':
494+
foundReleaseTag = ReleaseTag.Beta; break;
495+
case 'public':
496+
foundReleaseTag = ReleaseTag.Public; break;
497+
}
423498

424-
releaseTag = foundReleaseTag;
499+
if (releaseTag !== ReleaseTag.None && foundReleaseTag !== releaseTag) {
500+
// this._analyzeWarnings.push('WARNING: Conflicting release tags found for ' + symbol.name);
501+
return releaseTag;
425502
}
503+
504+
releaseTag = foundReleaseTag;
426505
}
427506
}
428507

0 commit comments

Comments
 (0)