From 166bc49f0c666f5a2a75bcfacd421e6b8f5135c7 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 16 Jun 2016 13:20:12 -0700 Subject: [PATCH 1/2] Refactor navigation bar --- src/compiler/core.ts | 11 + src/compiler/parser.ts | 8 +- src/server/client.ts | 17 +- src/server/editorServices.ts | 14 +- src/server/session.ts | 10 +- src/services/navigationBar.ts | 1304 +++++++---------- src/services/services.ts | 2 +- .../navbar_contains-no-duplicates.ts | 14 +- tests/cases/fourslash/navbar_exportDefault.ts | 16 +- ...BarAnonymousClassAndFunctionExpressions.ts | 147 ++ ...arAnonymousClassAndFunctionExpressions2.ts | 64 + .../fourslash/navigationBarGetterAndSetter.ts | 48 + tests/cases/fourslash/navigationBarImports.ts | 30 + .../fourslash/navigationBarItemsFunctions.ts | 14 + .../navigationBarItemsFunctionsBroken.ts | 6 + .../navigationBarItemsFunctionsBroken2.ts | 10 + ...ionBarItemsInsideMethodsAndConstructors.ts | 12 +- .../fourslash/navigationBarItemsItems2.ts | 7 +- ...rItemsItemsContainsNoAnonymousFunctions.ts | 80 - .../navigationBarItemsMissingName1.ts | 5 + .../navigationBarItemsMissingName2.ts | 10 +- .../fourslash/navigationBarItemsModules.ts | 196 +-- ...ationBarItemsMultilineStringIdentifiers.ts | 56 +- tests/cases/fourslash/navigationBarJsDoc.ts | 26 +- tests/cases/fourslash/navigationBarMerging.ts | 189 +++ .../cases/fourslash/navigationBarVariables.ts | 53 + .../server/jsdocTypedefTagNavigateTo.ts | 48 +- 27 files changed, 1380 insertions(+), 1017 deletions(-) create mode 100644 tests/cases/fourslash/navigationBarAnonymousClassAndFunctionExpressions.ts create mode 100644 tests/cases/fourslash/navigationBarAnonymousClassAndFunctionExpressions2.ts create mode 100644 tests/cases/fourslash/navigationBarGetterAndSetter.ts create mode 100644 tests/cases/fourslash/navigationBarImports.ts delete mode 100644 tests/cases/fourslash/navigationBarItemsItemsContainsNoAnonymousFunctions.ts create mode 100644 tests/cases/fourslash/navigationBarMerging.ts create mode 100644 tests/cases/fourslash/navigationBarVariables.ts diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 8a2040a83df07..10a0526d6ae1e 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -138,6 +138,17 @@ namespace ts { return result; } + export function filterMutate(array: T[], f: (x: T) => boolean): void { + let outIndex = 0; + for (const item of array) { + if (f(item)) { + array[outIndex] = item; + outIndex++; + } + } + array.length = outIndex; + } + export function map(array: T[], f: (x: T) => U): U[] { let result: U[]; if (array) { diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index b2f3755ec46be..6e0a37c3d9fbf 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -17,19 +17,19 @@ namespace ts { } function visitNode(cbNode: (node: Node) => T, node: Node): T { - if (node) { + if (node !== void 0) { return cbNode(node); } } function visitNodeArray(cbNodes: (nodes: Node[]) => T, nodes: Node[]) { - if (nodes) { + if (nodes !== void 0) { return cbNodes(nodes); } } function visitEachNode(cbNode: (node: Node) => T, nodes: Node[]) { - if (nodes) { + if (nodes !== void 0) { for (const node of nodes) { const result = cbNode(node); if (result) { @@ -44,7 +44,7 @@ namespace ts { // embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns // a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. export function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T { - if (!node) { + if (node === void 0) { return; } // The visitXXX functions could be written as local functions that close over the cbNode and cbNodeArray diff --git a/src/server/client.ts b/src/server/client.ts index 864dac9fdaaa1..09cfa2ac739fc 100644 --- a/src/server/client.ts +++ b/src/server/client.ts @@ -45,8 +45,9 @@ namespace ts.server { return lineMap; } - private lineOffsetToPosition(fileName: string, lineOffset: protocol.Location): number { - return ts.computePositionOfLineAndCharacter(this.getLineMap(fileName), lineOffset.line - 1, lineOffset.offset - 1); + private lineOffsetToPosition(fileName: string, lineOffset: protocol.Location, lineMap?: number[]): number { + lineMap = lineMap || this.getLineMap(fileName); + return ts.computePositionOfLineAndCharacter(lineMap, lineOffset.line - 1, lineOffset.offset - 1); } private positionToOneBasedLineOffset(fileName: string, position: number): protocol.Location { @@ -449,7 +450,7 @@ namespace ts.server { return this.lastRenameEntry.locations; } - decodeNavigationBarItems(items: protocol.NavigationBarItem[], fileName: string): NavigationBarItem[] { + decodeNavigationBarItems(items: protocol.NavigationBarItem[], fileName: string, lineMap: number[]): NavigationBarItem[] { if (!items) { return []; } @@ -458,8 +459,11 @@ namespace ts.server { text: item.text, kind: item.kind, kindModifiers: item.kindModifiers || "", - spans: item.spans.map(span => createTextSpanFromBounds(this.lineOffsetToPosition(fileName, span.start), this.lineOffsetToPosition(fileName, span.end))), - childItems: this.decodeNavigationBarItems(item.childItems, fileName), + spans: item.spans.map(span => + createTextSpanFromBounds( + this.lineOffsetToPosition(fileName, span.start, lineMap), + this.lineOffsetToPosition(fileName, span.end, lineMap))), + childItems: this.decodeNavigationBarItems(item.childItems, fileName, lineMap), indent: item.indent, bolded: false, grayed: false @@ -474,7 +478,8 @@ namespace ts.server { const request = this.processRequest(CommandNames.NavBar, args); const response = this.processResponse(request); - return this.decodeNavigationBarItems(response.body, fileName); + const lineMap = this.getLineMap(fileName); + return this.decodeNavigationBarItems(response.body, fileName, lineMap); } getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan { diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 346b2e00a109a..74dbb7a078513 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -359,12 +359,16 @@ namespace ts.server { * @param line 1-based index * @param offset 1-based index */ - positionToLineOffset(filename: string, position: number): ILineInfo { + positionToLineOffset(filename: string, position: number, lineIndex?: LineIndex): ILineInfo { + lineIndex = lineIndex || this.getLineIndex(filename); + const lineOffset = lineIndex.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + } + + getLineIndex(filename: string): LineIndex { const path = toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); const script: ScriptInfo = this.filenameToScript.get(path); - const index = script.snap().index; - const lineOffset = index.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + return script.snap().index; } } @@ -1452,7 +1456,7 @@ namespace ts.server { } // if the project is too large, the root files might not have been all loaded if the total - // program size reached the upper limit. In that case project.projectOptions.files should + // program size reached the upper limit. In that case project.projectOptions.files should // be more precise. However this would only happen for configured project. const oldFileNames = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(info => info.fileName); const newFileNames = ts.filter(projectOptions.files, f => this.host.fileExists(f)); diff --git a/src/server/session.ts b/src/server/session.ts index 65540082f6068..aafc02a2b0b6d 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -863,7 +863,7 @@ namespace ts.server { this.projectService.closeClientFile(file); } - private decorateNavigationBarItem(project: Project, fileName: string, items: ts.NavigationBarItem[]): protocol.NavigationBarItem[] { + private decorateNavigationBarItem(project: Project, fileName: string, items: ts.NavigationBarItem[], lineIndex: LineIndex): protocol.NavigationBarItem[] { if (!items) { return undefined; } @@ -875,10 +875,10 @@ namespace ts.server { kind: item.kind, kindModifiers: item.kindModifiers, spans: item.spans.map(span => ({ - start: compilerService.host.positionToLineOffset(fileName, span.start), - end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span)) + start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex), + end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex) })), - childItems: this.decorateNavigationBarItem(project, fileName, item.childItems), + childItems: this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex), indent: item.indent })); } @@ -896,7 +896,7 @@ namespace ts.server { return undefined; } - return this.decorateNavigationBarItem(project, fileName, items); + return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); } private getNavigateToItems(searchValue: string, fileName: string, maxResultCount?: number): protocol.NavtoItem[] { diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 59dc4a3828394..e722f33bc703b 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -2,860 +2,660 @@ /* @internal */ namespace ts.NavigationBar { - export function getNavigationBarItems(sourceFile: SourceFile, compilerOptions: CompilerOptions): ts.NavigationBarItem[] { - // TODO: Handle JS files differently in 'navbar' calls for now, but ideally we should unify - // the 'navbar' and 'navto' logic for TypeScript and JavaScript. - if (isSourceFileJavaScript(sourceFile)) { - return getJsNavigationBarItems(sourceFile, compilerOptions); - } - - return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem); - - function getIndent(node: Node): number { - let indent = 1; // Global node is the only one with indent 0. - - let current = node.parent; - while (current) { - switch (current.kind) { - case SyntaxKind.ModuleDeclaration: - // If we have a module declared as A.B.C, it is more "intuitive" - // to say it only has a single layer of depth - do { - current = current.parent; - } - while (current.kind === SyntaxKind.ModuleDeclaration); - - // fall through - case SyntaxKind.ClassDeclaration: - case SyntaxKind.EnumDeclaration: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.FunctionDeclaration: - indent++; - } - - current = current.parent; - } + /** + * Represents a navigation bar item and its children. + * The returned NavigationBarItem is more complicated and doesn't include 'parent', so we use these to do work before converting. + */ + interface NavigationBarNode { + node: Node; + additionalNodes: Node[] | undefined; + parent: NavigationBarNode | undefined; // Present for all but root node + children: NavigationBarNode[] | undefined; + indent: number; // # of parents + } - return indent; - } + export function getNavigationBarItems(sourceFile_: SourceFile): NavigationBarItem[] { + sourceFile = sourceFile_; + const result = map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem); + sourceFile = void 0; + return result; + } - function getChildNodes(nodes: Node[]): Node[] { - const childNodes: Node[] = []; + // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. + let sourceFile: SourceFile; + function nodeText(node: Node): string { + return node.getText(sourceFile); + } - function visit(node: Node) { - switch (node.kind) { - case SyntaxKind.VariableStatement: - forEach((node).declarationList.declarations, visit); - break; - case SyntaxKind.ObjectBindingPattern: - case SyntaxKind.ArrayBindingPattern: - forEach((node).elements, visit); - break; + function navigationBarNodeKind(n: NavigationBarNode): SyntaxKind { + return n.node.kind; + } - case SyntaxKind.ExportDeclaration: - // Handle named exports case e.g.: - // export {a, b as B} from "mod"; - if ((node).exportClause) { - forEach((node).exportClause.elements, visit); - } - break; - - case SyntaxKind.ImportDeclaration: - let importClause = (node).importClause; - if (importClause) { - // Handle default import case e.g.: - // import d from "mod"; - if (importClause.name) { - childNodes.push(importClause); - } + function pushChild(parent: NavigationBarNode, child: NavigationBarNode): void { + if (parent.children !== void 0) { + parent.children.push(child); + } + else { + parent.children = [child]; + } + } - // Handle named bindings in imports e.g.: - // import * as NS from "mod"; - // import {a, b as B} from "mod"; - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === SyntaxKind.NamespaceImport) { - childNodes.push(importClause.namedBindings); - } - else { - forEach((importClause.namedBindings).elements, visit); - } - } - } - break; + /* + For performance, we keep navigation bar parents on a stack rather than passing them through each recursion. + `parent` is the current parent and is *not* stored in parentsStack. + `startNode` sets a new parent and `endNode` returns to the previous parent. + */ + const parentsStack: NavigationBarNode[] = []; + let parent: NavigationBarNode; + + function rootNavigationBarNode(sourceFile: SourceFile): NavigationBarNode { + Debug.assert(!parentsStack.length); + const root: NavigationBarNode = { node: sourceFile, additionalNodes: void 0, parent: void 0, children: void 0, indent: 0 }; + parent = root; + for (const statement of sourceFile.statements) { + addChildrenRecursively(statement); + } + endNode(); + Debug.assert(parent === void 0 && !parentsStack.length); + return root; + } - case SyntaxKind.BindingElement: - case SyntaxKind.VariableDeclaration: - if (isBindingPattern((node).name)) { - visit((node).name); - break; - } - // Fall through - case SyntaxKind.ClassDeclaration: - case SyntaxKind.EnumDeclaration: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.ModuleDeclaration: - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.ImportEqualsDeclaration: - case SyntaxKind.ImportSpecifier: - case SyntaxKind.ExportSpecifier: - case SyntaxKind.TypeAliasDeclaration: - childNodes.push(node); - break; - } - } + function addLeafNode(node: Node): void { + pushChild(parent, emptyNavigationBarNode(node)); + } - // for (let i = 0, n = nodes.length; i < n; i++) { - // let node = nodes[i]; + function emptyNavigationBarNode(node: Node): NavigationBarNode { + return { + node, + additionalNodes: void 0, + parent, + children: void 0, + indent: parent.indent + 1 + }; + } - // if (node.kind === SyntaxKind.ClassDeclaration || - // node.kind === SyntaxKind.EnumDeclaration || - // node.kind === SyntaxKind.InterfaceDeclaration || - // node.kind === SyntaxKind.ModuleDeclaration || - // node.kind === SyntaxKind.FunctionDeclaration) { + /** + * Add a new level of NavigationBarNodes. + * This pushes to the stack, so you must call `endNode` when you are done adding to this node. + */ + function startNode(node: Node): void { + const navNode: NavigationBarNode = emptyNavigationBarNode(node); + pushChild(parent, navNode); + + // Save the old parent + parentsStack.push(parent); + parent = navNode; + } - // childNodes.push(node); - // } - // else if (node.kind === SyntaxKind.VariableStatement) { - // childNodes.push.apply(childNodes, (node).declarations); - // } - // } - forEach(nodes, visit); - return sortNodes(childNodes); + /** Call after calling `startNode` and adding children to it. */ + function endNode(): void { + if (parent.children !== void 0) { + mergeChildren(parent.children); + sortChildren(parent.children); } + parent = parentsStack.pop(); + } - function getTopLevelNodes(node: SourceFile): Node[] { - const topLevelNodes: Node[] = []; - topLevelNodes.push(node); - - addTopLevelNodes(node.statements, topLevelNodes); + function addNodeWithRecursiveChild(node: Node, child: Node): void { + startNode(node); + addChildrenRecursively(child); + endNode(); + } - return topLevelNodes; + /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ + function addChildrenRecursively(node: Node): void { + if (node === void 0 || isToken(node)) { + return; } - function sortNodes(nodes: Node[]): Node[] { - return nodes.slice(0).sort((n1: Declaration, n2: Declaration) => { - if (n1.name && n2.name) { - return localeCompareFix(getPropertyNameForPropertyNameNode(n1.name), getPropertyNameForPropertyNameNode(n2.name)); - } - else if (n1.name) { - return 1; + switch (node.kind) { + case SyntaxKind.Constructor: + // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. + const ctr = node; + addNodeWithRecursiveChild(ctr, ctr.body); + + // Parameter properties are children of the class, not the constructor. + for (const param of ctr.parameters) { + if (isParameterPropertyDeclaration(param)) { + addLeafNode(param); + } } - else if (n2.name) { - return -1; + break; + + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.MethodSignature: + if (!hasDynamicName((node))) { + addNodeWithRecursiveChild(node, (node).body); } - else { - return n1.kind - n2.kind; - } - }); - - // node 0.10 treats "a" as greater than "B". - // For consistency, sort alphabetically, falling back to which is lower-case. - function localeCompareFix(a: string, b: string) { - const cmp = a.toLowerCase().localeCompare(b.toLowerCase()); - if (cmp !== 0) - return cmp; - // Return the *opposite* of the `<` operator, which works the same in node 0.10 and 6.0. - return a < b ? 1 : a > b ? -1 : 0; - } - } + break; - function addTopLevelNodes(nodes: Node[], topLevelNodes: Node[]): void { - nodes = sortNodes(nodes); - - for (const node of nodes) { - switch (node.kind) { - case SyntaxKind.ClassDeclaration: - topLevelNodes.push(node); - for (const member of (node).members) { - if (member.kind === SyntaxKind.MethodDeclaration || member.kind === SyntaxKind.Constructor) { - type FunctionLikeMember = MethodDeclaration | ConstructorDeclaration; - if ((member).body) { - // We do not include methods that does not have child functions in it, because of duplications. - if (hasNamedFunctionDeclarations(((member).body).statements)) { - topLevelNodes.push(member); - } - addTopLevelNodes(((member).body).statements, topLevelNodes); - } - } - } - break; - case SyntaxKind.EnumDeclaration: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.TypeAliasDeclaration: - topLevelNodes.push(node); - break; - - case SyntaxKind.ModuleDeclaration: - let moduleDeclaration = node; - topLevelNodes.push(node); - const inner = getInnermostModule(moduleDeclaration); - if (inner.body) { - addTopLevelNodes((inner.body).statements, topLevelNodes); - } - break; - - case SyntaxKind.FunctionDeclaration: - let functionDeclaration = node; - if (isTopLevelFunctionDeclaration(functionDeclaration)) { - topLevelNodes.push(node); - addTopLevelNodes((functionDeclaration.body).statements, topLevelNodes); - } - break; + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.PropertySignature: + if (!hasDynamicName((node))) { + addLeafNode(node); } - } - } - - function hasNamedFunctionDeclarations(nodes: NodeArray): boolean { - for (const s of nodes) { - if (s.kind === SyntaxKind.FunctionDeclaration && !isEmpty((s).name.text)) { - return true; + break; + + case SyntaxKind.ImportClause: + let importClause = node; + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name !== void 0) { + addLeafNode(importClause); } - } - return false; - } - - function isTopLevelFunctionDeclaration(functionDeclaration: FunctionLikeDeclaration): boolean { - if (functionDeclaration.kind === SyntaxKind.FunctionDeclaration) { - // A function declaration is 'top level' if it contains any function declarations - // within it. - if (functionDeclaration.body && functionDeclaration.body.kind === SyntaxKind.Block) { - // Proper function declarations can only have identifier names - if (hasNamedFunctionDeclarations((functionDeclaration.body).statements)) { - return true; - } - // Or if it is not parented by another function. I.e all functions at module scope are 'top level'. - if (!isFunctionBlock(functionDeclaration.parent)) { - return true; + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + const {namedBindings} = importClause; + if (namedBindings !== void 0) { + if (namedBindings.kind === SyntaxKind.NamespaceImport) { + addLeafNode(namedBindings); } - - // Or if it is nested inside class methods and constructors. else { - // We have made sure that a grand parent node exists with 'isFunctionBlock()' above. - const grandParentKind = functionDeclaration.parent.parent.kind; - if (grandParentKind === SyntaxKind.MethodDeclaration || - grandParentKind === SyntaxKind.Constructor) { - - return true; + for (const element of (namedBindings).elements) { + addLeafNode(element); } } } - } - - return false; - } - - function getItemsWorker(nodes: Node[], createItem: (n: Node) => ts.NavigationBarItem): ts.NavigationBarItem[] { - const items: ts.NavigationBarItem[] = []; - - const keyToItem: Map = {}; - - for (const child of nodes) { - const item = createItem(child); - if (item !== undefined) { - if (item.text.length > 0) { - const key = item.text + "-" + item.kind + "-" + item.indent; - - const itemWithSameName = keyToItem[key]; - if (itemWithSameName) { - // We had an item with the same name. Merge these items together. - merge(itemWithSameName, item); - } - else { - keyToItem[key] = item; - items.push(item); - } - } + break; + + case SyntaxKind.BindingElement: + case SyntaxKind.VariableDeclaration: + const decl = node; + const name = decl.name; + if (isBindingPattern(name)) { + addChildrenRecursively(name); } - } - - return items; - } - - function merge(target: ts.NavigationBarItem, source: ts.NavigationBarItem) { - // First, add any spans in the source to the target. - addRange(target.spans, source.spans); - - if (source.childItems) { - if (!target.childItems) { - target.childItems = []; + else if (decl.initializer !== void 0 && isFunctionOrClassExpression(decl.initializer)) { + // For `const x = function() {}`, just use the function node, not the const. + addChildrenRecursively(decl.initializer); } - - // Next, recursively merge or add any children in the source as appropriate. - outer: - for (const sourceChild of source.childItems) { - for (const targetChild of target.childItems) { - if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) { - // Found a match. merge them. - merge(targetChild, sourceChild); - continue outer; - } - } - - // Didn't find a match, just add this child to the list. - target.childItems.push(sourceChild); + else { + addNodeWithRecursiveChild(decl, decl.initializer); } - } - } - - function createChildItem(node: Node): ts.NavigationBarItem { - switch (node.kind) { - case SyntaxKind.Parameter: - if (isBindingPattern((node).name)) { - break; - } - if ((node.flags & NodeFlags.Modifier) === 0) { - return undefined; + break; + + case SyntaxKind.ArrowFunction: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.FunctionExpression: + addNodeWithRecursiveChild(node, (node).body); + break; + + case SyntaxKind.EnumDeclaration: + startNode(node); + for (const member of (node).members) { + if (!isComputedProperty(member)) { + addLeafNode(member); } - return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.memberVariableElement); - - case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: - return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.memberFunctionElement); - - case SyntaxKind.GetAccessor: - return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.memberGetAccessorElement); - - case SyntaxKind.SetAccessor: - return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.memberSetAccessorElement); - - case SyntaxKind.IndexSignature: - return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - - case SyntaxKind.EnumDeclaration: - return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.enumElement); - - case SyntaxKind.EnumMember: - return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.memberVariableElement); - - case SyntaxKind.ModuleDeclaration: - return createItem(node, getModuleName(node), ts.ScriptElementKind.moduleElement); - - case SyntaxKind.InterfaceDeclaration: - return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.interfaceElement); - - case SyntaxKind.TypeAliasDeclaration: - return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.typeElement); - - case SyntaxKind.CallSignature: - return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - - case SyntaxKind.ConstructSignature: - return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.PropertySignature: - return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.memberVariableElement); - - case SyntaxKind.ClassDeclaration: - return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.classElement); - - case SyntaxKind.FunctionDeclaration: - return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.functionElement); - - case SyntaxKind.VariableDeclaration: - case SyntaxKind.BindingElement: - let variableDeclarationNode: Node; - let name: Node; - - if (node.kind === SyntaxKind.BindingElement) { - name = (node).name; - variableDeclarationNode = node; - // binding elements are added only for variable declarations - // bubble up to the containing variable declaration - while (variableDeclarationNode && variableDeclarationNode.kind !== SyntaxKind.VariableDeclaration) { - variableDeclarationNode = variableDeclarationNode.parent; + } + endNode(); + break; + + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + case SyntaxKind.InterfaceDeclaration: + startNode(node); + for (const member of (node).members) { + addChildrenRecursively(member); + } + endNode(); + break; + + case SyntaxKind.ModuleDeclaration: + addNodeWithRecursiveChild(node, getInteriorModule(node).body); + break; + + case SyntaxKind.ExportSpecifier: + case SyntaxKind.ImportEqualsDeclaration: + case SyntaxKind.IndexSignature: + case SyntaxKind.CallSignature: + case SyntaxKind.ConstructSignature: + case SyntaxKind.TypeAliasDeclaration: + addLeafNode(node); + break; + + default: + if (node.jsDocComments !== void 0) { + for (const jsDocComment of node.jsDocComments) { + for (const tag of jsDocComment.tags) { + if (tag.kind === SyntaxKind.JSDocTypedefTag) { + addLeafNode(tag); + } } - Debug.assert(variableDeclarationNode !== undefined); - } - else { - Debug.assert(!isBindingPattern((node).name)); - variableDeclarationNode = node; - name = (node).name; - } - - if (isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name), ts.ScriptElementKind.constElement); } - else if (isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name), ts.ScriptElementKind.letElement); - } - else { - return createItem(node, getTextOfNode(name), ts.ScriptElementKind.variableElement); - } - - case SyntaxKind.Constructor: - return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - - case SyntaxKind.ExportSpecifier: - case SyntaxKind.ImportSpecifier: - case SyntaxKind.ImportEqualsDeclaration: - case SyntaxKind.ImportClause: - case SyntaxKind.NamespaceImport: - return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.alias); - } - - return undefined; - - function createItem(node: Node, name: string, scriptElementKind: string): NavigationBarItem { - return getNavigationBarItem(name, scriptElementKind, getNodeModifiers(node), [getNodeSpan(node)]); - } - } - - function isEmpty(text: string) { - return !text || text.trim() === ""; - } - - function getNavigationBarItem(text: string, kind: string, kindModifiers: string, spans: TextSpan[], childItems: NavigationBarItem[] = [], indent = 0): NavigationBarItem { - if (isEmpty(text)) { - return undefined; - } + } - return { - text, - kind, - kindModifiers, - spans, - childItems, - indent, - bolded: false, - grayed: false - }; + forEachChild(node, addChildrenRecursively); } + } - function createTopLevelItem(node: Node): ts.NavigationBarItem { - switch (node.kind) { - case SyntaxKind.SourceFile: - return createSourceFileItem(node); - - case SyntaxKind.ClassDeclaration: - return createClassItem(node); - - case SyntaxKind.MethodDeclaration: - case SyntaxKind.Constructor: - return createMemberFunctionLikeItem(node); - - case SyntaxKind.EnumDeclaration: - return createEnumItem(node); - - case SyntaxKind.InterfaceDeclaration: - return createInterfaceItem(node); - - case SyntaxKind.ModuleDeclaration: - return createModuleItem(node); - - case SyntaxKind.FunctionDeclaration: - return createFunctionItem(node); - - case SyntaxKind.TypeAliasDeclaration: - return createTypeAliasItem(node); + /** Merge declarations of the same kind. */ + function mergeChildren(children: NavigationBarNode[]): void { + const nameToItems: Map = {}; + filterMutate(children, child => { + const decl = child.node; + const name = decl.name && nodeText(decl.name); + if (name === void 0) { + // Anonymous items are never merged. + return true; } - return undefined; - - function createModuleItem(node: ModuleDeclaration): NavigationBarItem { - const moduleName = getModuleName(node); - - const body = getInnermostModule(node).body; - const childItems = body ? getItemsWorker(getChildNodes(body.statements), createChildItem) : []; - - return getNavigationBarItem(moduleName, - ts.ScriptElementKind.moduleElement, - getNodeModifiers(node), - [getNodeSpan(node)], - childItems, - getIndent(node)); + const itemsWithSameName = getProperty(nameToItems, name); + if (itemsWithSameName === void 0) { + nameToItems[name] = child; + return true; } - function createFunctionItem(node: FunctionDeclaration): ts.NavigationBarItem { - if (node.body && node.body.kind === SyntaxKind.Block) { - const childItems = getItemsWorker(sortNodes((node.body).statements), createChildItem); - - return getNavigationBarItem(!node.name ? "default" : node.name.text, - ts.ScriptElementKind.functionElement, - getNodeModifiers(node), - [getNodeSpan(node)], - childItems, - getIndent(node)); + if (itemsWithSameName instanceof Array) { + for (const itemWithSameName of itemsWithSameName) { + if (tryMerge(itemWithSameName, child)) { + return false; + } } - - return undefined; + itemsWithSameName.push(child); + return true; } - - function createTypeAliasItem(node: TypeAliasDeclaration): ts.NavigationBarItem { - return getNavigationBarItem(node.name.text, - ts.ScriptElementKind.typeElement, - getNodeModifiers(node), - [getNodeSpan(node)], - [], - getIndent(node)); - } - - function createMemberFunctionLikeItem(node: MethodDeclaration | ConstructorDeclaration): ts.NavigationBarItem { - if (node.body && node.body.kind === SyntaxKind.Block) { - const childItems = getItemsWorker(sortNodes((node.body).statements), createChildItem); - let scriptElementKind: string; - let memberFunctionName: string; - if (node.kind === SyntaxKind.MethodDeclaration) { - memberFunctionName = getPropertyNameForPropertyNameNode(node.name); - scriptElementKind = ts.ScriptElementKind.memberFunctionElement; - } - else { - memberFunctionName = "constructor"; - scriptElementKind = ts.ScriptElementKind.constructorImplementationElement; - } - - return getNavigationBarItem(memberFunctionName, - scriptElementKind, - getNodeModifiers(node), - [getNodeSpan(node)], - childItems, - getIndent(node)); + else { + const itemWithSameName = itemsWithSameName; + if (tryMerge(itemWithSameName, child)) { + return false; } - - return undefined; + nameToItems[name] = [itemWithSameName, child]; + return true; } - function createSourceFileItem(node: SourceFile): ts.NavigationBarItem { - const childItems = getItemsWorker(getChildNodes(node.statements), createChildItem); - - const rootName = isExternalModule(node) - ? "\"" + escapeString(getBaseFileName(removeFileExtension(normalizePath(node.fileName)))) + "\"" - : ""; - - return getNavigationBarItem(rootName, - ts.ScriptElementKind.moduleElement, - ts.ScriptElementKindModifier.none, - [getNodeSpan(node)], - childItems); + function tryMerge(a: NavigationBarNode, b: NavigationBarNode): boolean { + if (shouldReallyMerge(a.node, b.node)) { + merge(a, b); + return true; + } + return false; } + }); - function createClassItem(node: ClassDeclaration): ts.NavigationBarItem { - let childItems: NavigationBarItem[]; - - if (node.members) { - const constructor = forEach(node.members, member => { - return member.kind === SyntaxKind.Constructor && member; - }); - - // Add the constructor parameters in as children of the class (for property parameters). - // Note that *all non-binding pattern named* parameters will be added to the nodes array, but parameters that - // are not properties will be filtered out later by createChildItem. - const nodes: Node[] = removeDynamicallyNamedProperties(node); - if (constructor) { - addRange(nodes, filter(constructor.parameters, p => !isBindingPattern(p.name))); - } + /** a and b have the same name, but they may not be mergeable. */ + function shouldReallyMerge(a: Node, b: Node): boolean { + return a.kind === b.kind && (a.kind !== SyntaxKind.ModuleDeclaration || areSameModule(a, b)); - childItems = getItemsWorker(sortNodes(nodes), createChildItem); + // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. + // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! + function areSameModule(a: ModuleDeclaration, b: ModuleDeclaration): boolean { + if (a.body.kind !== b.body.kind) { + return false; } - - const nodeName = !node.name ? "default" : node.name.text; - - return getNavigationBarItem( - nodeName, - ts.ScriptElementKind.classElement, - getNodeModifiers(node), - [getNodeSpan(node)], - childItems, - getIndent(node)); + if (a.body.kind !== SyntaxKind.ModuleDeclaration) { + return true; + } + return areSameModule(a.body, b.body); } + } - function createEnumItem(node: EnumDeclaration): ts.NavigationBarItem { - const childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem); - return getNavigationBarItem( - node.name.text, - ts.ScriptElementKind.enumElement, - getNodeModifiers(node), - [getNodeSpan(node)], - childItems, - getIndent(node)); + /** Merge source into target. Source should be thrown away after this is called. */ + function merge(target: NavigationBarNode, source: NavigationBarNode): void { + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes !== void 0) { + target.additionalNodes.push(...source.additionalNodes); } - function createInterfaceItem(node: InterfaceDeclaration): ts.NavigationBarItem { - const childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem); - return getNavigationBarItem( - node.name.text, - ts.ScriptElementKind.interfaceElement, - getNodeModifiers(node), - [getNodeSpan(node)], - childItems, - getIndent(node)); + target.children = concatenate(target.children, source.children); + if (target.children !== void 0) { + mergeChildren(target.children); + sortChildren(target.children); } } + } - function getModuleName(moduleDeclaration: ModuleDeclaration): string { - // We want to maintain quotation marks. - if (isAmbientModule(moduleDeclaration)) { - return getTextOfNode(moduleDeclaration.name); - } - - // Otherwise, we need to aggregate each identifier to build up the qualified name. - const result: string[] = []; - - result.push(moduleDeclaration.name.text); + /** Recursively ensure that each NavNode's children are in sorted order. */ + function sortChildren(children: NavigationBarNode[]): void { + children.sort(compareChildren); + } - while (moduleDeclaration.body && moduleDeclaration.body.kind === SyntaxKind.ModuleDeclaration) { - moduleDeclaration = moduleDeclaration.body; + function compareChildren(child1: NavigationBarNode, child2: NavigationBarNode): number { + const name1 = tryGetName(child1.node), name2 = tryGetName(child2.node); + if (name1 !== void 0 && name2 !== void 0) { + const cmp = localeCompareFix(name1, name2); + return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + else { + return name1 !== void 0 ? 1 : name2 !== void 0 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + } - result.push(moduleDeclaration.name.text); + // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. + const collator: { compare(a: string, b: string): number } = typeof Intl === "undefined" ? void 0 : new Intl.Collator(); + // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". + const localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; + const localeCompareFix: (a: string, b: string) => number = localeCompareIsCorrect ? collator.compare : function(a, b) { + // This isn't perfect, but it passes all of our tests. + for (let i = 0; i < Math.min(a.length, b.length); i++) { + const chA = a.charAt(i), chB = b.charAt(i); + if (chA === "\"" && chB === "'") { + return 1; + } + if (chA === "'" && chB === "\"") { + return -1; + } + const cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + if (cmp !== 0) { + return cmp; } - - return result.join("."); } - - function removeComputedProperties(node: EnumDeclaration): Declaration[] { - return filter(node.members, member => member.name === undefined || member.name.kind !== SyntaxKind.ComputedPropertyName); + return a.length - b.length; + }; + + /** + * This differs from getItemName because this is just used for sorting. + * We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like. + * So `new()` can still come before an `aardvark` method. + */ + function tryGetName(node: Node): string | undefined { + if (node.kind === SyntaxKind.ModuleDeclaration) { + return getModuleName(node); } - /** - * Like removeComputedProperties, but retains the properties with well known symbol names - */ - function removeDynamicallyNamedProperties(node: ClassDeclaration | InterfaceDeclaration): Declaration[] { - return filter(node.members, member => !hasDynamicName(member)); + const decl = node; + if (decl.name !== void 0) { + return getPropertyNameForPropertyNameNode(decl.name); } + switch (node.kind) { + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + case SyntaxKind.ClassExpression: + return getFunctionOrClassName(node); + case SyntaxKind.JSDocTypedefTag: + return getJSDocTypedefTagName(node); + default: + return void 0; + } + } - function getInnermostModule(node: ModuleDeclaration): ModuleDeclaration { - while (node.body && node.body.kind === SyntaxKind.ModuleDeclaration) { - node = node.body; - } - - return node; + function getItemName(node: Node): string { + if (node.kind === SyntaxKind.ModuleDeclaration) { + return getModuleName(node); } - function getNodeSpan(node: Node) { - return node.kind === SyntaxKind.SourceFile - ? createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : createTextSpanFromBounds(node.getStart(), node.getEnd()); + const name = (node).name; + if (name !== void 0) { + const text = nodeText(name); + if (text.length > 0) { + return text; + } } - function getTextOfNode(node: Node): string { - return getTextOfNodeFromSourceText(sourceFile.text, node); + switch (node.kind) { + case SyntaxKind.SourceFile: + const sourceFile = node; + return isExternalModule(sourceFile) + ? `"${escapeString(getBaseFileName(removeFileExtension(normalizePath(sourceFile.fileName))))}"` + : ""; + case SyntaxKind.ArrowFunction: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.FunctionExpression: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + if (node.flags & NodeFlags.Default) { + return "default"; + } + return getFunctionOrClassName(node); + case SyntaxKind.Constructor: + return "constructor"; + case SyntaxKind.ConstructSignature: + return "new()"; + case SyntaxKind.CallSignature: + return "()"; + case SyntaxKind.IndexSignature: + return "[]"; + case SyntaxKind.JSDocTypedefTag: + return getJSDocTypedefTagName(node); + default: + Debug.fail(); + return ""; } } - export function getJsNavigationBarItems(sourceFile: SourceFile, compilerOptions: CompilerOptions): NavigationBarItem[] { - const anonFnText = ""; - const anonClassText = ""; - let indent = 0; - - const rootName = isExternalModule(sourceFile) ? - "\"" + escapeString(getBaseFileName(removeFileExtension(normalizePath(sourceFile.fileName)))) + "\"" - : ""; - - const sourceFileItem = getNavBarItem(rootName, ScriptElementKind.moduleElement, [getNodeSpan(sourceFile)]); - let topItem = sourceFileItem; - - // Walk the whole file, because we want to also find function expressions - which may be in variable initializer, - // call arguments, expressions, etc... - forEachChild(sourceFile, visitNode); - - function visitNode(node: Node) { - const newItem = createNavBarItem(node); - - if (newItem) { - topItem.childItems.push(newItem); - } - - if (node.jsDocComments && node.jsDocComments.length > 0) { - for (const jsDocComment of node.jsDocComments) { - visitNode(jsDocComment); + function getJSDocTypedefTagName(node: JSDocTypedefTag): string { + if (node.name !== void 0) { + return node.name.text; + } + else { + const parentNode = node.parent && node.parent.parent; + if (parentNode && parentNode.kind === SyntaxKind.VariableStatement) { + if ((parentNode).declarationList.declarations.length > 0) { + const nameIdentifier = (parentNode).declarationList.declarations[0].name; + if (nameIdentifier.kind === SyntaxKind.Identifier) { + return (nameIdentifier).text; + } } } + return ""; + } + } - // Add a level if traversing into a container - if (newItem && (isFunctionLike(node) || isClassLike(node))) { - const lastTop = topItem; - indent++; - topItem = newItem; - forEachChild(node, visitNode); - topItem = lastTop; - indent--; - - // If the last item added was an anonymous function expression, and it had no children, discard it. - if (newItem && newItem.text === anonFnText && newItem.childItems.length === 0) { - topItem.childItems.pop(); + /** Flattens the NavNode tree to a list, keeping only the top-level items. */ + function topLevelItems(root: NavigationBarNode): NavigationBarNode[] { + const topLevel: NavigationBarNode[] = []; + function recur(item: NavigationBarNode) { + if (isTopLevel(item)) { + topLevel.push(item); + if (item.children !== void 0) { + for (const child of item.children) { + recur(child); + } } } - else { - forEachChild(node, visitNode); - } } + recur(root); + return topLevel; - function createNavBarItem(node: Node): NavigationBarItem { - switch (node.kind) { - case SyntaxKind.VariableDeclaration: - // Only add to the navbar if at the top-level of the file - // Note: "const" and "let" are also SyntaxKind.VariableDeclarations - if (node.parent/*VariableDeclarationList*/.parent/*VariableStatement*/ - .parent/*SourceFile*/.kind !== SyntaxKind.SourceFile) { - return undefined; - } - // If it is initialized with a function expression, handle it when we reach the function expression node - const varDecl = node as VariableDeclaration; - if (varDecl.initializer && (varDecl.initializer.kind === SyntaxKind.FunctionExpression || - varDecl.initializer.kind === SyntaxKind.ArrowFunction || - varDecl.initializer.kind === SyntaxKind.ClassExpression)) { - return undefined; - } - // Fall through - case SyntaxKind.FunctionDeclaration: + function isTopLevel(item: NavigationBarNode): boolean { + switch (navigationBarNodeKind(item)) { case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.SourceFile: + case SyntaxKind.TypeAliasDeclaration: + case SyntaxKind.JSDocTypedefTag: + return true; + case SyntaxKind.Constructor: + case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - // "export default function().." looks just like a regular function/class declaration, except with the 'default' flag - const name = node.flags && (node.flags & NodeFlags.Default) && !(node as (Declaration)).name ? "default" : - node.kind === SyntaxKind.Constructor ? "constructor" : - declarationNameToString((node as (Declaration)).name); - return getNavBarItem(name, getScriptKindForElementKind(node.kind), [getNodeSpan(node)]); - case SyntaxKind.FunctionExpression: + return hasSomeImportantChild(item); + case SyntaxKind.ArrowFunction: - case SyntaxKind.ClassExpression: - return getDefineModuleItem(node) || getFunctionOrClassExpressionItem(node); - case SyntaxKind.MethodDeclaration: - const methodDecl = node as MethodDeclaration; - return getNavBarItem(declarationNameToString(methodDecl.name), - ScriptElementKind.memberFunctionElement, - [getNodeSpan(node)]); - case SyntaxKind.ExportAssignment: - // e.g. "export default " - return getNavBarItem("default", ScriptElementKind.variableElement, [getNodeSpan(node)]); - case SyntaxKind.ImportClause: // e.g. 'def' in: import def from 'mod' (in ImportDeclaration) - if (!(node as ImportClause).name) { - // No default import (this node is still a parent of named & namespace imports, which are handled below) - return undefined; - } - // fall through - case SyntaxKind.ImportSpecifier: // e.g. 'id' in: import {id} from 'mod' (in NamedImports, in ImportClause) - case SyntaxKind.NamespaceImport: // e.g. '* as ns' in: import * as ns from 'mod' (in ImportClause) - case SyntaxKind.ExportSpecifier: // e.g. 'a' or 'b' in: export {a, foo as b} from 'mod' - // Export specifiers are only interesting if they are reexports from another module, or renamed, else they are already globals - if (node.kind === SyntaxKind.ExportSpecifier) { - if (!(node.parent.parent as ExportDeclaration).moduleSpecifier && !(node as ExportSpecifier).propertyName) { - return undefined; - } - } - const decl = node as (ImportSpecifier | ImportClause | NamespaceImport | ExportSpecifier); - if (!decl.name) { - return undefined; - } - const declName = declarationNameToString(decl.name); - return getNavBarItem(declName, ScriptElementKind.constElement, [getNodeSpan(node)]); - case SyntaxKind.JSDocTypedefTag: - if ((node).name) { - return getNavBarItem( - (node).name.text, - ScriptElementKind.typeElement, - [getNodeSpan(node)]); - } - else { - const parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === SyntaxKind.VariableStatement) { - if ((parentNode).declarationList.declarations.length > 0) { - const nameIdentifier = (parentNode).declarationList.declarations[0].name; - if (nameIdentifier.kind === SyntaxKind.Identifier) { - return getNavBarItem( - (nameIdentifier).text, - ScriptElementKind.typeElement, - [getNodeSpan(node)]); - } - } - } - } + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.FunctionExpression: + return isTopLevelFunctionDeclaration(item); + default: - return undefined; + return false; + } + function isTopLevelFunctionDeclaration(item: NavigationBarNode): boolean { + if ((item.node).body === void 0) { + return false; + } + + switch (navigationBarNodeKind(item.parent)) { + case SyntaxKind.ModuleBlock: + case SyntaxKind.SourceFile: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.Constructor: + return true; + default: + return hasSomeImportantChild(item); + } + } + function hasSomeImportantChild(item: NavigationBarNode) { + return forEach(item.children, child => { + const childKind = navigationBarNodeKind(child); + return childKind !== SyntaxKind.VariableDeclaration && childKind !== SyntaxKind.BindingElement; + }); } } + } - function getNavBarItem(text: string, kind: string, spans: TextSpan[], kindModifiers = ScriptElementKindModifier.none): NavigationBarItem { + // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. + const emptyChildItemArray: NavigationBarItem[] = []; + + function convertToTopLevelItem(n: NavigationBarNode): NavigationBarItem { + return { + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: getNodeModifiers(n.node), + spans: getSpans(n), + childItems: map(n.children, convertToChildItem) || emptyChildItemArray, + indent: n.indent, + bolded: false, + grayed: false + }; + + function convertToChildItem(n: NavigationBarNode): NavigationBarItem { return { - text, kind, kindModifiers, spans, childItems: [], indent, bolded: false, grayed: false + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: getNodeModifiers(n.node), + spans: getSpans(n), + childItems: emptyChildItemArray, + indent: 0, + bolded: false, + grayed: false }; } - function getDefineModuleItem(node: Node): NavigationBarItem { - if (node.kind !== SyntaxKind.FunctionExpression && node.kind !== SyntaxKind.ArrowFunction) { - return undefined; - } - - // No match if this is not a call expression to an identifier named 'define' - if (node.parent.kind !== SyntaxKind.CallExpression) { - return undefined; - } - const callExpr = node.parent as CallExpression; - if (callExpr.expression.kind !== SyntaxKind.Identifier || callExpr.expression.getText() !== "define") { - return undefined; - } - - // Return a module of either the given text in the first argument, or of the source file path - let defaultName = node.getSourceFile().fileName; - if (callExpr.arguments[0].kind === SyntaxKind.StringLiteral) { - defaultName = ((callExpr.arguments[0]) as StringLiteral).text; + function getSpans(n: NavigationBarNode): TextSpan[] { + const spans = [getNodeSpan(n.node)]; + if (n.additionalNodes !== void 0) { + for (const node of n.additionalNodes) { + spans.push(getNodeSpan(node)); + } } - return getNavBarItem(defaultName, ScriptElementKind.moduleElement, [getNodeSpan(node.parent)]); + return spans; } + } - function getFunctionOrClassExpressionItem(node: Node): NavigationBarItem { - if (node.kind !== SyntaxKind.FunctionExpression && - node.kind !== SyntaxKind.ArrowFunction && - node.kind !== SyntaxKind.ClassExpression) { - return undefined; - } - - const fnExpr = node as FunctionExpression | ArrowFunction | ClassExpression; - let fnName: string; - if (fnExpr.name && getFullWidth(fnExpr.name) > 0) { - // The expression has an identifier, so use that as the name - fnName = declarationNameToString(fnExpr.name); - } - else { - // See if it is a var initializer. If so, use the var name. - if (fnExpr.parent.kind === SyntaxKind.VariableDeclaration) { - fnName = declarationNameToString((fnExpr.parent as VariableDeclaration).name); + // TODO: GH#9145: We should just use getNodeKind. No reason why navigationBar and navigateTo should have different behaviors. + function nodeKind(node: Node): string { + switch (node.kind) { + case SyntaxKind.SourceFile: + return ScriptElementKind.moduleElement; + + case SyntaxKind.EnumMember: + return ScriptElementKind.memberVariableElement; + + case SyntaxKind.VariableDeclaration: + case SyntaxKind.BindingElement: + let variableDeclarationNode: Node; + let name: Node; + + if (node.kind === SyntaxKind.BindingElement) { + name = (node).name; + variableDeclarationNode = node; + // binding elements are added only for variable declarations + // bubble up to the containing variable declaration + while (variableDeclarationNode && variableDeclarationNode.kind !== SyntaxKind.VariableDeclaration) { + variableDeclarationNode = variableDeclarationNode.parent; + } + Debug.assert(variableDeclarationNode !== void 0); } - // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (fnExpr.parent.kind === SyntaxKind.BinaryExpression && - (fnExpr.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) { - fnName = (fnExpr.parent as BinaryExpression).left.getText(); + else { + Debug.assert(!isBindingPattern((node).name)); + variableDeclarationNode = node; + name = (node).name; } - // See if it is a property assignment, and if so use the property name - else if (fnExpr.parent.kind === SyntaxKind.PropertyAssignment && - (fnExpr.parent as PropertyAssignment).name) { - fnName = (fnExpr.parent as PropertyAssignment).name.getText(); + + if (isConst(variableDeclarationNode)) { + return ts.ScriptElementKind.constElement; + } + else if (isLet(variableDeclarationNode)) { + return ts.ScriptElementKind.letElement; } else { - fnName = node.kind === SyntaxKind.ClassExpression ? anonClassText : anonFnText; + return ts.ScriptElementKind.variableElement; } - } - const scriptKind = node.kind === SyntaxKind.ClassExpression ? ScriptElementKind.classElement : ScriptElementKind.functionElement; - return getNavBarItem(fnName, scriptKind, [getNodeSpan(node)]); + + case SyntaxKind.ArrowFunction: + return ts.ScriptElementKind.functionElement; + + case SyntaxKind.JSDocTypedefTag: + return ScriptElementKind.typeElement; + + default: + return getNodeKind(node); } + } - function getNodeSpan(node: Node) { - return node.kind === SyntaxKind.SourceFile - ? createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : createTextSpanFromBounds(node.getStart(), node.getEnd()); + function getModuleName(moduleDeclaration: ModuleDeclaration): string { + // We want to maintain quotation marks. + if (isAmbientModule(moduleDeclaration)) { + return getTextOfNode(moduleDeclaration.name); } - function getScriptKindForElementKind(kind: SyntaxKind) { - switch (kind) { - case SyntaxKind.VariableDeclaration: - return ScriptElementKind.variableElement; - case SyntaxKind.FunctionDeclaration: - return ScriptElementKind.functionElement; - case SyntaxKind.ClassDeclaration: - return ScriptElementKind.classElement; - case SyntaxKind.Constructor: - return ScriptElementKind.constructorImplementationElement; - case SyntaxKind.GetAccessor: - return ScriptElementKind.memberGetAccessorElement; - case SyntaxKind.SetAccessor: - return ScriptElementKind.memberSetAccessorElement; - default: - return "unknown"; - } + // Otherwise, we need to aggregate each identifier to build up the qualified name. + const result: string[] = []; + + result.push(moduleDeclaration.name.text); + + while (moduleDeclaration.body && moduleDeclaration.body.kind === SyntaxKind.ModuleDeclaration) { + moduleDeclaration = moduleDeclaration.body; + + result.push(moduleDeclaration.name.text); + } + + return result.join("."); + } + + /** + * For 'module A.B.C', we want to get the node for 'C'. + * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. + */ + function getInteriorModule(decl: ModuleDeclaration): ModuleDeclaration { + return decl.body.kind === SyntaxKind.ModuleDeclaration ? getInteriorModule(decl.body) : decl; + } + + function isComputedProperty(member: EnumMember): boolean { + return member.name === void 0 || member.name.kind === SyntaxKind.ComputedPropertyName; + } + + function getNodeSpan(node: Node): TextSpan { + return node.kind === SyntaxKind.SourceFile + ? createTextSpanFromBounds(node.getFullStart(), node.getEnd()) + : createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); + } + + function getFunctionOrClassName(node: FunctionExpression | FunctionDeclaration | ArrowFunction | ClassLikeDeclaration): string { + if (node.name !== void 0 && getFullWidth(node.name) > 0) { + return declarationNameToString(node.name); + } + // See if it is a var initializer. If so, use the var name. + else if (node.parent.kind === SyntaxKind.VariableDeclaration) { + return declarationNameToString((node.parent as VariableDeclaration).name); + } + // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. + else if (node.parent.kind === SyntaxKind.BinaryExpression && + (node.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) { + return nodeText((node.parent as BinaryExpression).left); } + // See if it is a property assignment, and if so use the property name + else if (node.parent.kind === SyntaxKind.PropertyAssignment && (node.parent as PropertyAssignment).name) { + return nodeText((node.parent as PropertyAssignment).name); + } + // Default exports are named "default" + else if (node.flags & NodeFlags.Default) { + return "default"; + } + else { + return isClassLike(node) ? "" : ""; + } + } - return sourceFileItem.childItems; + function isFunctionOrClassExpression(node: Node): boolean { + return node.kind === SyntaxKind.FunctionExpression || node.kind === SyntaxKind.ArrowFunction || node.kind === SyntaxKind.ClassExpression; } } diff --git a/src/services/services.ts b/src/services/services.ts index 983ddfbf250f6..163be48695dfb 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -7039,7 +7039,7 @@ namespace ts { function getNavigationBarItems(fileName: string): NavigationBarItem[] { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); + return NavigationBar.getNavigationBarItems(sourceFile); } function getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[] { diff --git a/tests/cases/fourslash/navbar_contains-no-duplicates.ts b/tests/cases/fourslash/navbar_contains-no-duplicates.ts index e259a7bef901f..10e4027ff84c7 100644 --- a/tests/cases/fourslash/navbar_contains-no-duplicates.ts +++ b/tests/cases/fourslash/navbar_contains-no-duplicates.ts @@ -7,7 +7,7 @@ //// } //// } //// } -//// +//// //// declare module Windows { //// export module Foundation { //// export var B; @@ -16,13 +16,13 @@ //// } //// } //// } -//// +//// //// class ABC { //// public foo() { //// return 3; //// } //// } -//// +//// //// module ABC { //// export var x = 3; //// } @@ -95,13 +95,13 @@ verify.navigationBar([ "kindModifiers": "export,declare" }, { - "text": "Test", - "kind": "class", + "text": "B", + "kind": "var", "kindModifiers": "export,declare" }, { - "text": "B", - "kind": "var", + "text": "Test", + "kind": "class", "kindModifiers": "export,declare" }, { diff --git a/tests/cases/fourslash/navbar_exportDefault.ts b/tests/cases/fourslash/navbar_exportDefault.ts index dc99cff7d649c..e547c9129a69d 100644 --- a/tests/cases/fourslash/navbar_exportDefault.ts +++ b/tests/cases/fourslash/navbar_exportDefault.ts @@ -16,7 +16,14 @@ goTo.file("a.ts"); verify.navigationBar([ { "text": "\"a\"", - "kind": "module" + "kind": "module", + "childItems": [ + { + "text": "default", + "kind": "class", + "kindModifiers": "export" + } + ] }, { "text": "default", @@ -52,6 +59,13 @@ verify.navigationBar([ { "text": "\"c\"", "kind": "module", + "childItems": [ + { + "text": "default", + "kind": "function", + "kindModifiers": "export" + } + ] }, { "text": "default", diff --git a/tests/cases/fourslash/navigationBarAnonymousClassAndFunctionExpressions.ts b/tests/cases/fourslash/navigationBarAnonymousClassAndFunctionExpressions.ts new file mode 100644 index 0000000000000..f15959812fc06 --- /dev/null +++ b/tests/cases/fourslash/navigationBarAnonymousClassAndFunctionExpressions.ts @@ -0,0 +1,147 @@ +/// + +////global.cls = class { }; +////(function() { +//// const x = () => { +//// // Presence of inner function causes x to be a top-level function. +//// function xx() {} +//// }; +//// const y = { +//// // This is not a top-level function (contains nothing, but shows up in childItems of its parent.) +//// foo: function() {} +//// }; +//// (function nest() { +//// function moreNest() {} +//// })(); +////})(); +////(function() { // Different anonymous functions are not merged +//// // These will only show up as childItems. +//// function z() {} +//// console.log(function() {}) +////}) +////(function classes() { +//// // Classes show up in top-level regardless of whether they have names or inner declarations. +//// const cls2 = class { }; +//// console.log(class cls3 {}); +//// (class { }); +////}) + +verify.navigationBar([ + { + "text": "", + "kind": "module", + "childItems": [ + { + "text": "", + "kind": "function" + }, + { + "text": "", + "kind": "function" + }, + { + "text": "classes", + "kind": "function" + }, + { + "text": "global.cls", + "kind": "class" + } + ] + }, + { + "text": "", + "kind": "function", + "childItems": [ + { + "text": "nest", + "kind": "function" + }, + { + "text": "x", + "kind": "function" + }, + { + "text": "y", + "kind": "const" + } + ], + "indent": 1 + }, + { + "text": "nest", + "kind": "function", + "childItems": [ + { + "text": "moreNest", + "kind": "function" + } + ], + "indent": 2 + }, + { + "text": "x", + "kind": "function", + "childItems": [ + { + "text": "xx", + "kind": "function" + } + ], + "indent": 2 + }, + { + "text": "", + "kind": "function", + "childItems": [ + { + "text": "", + "kind": "function" + }, + { + "text": "z", + "kind": "function" + } + ], + "indent": 1 + }, + { + "text": "classes", + "kind": "function", + "childItems": [ + { + "text": "", + "kind": "class" + }, + { + "text": "cls2", + "kind": "class" + }, + { + "text": "cls3", + "kind": "class" + } + ], + "indent": 1 + }, + { + "text": "", + "kind": "class", + "indent": 2 + }, + { + "text": "cls2", + "kind": "class", + "indent": 2 + }, + { + "text": "cls3", + "kind": "class", + "indent": 2 + }, + { + "text": "global.cls", + "kind": "class", + "indent": 1 + } +]); diff --git a/tests/cases/fourslash/navigationBarAnonymousClassAndFunctionExpressions2.ts b/tests/cases/fourslash/navigationBarAnonymousClassAndFunctionExpressions2.ts new file mode 100644 index 0000000000000..214a14949ac5e --- /dev/null +++ b/tests/cases/fourslash/navigationBarAnonymousClassAndFunctionExpressions2.ts @@ -0,0 +1,64 @@ +/// + +////console.log(console.log(class Y {}, class X {}), console.log(class B {}, class A {})); +////console.log(class Cls { meth() {} }); + +verify.navigationBar([ + { + "text": "", + "kind": "module", + "childItems": [ + { + "text": "A", + "kind": "class" + }, + { + "text": "B", + "kind": "class" + }, + { + "text": "Cls", + "kind": "class" + }, + { + "text": "X", + "kind": "class" + }, + { + "text": "Y", + "kind": "class" + } + ] + }, + { + "text": "A", + "kind": "class", + "indent": 1 + }, + { + "text": "B", + "kind": "class", + "indent": 1 + }, + { + "text": "Cls", + "kind": "class", + "childItems": [ + { + "text": "meth", + "kind": "method" + } + ], + "indent": 1 + }, + { + "text": "X", + "kind": "class", + "indent": 1 + }, + { + "text": "Y", + "kind": "class", + "indent": 1 + } +]); diff --git a/tests/cases/fourslash/navigationBarGetterAndSetter.ts b/tests/cases/fourslash/navigationBarGetterAndSetter.ts new file mode 100644 index 0000000000000..48105e4e9af3a --- /dev/null +++ b/tests/cases/fourslash/navigationBarGetterAndSetter.ts @@ -0,0 +1,48 @@ +/// + +////class X { +//// get x() {} +//// set x(value) { +//// // Inner declaration should make the setter top-level. +//// function f() {} +//// } +////} + +verify.navigationBar([ + { + "text": "", + "kind": "module", + "childItems": [ + { + "text": "X", + "kind": "class" + } + ] + }, + { + "text": "X", + "kind": "class", + "childItems": [ + { + "text": "x", + "kind": "getter" + }, + { + "text": "x", + "kind": "setter" + } + ], + "indent": 1 + }, + { + "text": "x", + "kind": "setter", + "childItems": [ + { + "text": "f", + "kind": "function" + } + ], + "indent": 2 + } +]); diff --git a/tests/cases/fourslash/navigationBarImports.ts b/tests/cases/fourslash/navigationBarImports.ts new file mode 100644 index 0000000000000..43cb99c556a7e --- /dev/null +++ b/tests/cases/fourslash/navigationBarImports.ts @@ -0,0 +1,30 @@ +/// + +////import a, {b} from "m"; +////import c = require("m"); +////import * as d from "m"; + +verify.navigationBar([ + { + "text": "\"navigationBarImports\"", + "kind": "module", + "childItems": [ + { + "text": "a", + "kind": "alias" + }, + { + "text": "b", + "kind": "alias" + }, + { + "text": "c", + "kind": "alias" + }, + { + "text": "d", + "kind": "alias" + } + ] + } +]); diff --git a/tests/cases/fourslash/navigationBarItemsFunctions.ts b/tests/cases/fourslash/navigationBarItemsFunctions.ts index 91546462a2572..f5aa3fb681dd5 100644 --- a/tests/cases/fourslash/navigationBarItemsFunctions.ts +++ b/tests/cases/fourslash/navigationBarItemsFunctions.ts @@ -32,6 +32,12 @@ verify.navigationBar([ { "text": "baz", "kind": "function", + "childItems": [ + { + "text": "v", + "kind": "var" + } + ], "indent": 1 }, { @@ -41,6 +47,10 @@ verify.navigationBar([ { "text": "bar", "kind": "function" + }, + { + "text": "x", + "kind": "var" } ], "indent": 1 @@ -52,6 +62,10 @@ verify.navigationBar([ { "text": "biz", "kind": "function" + }, + { + "text": "y", + "kind": "var" } ], "indent": 2 diff --git a/tests/cases/fourslash/navigationBarItemsFunctionsBroken.ts b/tests/cases/fourslash/navigationBarItemsFunctionsBroken.ts index 96dcbb944ae07..2f17a5006ff5f 100644 --- a/tests/cases/fourslash/navigationBarItemsFunctionsBroken.ts +++ b/tests/cases/fourslash/navigationBarItemsFunctionsBroken.ts @@ -18,6 +18,12 @@ verify.navigationBar([ { "text": "f", "kind": "function", + "childItems": [ + { + "text": "", + "kind": "function" + } + ], "indent": 1 } ]); diff --git a/tests/cases/fourslash/navigationBarItemsFunctionsBroken2.ts b/tests/cases/fourslash/navigationBarItemsFunctionsBroken2.ts index 127bde8c9e71d..f907bdad06719 100644 --- a/tests/cases/fourslash/navigationBarItemsFunctionsBroken2.ts +++ b/tests/cases/fourslash/navigationBarItemsFunctionsBroken2.ts @@ -10,6 +10,10 @@ verify.navigationBar([ "text": "", "kind": "module", "childItems": [ + { + "text": "", + "kind": "function" + }, { "text": "f", "kind": "function" @@ -19,6 +23,12 @@ verify.navigationBar([ { "text": "f", "kind": "function", + "childItems": [ + { + "text": "", + "kind": "function" + } + ], "indent": 1 } ]); diff --git a/tests/cases/fourslash/navigationBarItemsInsideMethodsAndConstructors.ts b/tests/cases/fourslash/navigationBarItemsInsideMethodsAndConstructors.ts index 28ec25c6f1dd2..3af3b351114b1 100644 --- a/tests/cases/fourslash/navigationBarItemsInsideMethodsAndConstructors.ts +++ b/tests/cases/fourslash/navigationBarItemsInsideMethodsAndConstructors.ts @@ -76,17 +76,17 @@ verify.navigationBar([ "kind": "property" } ], - "indent": 2 + "indent": 3 }, { "text": "LocalFunctionInConstructor", "kind": "function", - "indent": 2 + "indent": 3 }, { "text": "LocalInterfaceInConstrcutor", "kind": "interface", - "indent": 2 + "indent": 3 }, { "text": "method", @@ -116,7 +116,7 @@ verify.navigationBar([ "kind": "property" } ], - "indent": 2 + "indent": 3 }, { "text": "LocalFunctionInMethod", @@ -127,11 +127,11 @@ verify.navigationBar([ "kind": "function" } ], - "indent": 2 + "indent": 3 }, { "text": "LocalInterfaceInMethod", "kind": "interface", - "indent": 2 + "indent": 3 } ]); diff --git a/tests/cases/fourslash/navigationBarItemsItems2.ts b/tests/cases/fourslash/navigationBarItemsItems2.ts index 762531d8778b5..6ab0827e8f959 100644 --- a/tests/cases/fourslash/navigationBarItemsItems2.ts +++ b/tests/cases/fourslash/navigationBarItemsItems2.ts @@ -12,6 +12,11 @@ verify.navigationBar([ "text": "\"navigationBarItemsItems2\"", "kind": "module", "childItems": [ + { + "text": "", + "kind": "class", + "kindModifiers": "export" + }, { "text": "A", "kind": "module" @@ -19,7 +24,7 @@ verify.navigationBar([ ] }, { - "text": "default", + "text": "", "kind": "class", "kindModifiers": "export", "indent": 1 diff --git a/tests/cases/fourslash/navigationBarItemsItemsContainsNoAnonymousFunctions.ts b/tests/cases/fourslash/navigationBarItemsItemsContainsNoAnonymousFunctions.ts deleted file mode 100644 index 276e19624c92a..0000000000000 --- a/tests/cases/fourslash/navigationBarItemsItemsContainsNoAnonymousFunctions.ts +++ /dev/null @@ -1,80 +0,0 @@ -/// -// @Filename: scriptLexicalStructureItemsContainsNoAnonymouseFunctions_0.ts -/////*file1*/ -////(function() { -//// // this should not be included -//// var x = 0; -//// -//// // this should not be included either -//// function foo() { -//// -//// } -////})(); -//// -// @Filename: scriptLexicalStructureItemsContainsNoAnonymouseFunctions_1.ts -/////*file2*/ -////var x = function() { -//// // this should not be included -//// var x = 0; -//// -//// // this should not be included either -//// function foo() { -////}; -//// -// @Filename: scriptLexicalStructureItemsContainsNoAnonymouseFunctions_2.ts -////// Named functions should still show up -/////*file3*/ -////function foo() { -////} -////function bar() { -////} - -goTo.marker("file1"); -verify.navigationBar([ - { - "text": "", - "kind": "module" - } -]); - -goTo.marker("file2"); -verify.navigationBar([ - { - "text": "", - "kind": "module", - "childItems": [ - { - "text": "x", - "kind": "var" - } - ] - } -]); - -goTo.marker("file3"); -verify.navigationBar([ - { - "text": "", - "kind": "module", - "childItems": [ - { - "text": "bar", - "kind": "function" - }, - { - "text": "foo", - "kind": "function" - } - ] - }, - { - "text": "bar", - "kind": "function", - "indent": 1 - }, - { - "text": "foo", - "kind": "function", - "indent": 1 - } -]); diff --git a/tests/cases/fourslash/navigationBarItemsMissingName1.ts b/tests/cases/fourslash/navigationBarItemsMissingName1.ts index af0e89683bcfe..2a445a5e1ed61 100644 --- a/tests/cases/fourslash/navigationBarItemsMissingName1.ts +++ b/tests/cases/fourslash/navigationBarItemsMissingName1.ts @@ -8,6 +8,11 @@ verify.navigationBar([ "text": "\"navigationBarItemsMissingName1\"", "kind": "module", "childItems": [ + { + "text": "", + "kind": "function", + "kindModifiers": "export" + }, { "text": "C", "kind": "class" diff --git a/tests/cases/fourslash/navigationBarItemsMissingName2.ts b/tests/cases/fourslash/navigationBarItemsMissingName2.ts index 2eda3b07855c7..a878c5be8455b 100644 --- a/tests/cases/fourslash/navigationBarItemsMissingName2.ts +++ b/tests/cases/fourslash/navigationBarItemsMissingName2.ts @@ -9,10 +9,16 @@ verify.navigationBar([ { "text": "", - "kind": "module" + "kind": "module", + "childItems": [ + { + "text": "", + "kind": "class" + } + ] }, { - "text": "default", + "text": "", "kind": "class", "childItems": [ { diff --git a/tests/cases/fourslash/navigationBarItemsModules.ts b/tests/cases/fourslash/navigationBarItemsModules.ts index 979f22084e587..ec11cd52b942c 100644 --- a/tests/cases/fourslash/navigationBarItemsModules.ts +++ b/tests/cases/fourslash/navigationBarItemsModules.ts @@ -28,107 +28,107 @@ //The declarations of A.B.C.x do not get merged, so the 4 vars are independent. //The two 'A' modules, however, do get merged, so in reality we have 7 modules. verify.navigationBar([ - { - "text": "", - "kind": "module", - "childItems": [ - { - "text": "A.B.C", - "kind": "module" - }, - { - "text": "A.B", - "kind": "module" - }, - { - "text": "A", - "kind": "module" - }, - { - "text": "\"X.Y.Z\"", + { + "text": "", "kind": "module", - "kindModifiers": "declare" - }, - { + "childItems": [ + { + "text": "'X2.Y2.Z2'", + "kind": "module", + "kindModifiers": "declare" + }, + { + "text": "\"X.Y.Z\"", + "kind": "module", + "kindModifiers": "declare" + }, + { + "text": "A", + "kind": "module" + }, + { + "text": "A.B", + "kind": "module" + }, + { + "text": "A.B.C", + "kind": "module" + } + ] + }, + { "text": "'X2.Y2.Z2'", "kind": "module", - "kindModifiers": "declare" - } - ] - }, - { - "text": "A.B.C", - "kind": "module", - "childItems": [ - { - "text": "x", - "kind": "var", - "kindModifiers": "export" - } - ], - "indent": 1 - }, - { - "text": "A.B", - "kind": "module", - "childItems": [ - { - "text": "y", - "kind": "var", - "kindModifiers": "export" - } - ], - "indent": 1 - }, - { - "text": "A", - "kind": "module", - "childItems": [ - { - "text": "z", - "kind": "var", - "kindModifiers": "export" - }, - { + "kindModifiers": "declare", + "indent": 1 + }, + { + "text": "\"X.Y.Z\"", + "kind": "module", + "kindModifiers": "declare", + "indent": 1 + }, + { + "text": "A", + "kind": "module", + "childItems": [ + { + "text": "B", + "kind": "module" + }, + { + "text": "z", + "kind": "var", + "kindModifiers": "export" + } + ], + "indent": 1 + }, + { "text": "B", - "kind": "module" - } - ], - "indent": 1 - }, - { - "text": "B", - "kind": "module", - "childItems": [ - { + "kind": "module", + "childItems": [ + { + "text": "C", + "kind": "module" + } + ], + "indent": 2 + }, + { "text": "C", - "kind": "module" - } - ], - "indent": 2 - }, - { - "text": "C", - "kind": "module", - "childItems": [ - { - "text": "x", - "kind": "var", - "kindModifiers": "declare" - } - ], - "indent": 3 - }, - { - "text": "\"X.Y.Z\"", - "kind": "module", - "kindModifiers": "declare", - "indent": 1 - }, - { - "text": "'X2.Y2.Z2'", - "kind": "module", - "kindModifiers": "declare", - "indent": 1 - } + "kind": "module", + "childItems": [ + { + "text": "x", + "kind": "var", + "kindModifiers": "declare" + } + ], + "indent": 3 + }, + { + "text": "A.B", + "kind": "module", + "childItems": [ + { + "text": "y", + "kind": "var", + "kindModifiers": "export" + } + ], + "indent": 1 + }, + { + "text": "A.B.C", + "kind": "module", + "childItems": [ + { + "text": "x", + "kind": "var", + "kindModifiers": "export" + } + ], + "indent": 1 + } ]); diff --git a/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts b/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts index 2ee4c93a2f1fb..4a29d718f2e0a 100644 --- a/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts +++ b/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts @@ -30,20 +30,12 @@ verify.navigationBar([ "kind": "module", "childItems": [ { - "text": "Bar", - "kind": "class" - }, - { - "text": "Foo", - "kind": "interface" - }, - { - "text": "\"Multiline\\r\\nMadness\"", + "text": "\"Multiline\\\nMadness\"", "kind": "module", "kindModifiers": "declare" }, { - "text": "\"Multiline\\\nMadness\"", + "text": "\"Multiline\\r\\nMadness\"", "kind": "module", "kindModifiers": "declare" }, @@ -51,9 +43,35 @@ verify.navigationBar([ "text": "\"MultilineMadness\"", "kind": "module", "kindModifiers": "declare" + }, + { + "text": "Bar", + "kind": "class" + }, + { + "text": "Foo", + "kind": "interface" } ] }, + { + "text": "\"Multiline\\\nMadness\"", + "kind": "module", + "kindModifiers": "declare", + "indent": 1 + }, + { + "text": "\"Multiline\\r\\nMadness\"", + "kind": "module", + "kindModifiers": "declare", + "indent": 1 + }, + { + "text": "\"MultilineMadness\"", + "kind": "module", + "kindModifiers": "declare", + "indent": 1 + }, { "text": "Bar", "kind": "class", @@ -83,23 +101,5 @@ verify.navigationBar([ } ], "indent": 1 - }, - { - "text": "\"Multiline\\r\\nMadness\"", - "kind": "module", - "kindModifiers": "declare", - "indent": 1 - }, - { - "text": "\"Multiline\\\nMadness\"", - "kind": "module", - "kindModifiers": "declare", - "indent": 1 - }, - { - "text": "\"MultilineMadness\"", - "kind": "module", - "kindModifiers": "declare", - "indent": 1 } ]); diff --git a/tests/cases/fourslash/navigationBarJsDoc.ts b/tests/cases/fourslash/navigationBarJsDoc.ts index 20a235bce9505..a2d33e216bfb5 100644 --- a/tests/cases/fourslash/navigationBarJsDoc.ts +++ b/tests/cases/fourslash/navigationBarJsDoc.ts @@ -7,15 +7,31 @@ verify.navigationBar([ { - "text": "NumberLike", - "kind": "type" + "text": "", + "kind": "module", + "childItems": [ + { + "text": "NumberLike", + "kind": "type" + }, + { + "text": "x", + "kind": "const" + }, + { + "text": "x", + "kind": "type" + } + ] }, { - "text": "x", - "kind": "type" + "text": "NumberLike", + "kind": "type", + "indent": 1, }, { "text": "x", - "kind": "var" + "kind": "type", + "indent": 1 } ]); diff --git a/tests/cases/fourslash/navigationBarMerging.ts b/tests/cases/fourslash/navigationBarMerging.ts new file mode 100644 index 0000000000000..192efe5db44b5 --- /dev/null +++ b/tests/cases/fourslash/navigationBarMerging.ts @@ -0,0 +1,189 @@ +/// + +// @Filename: file1.ts +////module a { +//// function foo() {} +////} +////module b { +//// function foo() {} +////} +////module a { +//// function bar() {} +////} + +verify.navigationBar([ + { + "text": "", + "kind": "module", + "childItems": [ + { + "text": "a", + "kind": "module" + }, + { + "text": "b", + "kind": "module" + } + ] + }, + { + "text": "a", + "kind": "module", + "childItems": [ + { + "text": "bar", + "kind": "function" + }, + { + "text": "foo", + "kind": "function" + } + ], + "indent": 1 + }, + { + "text": "b", + "kind": "module", + "childItems": [ + { + "text": "foo", + "kind": "function" + } + ], + "indent": 1 + } +]); + +// Does not merge unlike declarations. +// @Filename: file2.ts +////module a {} +////function a() {} + +goTo.file("file2.ts"); +verify.navigationBar([ + { + "text": "", + "kind": "module", + "childItems": [ + { + "text": "a", + "kind": "function" + }, + { + "text": "a", + "kind": "module" + } + ] + }, + { + "text": "a", + "kind": "function", + "indent": 1 + }, + { + "text": "a", + "kind": "module", + "indent": 1 + } +]); + +// Merges recursively +// @Filename: file3.ts +////module a { +//// interface A { +//// foo: number; +//// } +////} +////module a { +//// interface A { +//// bar: number; +//// } +////} + +goTo.file("file3.ts"); +verify.navigationBar([ + { + "text": "", + "kind": "module", + "childItems": [ + { + "text": "a", + "kind": "module" + } + ] + }, + { + "text": "a", + "kind": "module", + "childItems": [ + { + "text": "A", + "kind": "interface" + } + ], + "indent": 1 + }, + { + "text": "A", + "kind": "interface", + "childItems": [ + { + "text": "bar", + "kind": "property" + }, + { + "text": "foo", + "kind": "property" + } + ], + "indent": 2 + } +]); + +// Does not merge 'module A' with 'module A.B' + +// @Filename: file4.ts +////module A { export var x; } +////module A.B { export var y; } + +goTo.file("file4.ts"); +verify.navigationBar([ + { + "text": "", + "kind": "module", + "childItems": [ + { + "text": "A", + "kind": "module" + }, + { + "text": "A.B", + "kind": "module" + } + ] + }, + { + "text": "A", + "kind": "module", + "childItems": [ + { + "text": "x", + "kind": "var", + "kindModifiers": "export" + } + ], + "indent": 1 + }, + { + "text": "A.B", + "kind": "module", + "childItems": [ + { + "text": "y", + "kind": "var", + "kindModifiers": "export" + } + ], + "indent": 1 + } +]); diff --git a/tests/cases/fourslash/navigationBarVariables.ts b/tests/cases/fourslash/navigationBarVariables.ts new file mode 100644 index 0000000000000..42344c96f73df --- /dev/null +++ b/tests/cases/fourslash/navigationBarVariables.ts @@ -0,0 +1,53 @@ +/// + +////var x = 0; +////let y = 1; +////const z = 2; + +verify.navigationBar([ + { + "text": "", + "kind": "module", + "childItems": [ + { + "text": "x", + "kind": "var" + }, + { + "text": "y", + "kind": "let" + }, + { + "text": "z", + "kind": "const" + } + ] + } +]); + +// @Filename: file2.ts +////var {a} = 0; +////let {a: b} = 0; +////const [c] = 0; + +goTo.file("file2.ts"); +verify.navigationBar([ + { + "text": "", + "kind": "module", + "childItems": [ + { + "text": "a", + "kind": "var" + }, + { + "text": "b", + "kind": "let" + }, + { + "text": "c", + "kind": "const" + } + ] + } +]); diff --git a/tests/cases/fourslash/server/jsdocTypedefTagNavigateTo.ts b/tests/cases/fourslash/server/jsdocTypedefTagNavigateTo.ts index 77cd75aa44c77..1c617091f4c27 100644 --- a/tests/cases/fourslash/server/jsdocTypedefTagNavigateTo.ts +++ b/tests/cases/fourslash/server/jsdocTypedefTagNavigateTo.ts @@ -11,20 +11,36 @@ //// var numberLike; verify.navigationBar([ - { - "text": "NumberLike", - "kind": "type" - }, - { - "text": "NumberLike2", - "kind": "type" - }, - { - "text": "NumberLike2", - "kind": "var" - }, - { - "text": "numberLike", - "kind": "var" - } + { + "text": "", + "kind": "module", + "childItems": [ + { + "text": "numberLike", + "kind": "var" + }, + { + "text": "NumberLike", + "kind": "type" + }, + { + "text": "NumberLike2", + "kind": "var" + }, + { + "text": "NumberLike2", + "kind": "type" + } + ] + }, + { + "text": "NumberLike", + "kind": "type", + "indent": 1, + }, + { + "text": "NumberLike2", + "kind": "type", + "indent": 1 + } ]); \ No newline at end of file From 95cfaafdee9127b66535abc22cbe6722ee7dbd3a Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 20 Jun 2016 11:30:48 -0700 Subject: [PATCH 2/2] Use implicit boolean casts; it doesn't hurt performance --- src/compiler/parser.ts | 8 ++--- src/services/navigationBar.ts | 68 +++++++++++++++++------------------ 2 files changed, 38 insertions(+), 38 deletions(-) diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 6e0a37c3d9fbf..b2f3755ec46be 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -17,19 +17,19 @@ namespace ts { } function visitNode(cbNode: (node: Node) => T, node: Node): T { - if (node !== void 0) { + if (node) { return cbNode(node); } } function visitNodeArray(cbNodes: (nodes: Node[]) => T, nodes: Node[]) { - if (nodes !== void 0) { + if (nodes) { return cbNodes(nodes); } } function visitEachNode(cbNode: (node: Node) => T, nodes: Node[]) { - if (nodes !== void 0) { + if (nodes) { for (const node of nodes) { const result = cbNode(node); if (result) { @@ -44,7 +44,7 @@ namespace ts { // embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns // a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. export function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T { - if (node === void 0) { + if (!node) { return; } // The visitXXX functions could be written as local functions that close over the cbNode and cbNodeArray diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index e722f33bc703b..bfbaf5a6287ce 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -14,17 +14,17 @@ namespace ts.NavigationBar { indent: number; // # of parents } - export function getNavigationBarItems(sourceFile_: SourceFile): NavigationBarItem[] { - sourceFile = sourceFile_; + export function getNavigationBarItems(sourceFile: SourceFile): NavigationBarItem[] { + curSourceFile = sourceFile; const result = map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem); - sourceFile = void 0; + curSourceFile = undefined; return result; } // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. - let sourceFile: SourceFile; + let curSourceFile: SourceFile; function nodeText(node: Node): string { - return node.getText(sourceFile); + return node.getText(curSourceFile); } function navigationBarNodeKind(n: NavigationBarNode): SyntaxKind { @@ -32,7 +32,7 @@ namespace ts.NavigationBar { } function pushChild(parent: NavigationBarNode, child: NavigationBarNode): void { - if (parent.children !== void 0) { + if (parent.children) { parent.children.push(child); } else { @@ -50,13 +50,13 @@ namespace ts.NavigationBar { function rootNavigationBarNode(sourceFile: SourceFile): NavigationBarNode { Debug.assert(!parentsStack.length); - const root: NavigationBarNode = { node: sourceFile, additionalNodes: void 0, parent: void 0, children: void 0, indent: 0 }; + const root: NavigationBarNode = { node: sourceFile, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; parent = root; for (const statement of sourceFile.statements) { addChildrenRecursively(statement); } endNode(); - Debug.assert(parent === void 0 && !parentsStack.length); + Debug.assert(!parent && !parentsStack.length); return root; } @@ -67,9 +67,9 @@ namespace ts.NavigationBar { function emptyNavigationBarNode(node: Node): NavigationBarNode { return { node, - additionalNodes: void 0, + additionalNodes: undefined, parent, - children: void 0, + children: undefined, indent: parent.indent + 1 }; } @@ -89,7 +89,7 @@ namespace ts.NavigationBar { /** Call after calling `startNode` and adding children to it. */ function endNode(): void { - if (parent.children !== void 0) { + if (parent.children) { mergeChildren(parent.children); sortChildren(parent.children); } @@ -104,7 +104,7 @@ namespace ts.NavigationBar { /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ function addChildrenRecursively(node: Node): void { - if (node === void 0 || isToken(node)) { + if (!node || isToken(node)) { return; } @@ -142,7 +142,7 @@ namespace ts.NavigationBar { let importClause = node; // Handle default import case e.g.: // import d from "mod"; - if (importClause.name !== void 0) { + if (importClause.name) { addLeafNode(importClause); } @@ -150,7 +150,7 @@ namespace ts.NavigationBar { // import * as NS from "mod"; // import {a, b as B} from "mod"; const {namedBindings} = importClause; - if (namedBindings !== void 0) { + if (namedBindings) { if (namedBindings.kind === SyntaxKind.NamespaceImport) { addLeafNode(namedBindings); } @@ -169,7 +169,7 @@ namespace ts.NavigationBar { if (isBindingPattern(name)) { addChildrenRecursively(name); } - else if (decl.initializer !== void 0 && isFunctionOrClassExpression(decl.initializer)) { + else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { // For `const x = function() {}`, just use the function node, not the const. addChildrenRecursively(decl.initializer); } @@ -218,7 +218,7 @@ namespace ts.NavigationBar { break; default: - if (node.jsDocComments !== void 0) { + if (node.jsDocComments) { for (const jsDocComment of node.jsDocComments) { for (const tag of jsDocComment.tags) { if (tag.kind === SyntaxKind.JSDocTypedefTag) { @@ -238,13 +238,13 @@ namespace ts.NavigationBar { filterMutate(children, child => { const decl = child.node; const name = decl.name && nodeText(decl.name); - if (name === void 0) { + if (!name) { // Anonymous items are never merged. return true; } const itemsWithSameName = getProperty(nameToItems, name); - if (itemsWithSameName === void 0) { + if (!itemsWithSameName) { nameToItems[name] = child; return true; } @@ -297,12 +297,12 @@ namespace ts.NavigationBar { function merge(target: NavigationBarNode, source: NavigationBarNode): void { target.additionalNodes = target.additionalNodes || []; target.additionalNodes.push(source.node); - if (source.additionalNodes !== void 0) { + if (source.additionalNodes) { target.additionalNodes.push(...source.additionalNodes); } target.children = concatenate(target.children, source.children); - if (target.children !== void 0) { + if (target.children) { mergeChildren(target.children); sortChildren(target.children); } @@ -316,17 +316,17 @@ namespace ts.NavigationBar { function compareChildren(child1: NavigationBarNode, child2: NavigationBarNode): number { const name1 = tryGetName(child1.node), name2 = tryGetName(child2.node); - if (name1 !== void 0 && name2 !== void 0) { + if (name1 && name2) { const cmp = localeCompareFix(name1, name2); return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); } else { - return name1 !== void 0 ? 1 : name2 !== void 0 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); } } // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. - const collator: { compare(a: string, b: string): number } = typeof Intl === "undefined" ? void 0 : new Intl.Collator(); + const collator: { compare(a: string, b: string): number } = typeof Intl === "undefined" ? undefined : new Intl.Collator(); // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". const localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; const localeCompareFix: (a: string, b: string) => number = localeCompareIsCorrect ? collator.compare : function(a, b) { @@ -358,7 +358,7 @@ namespace ts.NavigationBar { } const decl = node; - if (decl.name !== void 0) { + if (decl.name) { return getPropertyNameForPropertyNameNode(decl.name); } switch (node.kind) { @@ -369,7 +369,7 @@ namespace ts.NavigationBar { case SyntaxKind.JSDocTypedefTag: return getJSDocTypedefTagName(node); default: - return void 0; + return undefined; } } @@ -379,7 +379,7 @@ namespace ts.NavigationBar { } const name = (node).name; - if (name !== void 0) { + if (name) { const text = nodeText(name); if (text.length > 0) { return text; @@ -418,7 +418,7 @@ namespace ts.NavigationBar { } function getJSDocTypedefTagName(node: JSDocTypedefTag): string { - if (node.name !== void 0) { + if (node.name) { return node.name.text; } else { @@ -441,7 +441,7 @@ namespace ts.NavigationBar { function recur(item: NavigationBarNode) { if (isTopLevel(item)) { topLevel.push(item); - if (item.children !== void 0) { + if (item.children) { for (const child of item.children) { recur(child); } @@ -478,7 +478,7 @@ namespace ts.NavigationBar { return false; } function isTopLevelFunctionDeclaration(item: NavigationBarNode): boolean { - if ((item.node).body === void 0) { + if (!(item.node).body) { return false; } @@ -531,7 +531,7 @@ namespace ts.NavigationBar { function getSpans(n: NavigationBarNode): TextSpan[] { const spans = [getNodeSpan(n.node)]; - if (n.additionalNodes !== void 0) { + if (n.additionalNodes) { for (const node of n.additionalNodes) { spans.push(getNodeSpan(node)); } @@ -562,7 +562,7 @@ namespace ts.NavigationBar { while (variableDeclarationNode && variableDeclarationNode.kind !== SyntaxKind.VariableDeclaration) { variableDeclarationNode = variableDeclarationNode.parent; } - Debug.assert(variableDeclarationNode !== void 0); + Debug.assert(!!variableDeclarationNode); } else { Debug.assert(!isBindingPattern((node).name)); @@ -620,17 +620,17 @@ namespace ts.NavigationBar { } function isComputedProperty(member: EnumMember): boolean { - return member.name === void 0 || member.name.kind === SyntaxKind.ComputedPropertyName; + return !member.name || member.name.kind === SyntaxKind.ComputedPropertyName; } function getNodeSpan(node: Node): TextSpan { return node.kind === SyntaxKind.SourceFile ? createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); + : createTextSpanFromBounds(node.getStart(curSourceFile), node.getEnd()); } function getFunctionOrClassName(node: FunctionExpression | FunctionDeclaration | ArrowFunction | ClassLikeDeclaration): string { - if (node.name !== void 0 && getFullWidth(node.name) > 0) { + if (node.name && getFullWidth(node.name) > 0) { return declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name.