UNPKG

13.1 kBJavaScriptView Raw
1"use strict";
2// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
3// See LICENSE in the project root for license information.
4var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5 if (k2 === undefined) k2 = k;
6 var desc = Object.getOwnPropertyDescriptor(m, k);
7 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8 desc = { enumerable: true, get: function() { return m[k]; } };
9 }
10 Object.defineProperty(o, k2, desc);
11}) : (function(o, m, k, k2) {
12 if (k2 === undefined) k2 = k;
13 o[k2] = m[k];
14}));
15var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16 Object.defineProperty(o, "default", { enumerable: true, value: v });
17}) : function(o, v) {
18 o["default"] = v;
19});
20var __importStar = (this && this.__importStar) || function (mod) {
21 if (mod && mod.__esModule) return mod;
22 var result = {};
23 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
24 __setModuleDefault(result, mod);
25 return result;
26};
27Object.defineProperty(exports, "__esModule", { value: true });
28exports.ExcerptBuilder = void 0;
29const ts = __importStar(require("typescript"));
30const api_extractor_model_1 = require("@microsoft/api-extractor-model");
31const Span_1 = require("../analyzer/Span");
32class ExcerptBuilder {
33 /**
34 * Appends a blank line to the `excerptTokens` list.
35 * @param excerptTokens - The target token list to append to
36 */
37 static addBlankLine(excerptTokens) {
38 let newlines = '\n\n';
39 // If the existing text already ended with a newline, then only append one newline
40 if (excerptTokens.length > 0) {
41 const previousText = excerptTokens[excerptTokens.length - 1].text;
42 if (/\n$/.test(previousText)) {
43 newlines = '\n';
44 }
45 }
46 excerptTokens.push({ kind: api_extractor_model_1.ExcerptTokenKind.Content, text: newlines });
47 }
48 /**
49 * Appends the signature for the specified `AstDeclaration` to the `excerptTokens` list.
50 * @param excerptTokens - The target token list to append to
51 * @param nodesToCapture - A list of child nodes whose token ranges we want to capture
52 */
53 static addDeclaration(excerptTokens, astDeclaration, nodesToCapture, referenceGenerator) {
54 let stopBeforeChildKind = undefined;
55 switch (astDeclaration.declaration.kind) {
56 case ts.SyntaxKind.ClassDeclaration:
57 case ts.SyntaxKind.EnumDeclaration:
58 case ts.SyntaxKind.InterfaceDeclaration:
59 // FirstPunctuation = "{"
60 stopBeforeChildKind = ts.SyntaxKind.FirstPunctuation;
61 break;
62 case ts.SyntaxKind.ModuleDeclaration:
63 // ModuleBlock = the "{ ... }" block
64 stopBeforeChildKind = ts.SyntaxKind.ModuleBlock;
65 break;
66 }
67 const span = new Span_1.Span(astDeclaration.declaration);
68 const tokenRangesByNode = new Map();
69 for (const excerpt of nodesToCapture || []) {
70 if (excerpt.node) {
71 tokenRangesByNode.set(excerpt.node, excerpt.tokenRange);
72 }
73 }
74 ExcerptBuilder._buildSpan(excerptTokens, span, {
75 referenceGenerator: referenceGenerator,
76 startingNode: span.node,
77 stopBeforeChildKind,
78 tokenRangesByNode,
79 lastAppendedTokenIsSeparator: false
80 });
81 ExcerptBuilder._condenseTokens(excerptTokens, [...tokenRangesByNode.values()]);
82 }
83 static createEmptyTokenRange() {
84 return { startIndex: 0, endIndex: 0 };
85 }
86 static _buildSpan(excerptTokens, span, state) {
87 if (span.kind === ts.SyntaxKind.JSDocComment) {
88 // Discard any comments
89 return true;
90 }
91 // Can this node start a excerpt?
92 const capturedTokenRange = state.tokenRangesByNode.get(span.node);
93 let excerptStartIndex = 0;
94 if (capturedTokenRange) {
95 // We will assign capturedTokenRange.startIndex to be the index of the next token to be appended
96 excerptStartIndex = excerptTokens.length;
97 }
98 if (span.prefix) {
99 let canonicalReference = undefined;
100 if (span.kind === ts.SyntaxKind.Identifier) {
101 const name = span.node;
102 if (!ExcerptBuilder._isDeclarationName(name)) {
103 canonicalReference = state.referenceGenerator.getDeclarationReferenceForIdentifier(name);
104 }
105 }
106 if (canonicalReference) {
107 ExcerptBuilder._appendToken(excerptTokens, api_extractor_model_1.ExcerptTokenKind.Reference, span.prefix, canonicalReference);
108 }
109 else {
110 ExcerptBuilder._appendToken(excerptTokens, api_extractor_model_1.ExcerptTokenKind.Content, span.prefix);
111 }
112 state.lastAppendedTokenIsSeparator = false;
113 }
114 for (const child of span.children) {
115 if (span.node === state.startingNode) {
116 if (state.stopBeforeChildKind && child.kind === state.stopBeforeChildKind) {
117 // We reached a child whose kind is stopBeforeChildKind, so stop traversing
118 return false;
119 }
120 }
121 if (!this._buildSpan(excerptTokens, child, state)) {
122 return false;
123 }
124 }
125 if (span.suffix) {
126 ExcerptBuilder._appendToken(excerptTokens, api_extractor_model_1.ExcerptTokenKind.Content, span.suffix);
127 state.lastAppendedTokenIsSeparator = false;
128 }
129 if (span.separator) {
130 ExcerptBuilder._appendToken(excerptTokens, api_extractor_model_1.ExcerptTokenKind.Content, span.separator);
131 state.lastAppendedTokenIsSeparator = true;
132 }
133 // Are we building a excerpt? If so, set its range
134 if (capturedTokenRange) {
135 capturedTokenRange.startIndex = excerptStartIndex;
136 // We will assign capturedTokenRange.startIndex to be the index after the last token
137 // that was appended so far. However, if the last appended token was a separator, omit
138 // it from the range.
139 let excerptEndIndex = excerptTokens.length;
140 if (state.lastAppendedTokenIsSeparator) {
141 excerptEndIndex--;
142 }
143 capturedTokenRange.endIndex = excerptEndIndex;
144 }
145 return true;
146 }
147 static _appendToken(excerptTokens, excerptTokenKind, text, canonicalReference) {
148 if (text.length === 0) {
149 return;
150 }
151 const excerptToken = { kind: excerptTokenKind, text: text };
152 if (canonicalReference !== undefined) {
153 excerptToken.canonicalReference = canonicalReference.toString();
154 }
155 excerptTokens.push(excerptToken);
156 }
157 /**
158 * Condenses the provided excerpt tokens by merging tokens where possible. Updates the provided token ranges to
159 * remain accurate after token merging.
160 *
161 * @remarks
162 * For example, suppose we have excerpt tokens ["A", "B", "C"] and a token range [0, 2]. If the excerpt tokens
163 * are condensed to ["AB", "C"], then the token range would be updated to [0, 1]. Note that merges are only
164 * performed if they are compatible with the provided token ranges. In the example above, if our token range was
165 * originally [0, 1], we would not be able to merge tokens "A" and "B".
166 */
167 static _condenseTokens(excerptTokens, tokenRanges) {
168 // This set is used to quickly lookup a start or end index.
169 const startOrEndIndices = new Set();
170 for (const tokenRange of tokenRanges) {
171 startOrEndIndices.add(tokenRange.startIndex);
172 startOrEndIndices.add(tokenRange.endIndex);
173 }
174 for (let currentIndex = 1; currentIndex < excerptTokens.length; ++currentIndex) {
175 while (currentIndex < excerptTokens.length) {
176 const prevPrevToken = excerptTokens[currentIndex - 2]; // May be undefined
177 const prevToken = excerptTokens[currentIndex - 1];
178 const currentToken = excerptTokens[currentIndex];
179 // The number of excerpt tokens that are merged in this iteration. We need this to determine
180 // how to update the start and end indices of our token ranges.
181 let mergeCount;
182 // There are two types of merges that can occur. We only perform these merges if they are
183 // compatible with all of our token ranges.
184 if (prevPrevToken &&
185 prevPrevToken.kind === api_extractor_model_1.ExcerptTokenKind.Reference &&
186 prevToken.kind === api_extractor_model_1.ExcerptTokenKind.Content &&
187 prevToken.text.trim() === '.' &&
188 currentToken.kind === api_extractor_model_1.ExcerptTokenKind.Reference &&
189 !startOrEndIndices.has(currentIndex) &&
190 !startOrEndIndices.has(currentIndex - 1)) {
191 // If the current token is a reference token, the previous token is a ".", and the previous-
192 // previous token is a reference token, then merge all three tokens into a reference token.
193 //
194 // For example: Given ["MyNamespace" (R), ".", "MyClass" (R)], tokens "." and "MyClass" might
195 // be merged into "MyNamespace". The condensed token would be ["MyNamespace.MyClass" (R)].
196 prevPrevToken.text += prevToken.text + currentToken.text;
197 prevPrevToken.canonicalReference = currentToken.canonicalReference;
198 mergeCount = 2;
199 currentIndex--;
200 }
201 else if (
202 // If the current and previous tokens are both content tokens, then merge the tokens into a
203 // single content token. For example: Given ["export ", "declare class"], these tokens
204 // might be merged into "export declare class".
205 prevToken.kind === api_extractor_model_1.ExcerptTokenKind.Content &&
206 prevToken.kind === currentToken.kind &&
207 !startOrEndIndices.has(currentIndex)) {
208 prevToken.text += currentToken.text;
209 mergeCount = 1;
210 }
211 else {
212 // Otherwise, no merging can occur here. Continue to the next index.
213 break;
214 }
215 // Remove the now redundant excerpt token(s), as they were merged into a previous token.
216 excerptTokens.splice(currentIndex, mergeCount);
217 // Update the start and end indices for all token ranges based upon how many excerpt
218 // tokens were merged and in what positions.
219 for (const tokenRange of tokenRanges) {
220 if (tokenRange.startIndex > currentIndex) {
221 tokenRange.startIndex -= mergeCount;
222 }
223 if (tokenRange.endIndex > currentIndex) {
224 tokenRange.endIndex -= mergeCount;
225 }
226 }
227 // Clear and repopulate our set with the updated indices.
228 startOrEndIndices.clear();
229 for (const tokenRange of tokenRanges) {
230 startOrEndIndices.add(tokenRange.startIndex);
231 startOrEndIndices.add(tokenRange.endIndex);
232 }
233 }
234 }
235 }
236 static _isDeclarationName(name) {
237 return ExcerptBuilder._isDeclaration(name.parent) && name.parent.name === name;
238 }
239 static _isDeclaration(node) {
240 switch (node.kind) {
241 case ts.SyntaxKind.FunctionDeclaration:
242 case ts.SyntaxKind.FunctionExpression:
243 case ts.SyntaxKind.VariableDeclaration:
244 case ts.SyntaxKind.Parameter:
245 case ts.SyntaxKind.EnumDeclaration:
246 case ts.SyntaxKind.ClassDeclaration:
247 case ts.SyntaxKind.ClassExpression:
248 case ts.SyntaxKind.ModuleDeclaration:
249 case ts.SyntaxKind.MethodDeclaration:
250 case ts.SyntaxKind.MethodSignature:
251 case ts.SyntaxKind.PropertyDeclaration:
252 case ts.SyntaxKind.PropertySignature:
253 case ts.SyntaxKind.GetAccessor:
254 case ts.SyntaxKind.SetAccessor:
255 case ts.SyntaxKind.InterfaceDeclaration:
256 case ts.SyntaxKind.TypeAliasDeclaration:
257 case ts.SyntaxKind.TypeParameter:
258 case ts.SyntaxKind.EnumMember:
259 case ts.SyntaxKind.BindingElement:
260 return true;
261 default:
262 return false;
263 }
264 }
265}
266exports.ExcerptBuilder = ExcerptBuilder;
267//# sourceMappingURL=ExcerptBuilder.js.map
\No newline at end of file