diff --git a/src/clean-ast.js b/src/clean-ast.js index 4ecd483bd..f7659dcbd 100644 --- a/src/clean-ast.js +++ b/src/clean-ast.js @@ -27,7 +27,7 @@ function massageAST(ast) { } const newObj = {}; - for (var key in ast) { + for (const key in ast) { newObj[key] = massageAST(ast[key]); } diff --git a/src/comments.js b/src/comments.js index 7b1673a31..1a32ef420 100644 --- a/src/comments.js +++ b/src/comments.js @@ -1,22 +1,22 @@ "use strict"; -var assert = require("assert"); -var types = require("./ast-types") -var n = types.namedTypes; -var isArray = types.builtInTypes.array; -var isObject = types.builtInTypes.object; -var docBuilders = require("./doc-builders"); -var concat = docBuilders.concat; -var hardline = docBuilders.hardline; -var breakParent = docBuilders.breakParent; -var indent = docBuilders.indent; -var lineSuffix = docBuilders.lineSuffix; -var join = docBuilders.join; -var util = require("./util"); -var childNodesCacheKey = Symbol("child-nodes"); -var locStart = util.locStart; -var locEnd = util.locEnd; -var getNextNonSpaceNonCommentCharacter = +const assert = require("assert"); +const types = require("./ast-types"); +const n = types.namedTypes; +const isArray = types.builtInTypes.array; +const isObject = types.builtInTypes.object; +const docBuilders = require("./doc-builders"); +const concat = docBuilders.concat; +const hardline = docBuilders.hardline; +const breakParent = docBuilders.breakParent; +const indent = docBuilders.indent; +const lineSuffix = docBuilders.lineSuffix; +const join = docBuilders.join; +const util = require("./util"); +const childNodesCacheKey = Symbol("child-nodes"); +const locStart = util.locStart; +const locEnd = util.locEnd; +const getNextNonSpaceNonCommentCharacter = util.getNextNonSpaceNonCommentCharacter; // TODO Move a non-caching implementation of this function into ast-types, @@ -31,7 +31,8 @@ function getSortedChildNodes(node, text, resultArray) { // This reverse insertion sort almost always takes constant // time because we almost always (maybe always?) append the // nodes in order anyway. - for (var i = resultArray.length - 1; i >= 0; --i) { + let i; + for (i = resultArray.length - 1; i >= 0; --i) { if ( locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node) @@ -46,7 +47,7 @@ function getSortedChildNodes(node, text, resultArray) { return node[childNodesCacheKey]; } - var names; + let names; if (isArray.check(node)) { names = Object.keys(node); } else if (isObject.check(node)) { @@ -62,7 +63,7 @@ function getSortedChildNodes(node, text, resultArray) { }); } - for (var i = 0, nameCount = names.length; i < nameCount; ++i) { + for (let i = 0, nameCount = names.length; i < nameCount; ++i) { getSortedChildNodes(node[names[i]], text, resultArray); } @@ -73,13 +74,13 @@ function getSortedChildNodes(node, text, resultArray) { // .precedingNode, .enclosingNode, and/or .followingNode properties, at // least one of which is guaranteed to be defined. function decorateComment(node, comment, text) { - var childNodes = getSortedChildNodes(node, text); - var precedingNode, followingNode; + const childNodes = getSortedChildNodes(node, text); + let precedingNode, followingNode; // Time to dust off the old binary search robes and wizard hat. - var left = 0, right = childNodes.length; + let left = 0, right = childNodes.length; while (left < right) { - var middle = (left + right) >> 1; - var child = childNodes[middle]; + const middle = (left + right) >> 1; + const child = childNodes[middle]; if ( locStart(child) - locStart(comment) <= 0 && @@ -129,7 +130,7 @@ function attach(comments, ast, text) { return; } - var tiesToBreak = []; + const tiesToBreak = []; comments.forEach((comment, i) => { decorateComment(ast, comment, text); @@ -262,7 +263,7 @@ function attach(comments, ast, text) { // simply attach the right node; const tieCount = tiesToBreak.length; if (tieCount > 0) { - var lastTie = tiesToBreak[tieCount - 1]; + const lastTie = tiesToBreak[tieCount - 1]; if (lastTie.followingNode !== comment.followingNode) { breakTies(tiesToBreak, text); } @@ -294,29 +295,30 @@ function attach(comments, ast, text) { } function breakTies(tiesToBreak, text) { - var tieCount = tiesToBreak.length; + const tieCount = tiesToBreak.length; if (tieCount === 0) { return; } - var precedingNode = tiesToBreak[0].precedingNode; - var followingNode = tiesToBreak[0].followingNode; - var gapEndPos = locStart(followingNode); + const precedingNode = tiesToBreak[0].precedingNode; + const followingNode = tiesToBreak[0].followingNode; + let gapEndPos = locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps // between the tied comments. In order to qualify as leading, a // comment must be separated from followingNode by an unbroken series of // whitespace-only gaps (or other comments). + let indexOfFirstLeadingComment; for ( - var indexOfFirstLeadingComment = tieCount; + indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment ) { - var comment = tiesToBreak[indexOfFirstLeadingComment - 1]; + const comment = tiesToBreak[indexOfFirstLeadingComment - 1]; assert.strictEqual(comment.precedingNode, precedingNode); assert.strictEqual(comment.followingNode, followingNode); - var gap = text.slice(locEnd(comment), gapEndPos); + const gap = text.slice(locEnd(comment), gapEndPos); if (/\S/.test(gap)) { // The gap string contained something other than whitespace. break; @@ -337,7 +339,7 @@ function breakTies(tiesToBreak, text) { } function addCommentHelper(node, comment) { - var comments = node.comments || (node.comments = []); + const comments = node.comments || (node.comments = []); comments.push(comment); comment.printed = false; } @@ -898,22 +900,22 @@ function printDanglingComments(path, options, sameIndent) { } function printComments(path, print, options, needsSemi) { - var value = path.getValue(); - var parent = path.getParentNode(); - var printed = print(path); - var comments = n.Node.check(value) && types.getFieldValue(value, "comments"); + const value = path.getValue(); + const parent = path.getParentNode(); + const printed = print(path); + const comments = n.Node.check(value) && types.getFieldValue(value, "comments"); if (!comments || comments.length === 0) { return printed; } - var leadingParts = []; - var trailingParts = [needsSemi ? ";" : "", printed]; + const leadingParts = []; + const trailingParts = [needsSemi ? ";" : "", printed]; path.each(function(commentPath) { - var comment = commentPath.getValue(); - var leading = types.getFieldValue(comment, "leading"); - var trailing = types.getFieldValue(comment, "trailing"); + const comment = commentPath.getValue(); + const leading = types.getFieldValue(comment, "leading"); + const trailing = types.getFieldValue(comment, "trailing"); if (leading) { leadingParts.push(printLeadingComment(commentPath, print, options)); diff --git a/src/doc-builders.js b/src/doc-builders.js index 837e0d6d3..471e557a0 100644 --- a/src/doc-builders.js +++ b/src/doc-builders.js @@ -87,9 +87,9 @@ const literalline = concat([ ]); function join(sep, arr) { - var res = []; + const res = []; - for (var i = 0; i < arr.length; i++) { + for (let i = 0; i < arr.length; i++) { if (i !== 0) { res.push(sep); } diff --git a/src/doc-debug.js b/src/doc-debug.js index e0732d2a5..21d8a38ad 100644 --- a/src/doc-debug.js +++ b/src/doc-debug.js @@ -2,9 +2,9 @@ function flattenDoc(doc) { if (doc.type === "concat") { - var res = []; + const res = []; - for (var i = 0; i < doc.parts.length; ++i) { + for (let i = 0; i < doc.parts.length; ++i) { const doc2 = doc.parts[i]; if (typeof doc2 !== "string" && doc2.type === "concat") { [].push.apply(res, flattenDoc(doc2).parts); diff --git a/src/doc-printer.js b/src/doc-printer.js index d248d5fa2..f667eecd1 100644 --- a/src/doc-printer.js +++ b/src/doc-printer.js @@ -73,7 +73,7 @@ function fits(next, restCommands, width, mustBeFlat) { } else { switch (doc.type) { case "concat": - for (var i = doc.parts.length - 1; i >= 0; i--) { + for (let i = doc.parts.length - 1; i >= 0; i--) { cmds.push([ind, mode, doc.parts[i]]); } @@ -94,7 +94,7 @@ function fits(next, restCommands, width, mustBeFlat) { break; case "fill": - for (var i = doc.parts.length - 1; i >= 0; i--) { + for (let i = doc.parts.length - 1; i >= 0; i--) { cmds.push([ind, mode, doc.parts[i]]); } @@ -159,7 +159,7 @@ function printDocToString(doc, options) { } else { switch (doc.type) { case "concat": - for (var i = doc.parts.length - 1; i >= 0; i--) { + for (let i = doc.parts.length - 1; i >= 0; i--) { cmds.push([ind, mode, doc.parts[i]]); } @@ -211,7 +211,7 @@ function printDocToString(doc, options) { break; } else { - for (var i = 1; i < doc.expandedStates.length + 1; i++) { + for (let i = 1; i < doc.expandedStates.length + 1; i++) { if (i >= doc.expandedStates.length) { cmds.push([ind, MODE_BREAK, mostExpanded]); diff --git a/src/doc-utils.js b/src/doc-utils.js index 656db6fab..c310b52fa 100644 --- a/src/doc-utils.js +++ b/src/doc-utils.js @@ -2,7 +2,7 @@ function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) { function traverseDocRec(doc) { - var shouldRecurse = true; + let shouldRecurse = true; if (onEnter) { if (onEnter(doc) === false) { shouldRecurse = false; @@ -11,7 +11,7 @@ function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) { if (shouldRecurse) { if (doc.type === "concat" || doc.type === "fill") { - for (var i = 0; i < doc.parts.length; i++) { + for (let i = 0; i < doc.parts.length; i++) { traverseDocRec(doc.parts[i]); } } else if (doc.type === "if-break") { @@ -60,10 +60,10 @@ function mapDoc(doc, func) { } function findInDoc(doc, fn, defaultValue) { - var result = defaultValue; - var hasStopped = false; + let result = defaultValue; + let hasStopped = false; traverseDoc(doc, function(doc) { - var maybeResult = fn(doc); + const maybeResult = fn(doc); if (maybeResult !== undefined) { hasStopped = true; result = maybeResult; @@ -125,7 +125,7 @@ function breakParentGroup(groupStack) { } function propagateBreaks(doc) { - var alreadyVisited = new Map(); + const alreadyVisited = new Map(); const groupStack = []; traverseDoc( doc, diff --git a/src/fast-path.js b/src/fast-path.js index 66ecf7a96..ddf28ccb1 100644 --- a/src/fast-path.js +++ b/src/fast-path.js @@ -1,19 +1,19 @@ "use strict"; -var assert = require("assert"); -var types = require("./ast-types") -var util = require("./util"); -var n = types.namedTypes; -var isArray = types.builtInTypes.array; -var isNumber = types.builtInTypes.number; -var startsWithNoLookaheadToken = util.startsWithNoLookaheadToken; +const assert = require("assert"); +const types = require("./ast-types"); +const util = require("./util"); +const n = types.namedTypes; +const isArray = types.builtInTypes.array; +const isNumber = types.builtInTypes.number; +const startsWithNoLookaheadToken = util.startsWithNoLookaheadToken; function FastPath(value) { assert.ok(this instanceof FastPath); this.stack = [value]; } -var FPp = FastPath.prototype; +const FPp = FastPath.prototype; // Static convenience function for coercing a value to a FastPath. FastPath.from = function(obj) { @@ -25,9 +25,9 @@ FastPath.from = function(obj) { if (obj instanceof types.NodePath) { // For backwards compatibility, unroll NodePath instances into // lightweight FastPath [..., name, value] stacks. - var copy = Object.create(FastPath.prototype); - var stack = [obj.value]; - for (var pp; (pp = obj.parentPath); obj = pp) + const copy = Object.create(FastPath.prototype); + const stack = [obj.value]; + for (let pp; (pp = obj.parentPath); obj = pp) stack.push(obj.name, pp.value); copy.stack = stack.reverse(); return copy; @@ -38,7 +38,7 @@ FastPath.from = function(obj) { }; FPp.copy = function copy() { - var copy = Object.create(FastPath.prototype); + const copy = Object.create(FastPath.prototype); copy.stack = this.stack.slice(0); return copy; }; @@ -46,8 +46,8 @@ FPp.copy = function copy() { // The name of the current property is always the penultimate element of // this.stack, and always a String. FPp.getName = function getName() { - var s = this.stack; - var len = s.length; + const s = this.stack; + const len = s.length; if (len > 1) { return s[len - 2]; } @@ -59,15 +59,15 @@ FPp.getName = function getName() { // The value of the current property is always the final element of // this.stack. FPp.getValue = function getValue() { - var s = this.stack; + const s = this.stack; return s[s.length - 1]; }; function getNodeHelper(path, count) { - var s = path.stack; + const s = path.stack; - for (var i = s.length - 1; i >= 0; i -= 2) { - var value = s[i]; + for (let i = s.length - 1; i >= 0; i -= 2) { + const value = s[i]; if ((n.Node.check(value)) && --count < 0) { return value; @@ -86,9 +86,9 @@ FPp.getParentNode = function getParentNode(count) { }; FPp.isLast = function isLast() { - var s = this.stack; + const s = this.stack; if (this.getParentNode()) { - var idx = s[s.length - 2]; + const idx = s[s.length - 2]; // The name of this node should be an index assert.ok(typeof idx === "number"); @@ -107,16 +107,16 @@ FPp.isLast = function isLast() { // be restored to its original state after the callback is finished, so it // is probably a mistake to retain a reference to the path. FPp.call = function call(callback /*, name1, name2, ... */) { - var s = this.stack; - var origLen = s.length; - var value = s[origLen - 1]; - var argc = arguments.length; - for (var i = 1; i < argc; ++i) { - var name = arguments[i]; + const s = this.stack; + const origLen = s.length; + let value = s[origLen - 1]; + const argc = arguments.length; + for (let i = 1; i < argc; ++i) { + const name = arguments[i]; value = value[name]; s.push(name, value); } - var result = callback(this); + const result = callback(this); s.length = origLen; return result; }; @@ -126,18 +126,18 @@ FPp.call = function call(callback /*, name1, name2, ... */) { // callback will be called with a reference to this path object for each // element of the array. FPp.each = function each(callback /*, name1, name2, ... */) { - var s = this.stack; - var origLen = s.length; - var value = s[origLen - 1]; - var argc = arguments.length; + const s = this.stack; + const origLen = s.length; + let value = s[origLen - 1]; + const argc = arguments.length; - for (var i = 1; i < argc; ++i) { - var name = arguments[i]; + for (let i = 1; i < argc; ++i) { + const name = arguments[i]; value = value[name]; s.push(name, value); } - for (var i = 0; i < value.length; ++i) { + for (let i = 0; i < value.length; ++i) { if (i in value) { s.push(i, value[i]); // If the callback needs to know the value of i, call @@ -154,20 +154,20 @@ FPp.each = function each(callback /*, name1, name2, ... */) { // callback function invocations are stored in an array and returned at // the end of the iteration. FPp.map = function map(callback /*, name1, name2, ... */) { - var s = this.stack; - var origLen = s.length; - var value = s[origLen - 1]; - var argc = arguments.length; + const s = this.stack; + const origLen = s.length; + let value = s[origLen - 1]; + const argc = arguments.length; - for (var i = 1; i < argc; ++i) { - var name = arguments[i]; + for (let i = 1; i < argc; ++i) { + const name = arguments[i]; value = value[name]; s.push(name, value); } - var result = new Array(value.length); + const result = new Array(value.length); - for (var i = 0; i < value.length; ++i) { + for (let i = 0; i < value.length; ++i) { if (i in value) { s.push(i, value[i]); result[i] = callback(this, i); @@ -183,13 +183,13 @@ FPp.map = function map(callback /*, name1, name2, ... */) { // Inspired by require("ast-types").NodePath.prototype.needsParens, but // more efficient because we're iterating backwards through a stack. FPp.needsParens = function() { - var parent = this.getParentNode(); + const parent = this.getParentNode(); if (!parent) { return false; } - var name = this.getName(); - var node = this.getNode(); + const name = this.getName(); + const node = this.getNode(); // If the value of this path is some child of a Node and not a Node // itself, then it doesn't need parentheses. Only Node objects (in @@ -334,10 +334,10 @@ FPp.needsParens = function() { case "BinaryExpression": case "LogicalExpression": - var po = parent.operator; - var pp = util.getPrecedence(po); - var no = node.operator; - var np = util.getPrecedence(no); + const po = parent.operator; + const pp = util.getPrecedence(po); + const no = node.operator; + const np = util.getPrecedence(no); if (po === "||" && no === "&&") { return true; diff --git a/src/options.js b/src/options.js index 9abd7a46b..9800cc3a8 100644 --- a/src/options.js +++ b/src/options.js @@ -1,9 +1,9 @@ "use strict"; -var validate = require("jest-validate").validate; -var deprecatedConfig = require("./deprecated"); +const validate = require("jest-validate").validate; +const deprecatedConfig = require("./deprecated"); -var defaults = { +const defaults = { useTabs: false, tabWidth: 2, printWidth: 80, @@ -15,7 +15,7 @@ var defaults = { semi: true }; -var exampleConfig = Object.assign({}, defaults, { +const exampleConfig = Object.assign({}, defaults, { filename: "testFilename", printWidth: 80, originalText: "text" diff --git a/src/printer.js b/src/printer.js index 1be95b9be..b97b498ba 100644 --- a/src/printer.js +++ b/src/printer.js @@ -1,35 +1,35 @@ "use strict"; -var assert = require("assert"); -var comments = require("./comments"); -var FastPath = require("./fast-path"); -var util = require("./util"); -var isIdentifierName = require("esutils").keyword.isIdentifierNameES6; +const assert = require("assert"); +const comments = require("./comments"); +const FastPath = require("./fast-path"); +const util = require("./util"); +const isIdentifierName = require("esutils").keyword.isIdentifierNameES6; -var docBuilders = require("./doc-builders"); -var concat = docBuilders.concat; -var join = docBuilders.join; -var line = docBuilders.line; -var hardline = docBuilders.hardline; -var softline = docBuilders.softline; -var literalline = docBuilders.literalline; -var group = docBuilders.group; -var indent = docBuilders.indent; -var align = docBuilders.align; -var conditionalGroup = docBuilders.conditionalGroup; -var fill = docBuilders.fill; -var ifBreak = docBuilders.ifBreak; -var breakParent = docBuilders.breakParent; -var lineSuffixBoundary = docBuilders.lineSuffixBoundary; +const docBuilders = require("./doc-builders"); +const concat = docBuilders.concat; +const join = docBuilders.join; +const line = docBuilders.line; +const hardline = docBuilders.hardline; +const softline = docBuilders.softline; +const literalline = docBuilders.literalline; +const group = docBuilders.group; +const indent = docBuilders.indent; +const align = docBuilders.align; +const conditionalGroup = docBuilders.conditionalGroup; +const fill = docBuilders.fill; +const ifBreak = docBuilders.ifBreak; +const breakParent = docBuilders.breakParent; +const lineSuffixBoundary = docBuilders.lineSuffixBoundary; -var docUtils = require("./doc-utils"); -var willBreak = docUtils.willBreak; -var isLineNext = docUtils.isLineNext; -var isEmpty = docUtils.isEmpty; +const docUtils = require("./doc-utils"); +const willBreak = docUtils.willBreak; +const isLineNext = docUtils.isLineNext; +const isEmpty = docUtils.isEmpty; -var types = require("./ast-types"); -var namedTypes = types.namedTypes; -var isString = types.builtInTypes.string; +const types = require("./ast-types"); +const namedTypes = types.namedTypes; +const isString = types.builtInTypes.string; function shouldPrintComma(options, level) { level = level || "es5"; @@ -52,7 +52,7 @@ function shouldPrintComma(options, level) { function genericPrint(path, options, printPath, args) { assert.ok(path instanceof FastPath); - var node = path.getValue(); + const node = path.getValue(); // Escape hatch if ( @@ -64,9 +64,9 @@ function genericPrint(path, options, printPath, args) { return options.originalText.slice(util.locStart(node), util.locEnd(node)); } - var parts = []; - var needsParens = false; - var linesWithoutParens = genericPrintNoParens(path, options, printPath, args); + const parts = []; + let needsParens = false; + const linesWithoutParens = genericPrintNoParens(path, options, printPath, args); if (!node || isEmpty(linesWithoutParens)) { return linesWithoutParens; @@ -129,7 +129,7 @@ function genericPrint(path, options, printPath, args) { } function genericPrintNoParens(path, options, print, args) { - var n = path.getValue(); + const n = path.getValue(); const semi = options.semi ? ";" : ""; if (!n) { @@ -144,7 +144,7 @@ function genericPrintNoParens(path, options, print, args) { // This assert isn't very useful though. // namedTypes.Printable.assert(n); - var parts = []; + let parts = []; switch (n.type) { case "File": return path.call(print, "program"); @@ -326,11 +326,11 @@ function genericPrintNoParens(path, options, print, args) { return concat(parts); case "Path": return join(".", n.body); - case "Identifier": - var parentNode = path.getParentNode() - var isFunctionDeclarationIdentifier = + case "Identifier": { + const parentNode = path.getParentNode() + const isFunctionDeclarationIdentifier = parentNode.type === 'DeclareFunction' && - parentNode.id === n + parentNode.id === n; return concat([ n.name, @@ -338,6 +338,7 @@ function genericPrintNoParens(path, options, print, args) { (n.typeAnnotation && !isFunctionDeclarationIdentifier) ? ": " : "", path.call(print, "typeAnnotation") ]); + } case "SpreadElement": case "SpreadElementPattern": // Babel 6 for ObjectPattern @@ -571,11 +572,11 @@ function genericPrintNoParens(path, options, print, args) { parts.push(n.importKind + " "); } - var standalones = []; - var grouped = []; + const standalones = []; + const grouped = []; if (n.specifiers && n.specifiers.length > 0) { path.each(function(specifierPath) { - var value = specifierPath.getValue(); + const value = specifierPath.getValue(); if ( namedTypes.ImportDefaultSpecifier.check(value) || namedTypes.ImportNamespaceSpecifier.check(value) @@ -637,14 +638,14 @@ function genericPrintNoParens(path, options, print, args) { return "import"; } case "BlockStatement": { - var naked = path.call(function(bodyPath) { + const naked = path.call(function(bodyPath) { return printStatementSequence(bodyPath, options, print); }, "body"); const hasContent = n.body.find(node => node.type !== "EmptyStatement"); const hasDirectives = n.directives && n.directives.length > 0; - var parent = path.getParentNode(); + const parent = path.getParentNode(); const parentParent = path.getParentNode(1); if ( !hasContent && @@ -786,24 +787,24 @@ function genericPrintNoParens(path, options, print, args) { case "TSInterfaceBody": case "ObjectTypeAnnotation": case "TSTypeLiteral": { - var isTypeAnnotation = n.type === "ObjectTypeAnnotation"; - var isTypeScriptTypeAnnotation = n.type === "TSTypeLiteral"; - var isTypeScriptInterfaceBody = n.type === "TSInterfaceBody"; - var isTypeScriptType = isTypeScriptTypeAnnotation || isTypeScriptInterfaceBody; + const isTypeAnnotation = n.type === "ObjectTypeAnnotation"; + const isTypeScriptTypeAnnotation = n.type === "TSTypeLiteral"; + const isTypeScriptInterfaceBody = n.type === "TSInterfaceBody"; + const isTypeScriptType = isTypeScriptTypeAnnotation || isTypeScriptInterfaceBody; // Leave this here because we *might* want to make this // configurable later -- flow accepts ";" for type separators, // typescript accepts ";" and newlines - var separator = isTypeAnnotation ? "," : ","; + let separator = isTypeAnnotation ? "," : ","; if (isTypeScriptInterfaceBody) { separator = semi; } - var fields = []; - var prefix = []; - var leftBrace = n.exact ? "{|" : "{"; - var rightBrace = n.exact ? "|}" : "}"; - var parent = path.getParentNode(0); - var parentIsUnionTypeAnnotation = parent.type === "UnionTypeAnnotation"; - var propertiesField; + const fields = []; + const prefix = []; + const leftBrace = n.exact ? "{|" : "{"; + const rightBrace = n.exact ? "|}" : "}"; + const parent = path.getParentNode(0); + const parentIsUnionTypeAnnotation = parent.type === "UnionTypeAnnotation"; + let propertiesField; if (n.type === 'TSTypeLiteral') { propertiesField = "members"; @@ -1120,8 +1121,8 @@ function genericPrintNoParens(path, options, print, args) { } return concat(parts); - case "VariableDeclaration": - var printed = path.map(function(childPath) { + case "VariableDeclaration": { + const printed = path.map(function(childPath) { return print(childPath); }, "declarations"); @@ -1135,9 +1136,9 @@ function genericPrintNoParens(path, options, print, args) { // We generally want to terminate all variable declarations with a // semicolon, except when they in the () part of for loops. - var parentNode = path.getParentNode(); + const parentNode = path.getParentNode(); - var isParentForLoop = + const isParentForLoop = namedTypes.ForStatement.check(parentNode) || namedTypes.ForInStatement.check(parentNode) || (namedTypes.ForOfStatement && @@ -1150,6 +1151,7 @@ function genericPrintNoParens(path, options, print, args) { } return group(concat(parts)); + } case "VariableDeclarator": return printAssignment( n.id, @@ -1288,9 +1290,9 @@ function genericPrintNoParens(path, options, print, args) { ])); case "DoWhileStatement": - var clause = adjustClause(n.body, path.call(print, "body")); - var doBody = group(concat(["do", clause])); - var parts = [doBody]; + const clause = adjustClause(n.body, path.call(print, "body")); + const doBody = group(concat(["do", clause])); + parts = [doBody]; if (n.body.type === "BlockStatement") { parts.push(" "); @@ -1587,11 +1589,11 @@ function genericPrintNoParens(path, options, print, args) { return concat(parts); case "ClassProperty": - case "TSAbstractClassProperty": + case "TSAbstractClassProperty": { if (n.static) { parts.push("static "); } - var variance = getFlowVariance(n, options); + const variance = getFlowVariance(n, options); if (variance) { parts.push(variance); } @@ -1616,6 +1618,7 @@ function genericPrintNoParens(path, options, print, args) { parts.push(semi); return concat(parts); + } case "ClassDeclaration": case "ClassExpression": case "TSAbstractClassDeclaration": @@ -1636,12 +1639,12 @@ function genericPrintNoParens(path, options, print, args) { case "TemplateElement": return join(literalline, n.value.raw.split(/\r?\n/g)); case "TemplateLiteral": - var expressions = path.map(print, "expressions"); + const expressions = path.map(print, "expressions"); parts.push("`"); path.each(function(childPath) { - var i = childPath.getName(); + const i = childPath.getName(); parts.push(print(childPath)); @@ -1678,7 +1681,7 @@ function genericPrintNoParens(path, options, print, args) { let aligned = removeLines(expressions[i]); if (size > 0) { // Use indent to add tabs for all the levels of tabs we need - for (var i = 0; i < Math.floor(size / tabWidth); ++i) { + for (let i = 0; i < Math.floor(size / tabWidth); ++i) { aligned = indent(aligned); } // Use align for all the spaces that are needed @@ -1801,13 +1804,13 @@ function genericPrintNoParens(path, options, print, args) { case "DeclareExportDeclaration": return concat(["declare ", printExportDeclaration(path, options, print)]); case "FunctionTypeAnnotation": - case "TSFunctionType": + case "TSFunctionType": { // FunctionTypeAnnotation is ambiguous: // declare function foo(a: B): void; OR // var A: (a: B) => void; - var parent = path.getParentNode(0); - var parentParent = path.getParentNode(1); - var isArrowFunctionTypeAnnotation = + const parent = path.getParentNode(0); + const parentParent = path.getParentNode(1); + let isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((!getFlowVariance(parent, options) && !parent.optional && @@ -1815,7 +1818,7 @@ function genericPrintNoParens(path, options, print, args) { namedTypes.ObjectTypeCallProperty.check(parent) || namedTypes.DeclareFunction.check(path.getParentNode(2))); - var needsColon = + let needsColon = isArrowFunctionTypeAnnotation && namedTypes.TypeAnnotation.check(parent); @@ -1857,6 +1860,7 @@ function genericPrintNoParens(path, options, print, args) { } return group(concat(parts)); + } case "FunctionTypeParam": return concat([ path.call(print, "name"), @@ -1967,8 +1971,8 @@ function genericPrintNoParens(path, options, print, args) { parts.push(path.call(print, "value")); return concat(parts); - case "ObjectTypeIndexer": - var variance = getFlowVariance(n, options); + case "ObjectTypeIndexer": { + const variance = getFlowVariance(n, options); return concat([ variance || "", "[", @@ -1978,8 +1982,9 @@ function genericPrintNoParens(path, options, print, args) { "]: ", path.call(print, "value") ]); - case "ObjectTypeProperty": - var variance = getFlowVariance(n, options); + } + case "ObjectTypeProperty": { + const variance = getFlowVariance(n, options); return concat([ n.static ? "static " : "", @@ -1990,6 +1995,7 @@ function genericPrintNoParens(path, options, print, args) { isFunctionNotation(n) ? "" : ": ", path.call(print, "value") ]); + } case "QualifiedTypeIdentifier": return concat([ path.call(print, "qualification"), @@ -2050,8 +2056,8 @@ function genericPrintNoParens(path, options, print, args) { case "TypeParameterDeclaration": case "TypeParameterInstantiation": return printTypeParameters(path, options, print, "params"); - case "TypeParameter": - var variance = getFlowVariance(n, options); + case "TypeParameter": { + const variance = getFlowVariance(n, options); if (variance) { parts.push(variance); @@ -2073,6 +2079,7 @@ function genericPrintNoParens(path, options, print, args) { } return concat(parts); + } case "TypeofTypeAnnotation": return concat(["typeof ", path.call(print, "argument")]); case "VoidTypeAnnotation": @@ -2133,7 +2140,7 @@ function genericPrintNoParens(path, options, print, args) { case "TSArrayType": return concat([path.call(print, "elementType"), "[]"]); case "TSPropertySignature": - var computed = !namedTypes.Identifier.check(n.name) && + const computed = !namedTypes.Identifier.check(n.name) && !namedTypes.Literal.check(n.name); parts.push(printTypeScriptModifiers(path, options, print)); @@ -2214,7 +2221,7 @@ function genericPrintNoParens(path, options, print, args) { if (n.type !== "TSCallSignature") { parts.push("new "); } - var isType = n.type === "TSConstructorType"; + const isType = n.type === "TSConstructorType"; parts.push( printTypeParameters(path, options, print, "typeParameters"), "(", @@ -2379,11 +2386,11 @@ function genericPrintNoParens(path, options, print, args) { path.call(print, "expression"), ")" ]) - case "TSModuleDeclaration": - var parent = path.getParentNode(); - var isExternalModule = namedTypes.Literal.check(n.name); - var parentIsDeclaration = parent.type === "TSModuleDeclaration"; - var bodyIsDeclaration = n.body.type === "TSModuleDeclaration"; + case "TSModuleDeclaration": { + const parent = path.getParentNode(); + const isExternalModule = namedTypes.Literal.check(n.name); + const parentIsDeclaration = parent.type === "TSModuleDeclaration"; + const bodyIsDeclaration = n.body.type === "TSModuleDeclaration"; if (parentIsDeclaration) { parts.push("."); @@ -2392,7 +2399,7 @@ function genericPrintNoParens(path, options, print, args) { // Global declaration looks like this: // declare global { ... } - var isGlobalDeclaration = n.name.type === "Identifier" && + const isGlobalDeclaration = n.name.type === "Identifier" && n.name.name === "global" && n.modifiers.some(modifier => modifier.type === "TSDeclareKeyword"); @@ -2415,7 +2422,7 @@ function genericPrintNoParens(path, options, print, args) { } return concat(parts); - + } case "TSModuleBlock": return path.call(function(bodyPath) { return printStatementSequence(bodyPath, options, print); @@ -2470,7 +2477,7 @@ function printStatementSequence(path, options, print) { const isClass = bodyNode.type === "ClassBody"; path.map((stmtPath, i) => { - var stmt = stmtPath.getValue(); + const stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy // "statements," it's safer simply to skip them. @@ -2545,10 +2552,10 @@ function printPropertyKey(path, options, print) { } function printMethod(path, options, print) { - var node = path.getNode(); - var semi = options.semi ? ";" : ""; - var kind = node.kind; - var parts = []; + const node = path.getNode(); + const semi = options.semi ? ";" : ""; + const kind = node.kind; + const parts = []; if (node.type === "ObjectMethod" || node.type === "ClassMethod") { node.value = node; @@ -2570,7 +2577,7 @@ function printMethod(path, options, print) { parts.push(kind, " "); } - var key = printPropertyKey(path, options, print); + let key = printPropertyKey(path, options, print); if (node.computed) { key = concat(["[", key, "]"]); @@ -2640,8 +2647,8 @@ function shouldGroupFirstArg(args) { } function printArgumentsList(path, options, print) { - var printed = path.map(print, "arguments"); - var n = path.getValue(); + const printed = path.map(print, "arguments"); + const n = path.getValue(); if (printed.length === 0) { return concat([ "(", @@ -2739,19 +2746,19 @@ function printFunctionTypeParameters(path, options, print) { } function printFunctionParams(path, print, options, expandArg) { - var fun = path.getValue(); + const fun = path.getValue(); // namedTypes.Function.assert(fun); - var paramsField = (fun.type === "TSFunctionType" || + const paramsField = (fun.type === "TSFunctionType" || fun.type === "TSMethodSignature") ? "parameters" : "params"; - var printed = path.map(print, paramsField); + const printed = path.map(print, paramsField); if (fun.defaults) { path.each(function(defExprPath) { - var i = defExprPath.getName(); - var p = printed[i]; + const i = defExprPath.getName(); + const p = printed[i]; if (p && defExprPath.getValue()) { printed[i] = concat([p, " = ", print(defExprPath)]); @@ -2862,8 +2869,8 @@ function canPrintParamsWithoutParens(node) { } function printFunctionDeclaration(path, print, options) { - var n = path.getValue(); - var parts = []; + const n = path.getValue(); + const parts = []; if (n.async) { parts.push("async "); @@ -2894,8 +2901,8 @@ function printFunctionDeclaration(path, print, options) { } function printObjectMethod(path, options, print) { - var objMethod = path.getValue(); - var parts = []; + const objMethod = path.getValue(); + const parts = []; if (objMethod.async) { parts.push("async "); @@ -2909,7 +2916,7 @@ function printObjectMethod(path, options, print) { return printMethod(path, options, print); } - var key = printPropertyKey(path, options, print); + const key = printPropertyKey(path, options, print); if (objMethod.computed) { parts.push("[", key, "]"); @@ -3043,7 +3050,7 @@ function printExportDeclaration(path, options, print) { } function printFlowDeclaration(path, parts) { - var parentExportDecl = util.getParentExportDeclaration(path); + const parentExportDecl = util.getParentExportDeclaration(path); if (parentExportDecl) { assert.strictEqual(parentExportDecl.type, "DeclareExportDeclaration"); @@ -3281,9 +3288,9 @@ function printMemberChain(path, options, print) { // < fn()()() >.something() // - then, as many MemberExpression as possible but the last one // < this.items >.something() - var groups = []; - var currentGroup = [printedNodes[0]]; - var i = 1; + const groups = []; + let currentGroup = [printedNodes[0]]; + let i = 1; for (; i < printedNodes.length; ++i) { if (printedNodes[i].node.type === "CallExpression") { currentGroup.push(printedNodes[i]); @@ -3308,7 +3315,7 @@ function printMemberChain(path, options, print) { // a sequence of CallExpression. To compute it, we keep adding things to the // group until we has seen a CallExpression in the past and reach a // MemberExpression - var hasSeenCallExpression = false; + let hasSeenCallExpression = false; for (; i < printedNodes.length; ++i) { if ( hasSeenCallExpression && printedNodes[i].node.type === "MemberExpression" diff --git a/src/typescript-ast-nodes.js b/src/typescript-ast-nodes.js index b270f9b03..07c897731 100644 --- a/src/typescript-ast-nodes.js +++ b/src/typescript-ast-nodes.js @@ -1,10 +1,10 @@ module.exports = function(fork) { fork.use(require("ast-types/def/es7")); - var types = fork.use(require("ast-types/lib/types")); - var def = types.Type.def; - var or = types.Type.or; - var defaults = fork.use(require("ast-types/lib/shared")).defaults; + const types = fork.use(require("ast-types/lib/types")); + const def = types.Type.def; + const or = types.Type.or; + const defaults = fork.use(require("ast-types/lib/shared")).defaults; // Ambient def("TSAmbientVariableDefinition").bases("VariableDeclaration"); diff --git a/src/util.js b/src/util.js index 6106c1096..92207f884 100644 --- a/src/util.js +++ b/src/util.js @@ -16,7 +16,7 @@ function isExportDeclaration(node) { } function getParentExportDeclaration(path) { - var parentNode = path.getParentNode(); + const parentNode = path.getParentNode(); if (path.getName() === "declaration" && isExportDeclaration(parentNode)) { return parentNode; } @@ -85,7 +85,7 @@ function skipInlineComment(text, index) { } if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") { - for (var i = index + 2; i < text.length; ++i) { + for (let i = index + 2; i < text.length; ++i) { if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") { return i + 2; } @@ -152,7 +152,7 @@ function hasNewline(text, index, opts) { } function hasNewlineInRange(text, start, end) { - for (var i = start; i < end; ++i) { + for (let i = start; i < end; ++i) { if (text.charAt(i) === "\n") { return true; } @@ -234,7 +234,7 @@ function setLocEnd(node, index) { } } -var PRECEDENCE = {}; +const PRECEDENCE = {}; [ ["||"], ["&&"],