123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593 |
-
-
- "use strict";
-
-
-
-
-
- const lodash = require("lodash");
- const astUtils = require("../util/ast-utils");
- const createTree = require("functional-red-black-tree");
-
-
-
-
-
- const KNOWN_NODES = new Set([
- "AssignmentExpression",
- "AssignmentPattern",
- "ArrayExpression",
- "ArrayPattern",
- "ArrowFunctionExpression",
- "AwaitExpression",
- "BlockStatement",
- "BinaryExpression",
- "BreakStatement",
- "CallExpression",
- "CatchClause",
- "ClassBody",
- "ClassDeclaration",
- "ClassExpression",
- "ConditionalExpression",
- "ContinueStatement",
- "DoWhileStatement",
- "DebuggerStatement",
- "EmptyStatement",
- "ExperimentalRestProperty",
- "ExperimentalSpreadProperty",
- "ExpressionStatement",
- "ForStatement",
- "ForInStatement",
- "ForOfStatement",
- "FunctionDeclaration",
- "FunctionExpression",
- "Identifier",
- "IfStatement",
- "Literal",
- "LabeledStatement",
- "LogicalExpression",
- "MemberExpression",
- "MetaProperty",
- "MethodDefinition",
- "NewExpression",
- "ObjectExpression",
- "ObjectPattern",
- "Program",
- "Property",
- "RestElement",
- "ReturnStatement",
- "SequenceExpression",
- "SpreadElement",
- "Super",
- "SwitchCase",
- "SwitchStatement",
- "TaggedTemplateExpression",
- "TemplateElement",
- "TemplateLiteral",
- "ThisExpression",
- "ThrowStatement",
- "TryStatement",
- "UnaryExpression",
- "UpdateExpression",
- "VariableDeclaration",
- "VariableDeclarator",
- "WhileStatement",
- "WithStatement",
- "YieldExpression",
- "JSXIdentifier",
- "JSXNamespacedName",
- "JSXMemberExpression",
- "JSXEmptyExpression",
- "JSXExpressionContainer",
- "JSXElement",
- "JSXClosingElement",
- "JSXOpeningElement",
- "JSXAttribute",
- "JSXSpreadAttribute",
- "JSXText",
- "ExportDefaultDeclaration",
- "ExportNamedDeclaration",
- "ExportAllDeclaration",
- "ExportSpecifier",
- "ImportDeclaration",
- "ImportSpecifier",
- "ImportDefaultSpecifier",
- "ImportNamespaceSpecifier"
- ]);
-
-
-
-
-
- class BinarySearchTree {
-
-
-
- constructor() {
- this._rbTree = createTree();
- }
-
-
-
- insert(key, value) {
- const iterator = this._rbTree.find(key);
-
- if (iterator.valid) {
- this._rbTree = iterator.update(value);
- } else {
- this._rbTree = this._rbTree.insert(key, value);
- }
- }
-
-
-
- findLe(key) {
- const iterator = this._rbTree.le(key);
-
- return iterator && { key: iterator.key, value: iterator.value };
- }
-
-
-
- deleteRange(start, end) {
-
-
- if (start === end) {
- return;
- }
- const iterator = this._rbTree.ge(start);
-
- while (iterator.valid && iterator.key < end) {
- this._rbTree = this._rbTree.remove(iterator.key);
- iterator.next();
- }
- }
- }
-
-
- class TokenInfo {
-
-
-
- constructor(sourceCode) {
- this.sourceCode = sourceCode;
- this.firstTokensByLineNumber = sourceCode.tokensAndComments.reduce((map, token) => {
- if (!map.has(token.loc.start.line)) {
- map.set(token.loc.start.line, token);
- }
- if (!map.has(token.loc.end.line) && sourceCode.text.slice(token.range[1] - token.loc.end.column, token.range[1]).trim()) {
- map.set(token.loc.end.line, token);
- }
- return map;
- }, new Map());
- }
-
-
-
- getFirstTokenOfLine(token) {
- return this.firstTokensByLineNumber.get(token.loc.start.line);
- }
-
-
-
- isFirstTokenOfLine(token) {
- return this.getFirstTokenOfLine(token) === token;
- }
-
-
-
- getTokenIndent(token) {
- return this.sourceCode.text.slice(token.range[0] - token.loc.start.column, token.range[0]);
- }
- }
-
-
- class OffsetStorage {
-
-
-
- constructor(tokenInfo, indentSize, indentType) {
- this._tokenInfo = tokenInfo;
- this._indentSize = indentSize;
- this._indentType = indentType;
-
- this._tree = new BinarySearchTree();
- this._tree.insert(0, { offset: 0, from: null, force: false });
-
- this._lockedFirstTokens = new WeakMap();
- this._desiredIndentCache = new WeakMap();
- this._ignoredTokens = new WeakSet();
- }
-
- _getOffsetDescriptor(token) {
- return this._tree.findLe(token.range[0]).value;
- }
-
-
-
- matchOffsetOf(baseToken, offsetToken) {
-
-
-
- this._lockedFirstTokens.set(offsetToken, baseToken);
- }
-
-
-
- setDesiredOffset(token, fromToken, offset) {
- return this.setDesiredOffsets(token.range, fromToken, offset);
- }
-
-
-
- setDesiredOffsets(range, fromToken, offset, force) {
-
-
-
-
- const descriptorToInsert = { offset, from: fromToken, force };
-
- const descriptorAfterRange = this._tree.findLe(range[1]).value;
-
- const fromTokenIsInRange = fromToken && fromToken.range[0] >= range[0] && fromToken.range[1] <= range[1];
- const fromTokenDescriptor = fromTokenIsInRange && this._getOffsetDescriptor(fromToken);
-
-
- this._tree.deleteRange(range[0] + 1, range[1]);
-
-
- this._tree.insert(range[0], descriptorToInsert);
-
-
-
- if (fromTokenIsInRange) {
- this._tree.insert(fromToken.range[0], fromTokenDescriptor);
- this._tree.insert(fromToken.range[1], descriptorToInsert);
- }
-
-
-
- this._tree.insert(range[1], descriptorAfterRange);
- }
-
-
-
- getDesiredIndent(token) {
- if (!this._desiredIndentCache.has(token)) {
-
- if (this._ignoredTokens.has(token)) {
-
-
-
- this._desiredIndentCache.set(
- token,
- this._tokenInfo.getTokenIndent(token)
- );
- } else if (this._lockedFirstTokens.has(token)) {
- const firstToken = this._lockedFirstTokens.get(token);
-
- this._desiredIndentCache.set(
- token,
-
-
- this.getDesiredIndent(this._tokenInfo.getFirstTokenOfLine(firstToken)) +
-
-
- this._indentType.repeat(firstToken.loc.start.column - this._tokenInfo.getFirstTokenOfLine(firstToken).loc.start.column)
- );
- } else {
- const offsetInfo = this._getOffsetDescriptor(token);
- const offset = (
- offsetInfo.from &&
- offsetInfo.from.loc.start.line === token.loc.start.line &&
- !/^\s*?\n/.test(token.value) &&
- !offsetInfo.force
- ) ? 0 : offsetInfo.offset * this._indentSize;
-
- this._desiredIndentCache.set(
- token,
- (offsetInfo.from ? this.getDesiredIndent(offsetInfo.from) : "") + this._indentType.repeat(offset)
- );
- }
- }
- return this._desiredIndentCache.get(token);
- }
-
-
-
- ignoreToken(token) {
- if (this._tokenInfo.isFirstTokenOfLine(token)) {
- this._ignoredTokens.add(token);
- }
- }
-
-
-
- getFirstDependency(token) {
- return this._getOffsetDescriptor(token).from;
- }
- }
-
- const ELEMENT_LIST_SCHEMA = {
- oneOf: [
- {
- type: "integer",
- minimum: 0
- },
- {
- enum: ["first", "off"]
- }
- ]
- };
-
- module.exports = {
- meta: {
- type: "layout",
-
- docs: {
- description: "enforce consistent indentation",
- category: "Stylistic Issues",
- recommended: false,
- url: "https://eslint.org/docs/rules/indent"
- },
-
- fixable: "whitespace",
-
- schema: [
- {
- oneOf: [
- {
- enum: ["tab"]
- },
- {
- type: "integer",
- minimum: 0
- }
- ]
- },
- {
- type: "object",
- properties: {
- SwitchCase: {
- type: "integer",
- minimum: 0
- },
- VariableDeclarator: {
- oneOf: [
- {
- type: "integer",
- minimum: 0
- },
- {
- type: "object",
- properties: {
- var: {
- type: "integer",
- minimum: 0
- },
- let: {
- type: "integer",
- minimum: 0
- },
- const: {
- type: "integer",
- minimum: 0
- }
- },
- additionalProperties: false
- }
- ]
- },
- outerIIFEBody: {
- type: "integer",
- minimum: 0
- },
- MemberExpression: {
- oneOf: [
- {
- type: "integer",
- minimum: 0
- },
- {
- enum: ["off"]
- }
- ]
- },
- FunctionDeclaration: {
- type: "object",
- properties: {
- parameters: ELEMENT_LIST_SCHEMA,
- body: {
- type: "integer",
- minimum: 0
- }
- },
- additionalProperties: false
- },
- FunctionExpression: {
- type: "object",
- properties: {
- parameters: ELEMENT_LIST_SCHEMA,
- body: {
- type: "integer",
- minimum: 0
- }
- },
- additionalProperties: false
- },
- CallExpression: {
- type: "object",
- properties: {
- arguments: ELEMENT_LIST_SCHEMA
- },
- additionalProperties: false
- },
- ArrayExpression: ELEMENT_LIST_SCHEMA,
- ObjectExpression: ELEMENT_LIST_SCHEMA,
- ImportDeclaration: ELEMENT_LIST_SCHEMA,
- flatTernaryExpressions: {
- type: "boolean"
- },
- ignoredNodes: {
- type: "array",
- items: {
- type: "string",
- not: {
- pattern: ":exit$"
- }
- }
- },
- ignoreComments: {
- type: "boolean"
- }
- },
- additionalProperties: false
- }
- ]
- },
-
- create(context) {
- const DEFAULT_VARIABLE_INDENT = 1;
- const DEFAULT_PARAMETER_INDENT = 1;
- const DEFAULT_FUNCTION_BODY_INDENT = 1;
-
- let indentType = "space";
- let indentSize = 4;
- const options = {
- SwitchCase: 0,
- VariableDeclarator: {
- var: DEFAULT_VARIABLE_INDENT,
- let: DEFAULT_VARIABLE_INDENT,
- const: DEFAULT_VARIABLE_INDENT
- },
- outerIIFEBody: 1,
- FunctionDeclaration: {
- parameters: DEFAULT_PARAMETER_INDENT,
- body: DEFAULT_FUNCTION_BODY_INDENT
- },
- FunctionExpression: {
- parameters: DEFAULT_PARAMETER_INDENT,
- body: DEFAULT_FUNCTION_BODY_INDENT
- },
- CallExpression: {
- arguments: DEFAULT_PARAMETER_INDENT
- },
- MemberExpression: 1,
- ArrayExpression: 1,
- ObjectExpression: 1,
- ImportDeclaration: 1,
- flatTernaryExpressions: false,
- ignoredNodes: [],
- ignoreComments: false
- };
-
- if (context.options.length) {
- if (context.options[0] === "tab") {
- indentSize = 1;
- indentType = "tab";
- } else {
- indentSize = context.options[0];
- indentType = "space";
- }
-
- if (context.options[1]) {
- lodash.merge(options, context.options[1]);
-
- if (typeof options.VariableDeclarator === "number") {
- options.VariableDeclarator = {
- var: options.VariableDeclarator,
- let: options.VariableDeclarator,
- const: options.VariableDeclarator
- };
- }
- }
- }
-
- const sourceCode = context.getSourceCode();
- const tokenInfo = new TokenInfo(sourceCode);
- const offsets = new OffsetStorage(tokenInfo, indentSize, indentType === "space" ? " " : "\t");
- const parameterParens = new WeakSet();
-
-
-
- function createErrorMessage(expectedAmount, actualSpaces, actualTabs) {
- const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`;
- const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`;
- const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`;
- let foundStatement;
-
- if (actualSpaces > 0) {
-
-
-
- foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`;
- } else if (actualTabs > 0) {
- foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`;
- } else {
- foundStatement = "0";
- }
-
- return `Expected indentation of ${expectedStatement} but found ${foundStatement}.`;
- }
-
-
-
- function report(token, neededIndent) {
- const actualIndent = Array.from(tokenInfo.getTokenIndent(token));
- const numSpaces = actualIndent.filter(char => char === " ").length;
- const numTabs = actualIndent.filter(char => char === "\t").length;
-
- context.report({
- node: token,
- message: createErrorMessage(neededIndent.length, numSpaces, numTabs),
- loc: {
- start: { line: token.loc.start.line, column: 0 },
- end: { line: token.loc.start.line, column: token.loc.start.column }
- },
- fix(fixer) {
- const range = [token.range[0] - token.loc.start.column, token.range[0]];
- const newText = neededIndent;
-
- return fixer.replaceTextRange(range, newText);
- }
- });
- }
-
-
-
- function validateTokenIndent(token, desiredIndent) {
- const indentation = tokenInfo.getTokenIndent(token);
-
- return indentation === desiredIndent ||
-
-
- indentation.includes(" ") && indentation.includes("\t");
- }
-
-
-
- function isOuterIIFE(node) {
-
-
-
- if (!node.parent || node.parent.type !== "CallExpression" || node.parent.callee !== node) {
- return false;
- }
-
-
-
- let statement = node.parent && node.parent.parent;
-
- while (
- statement.type === "UnaryExpression" && ["!", "~", "+", "-"].indexOf(statement.operator) > -1 ||
- statement.type === "AssignmentExpression" ||
- statement.type === "LogicalExpression" ||
- statement.type === "SequenceExpression" ||
- statement.type === "VariableDeclarator"
- ) {
- statement = statement.parent;
- }
-
- return (statement.type === "ExpressionStatement" || statement.type === "VariableDeclaration") && statement.parent.type === "Program";
- }
-
-
-
- function countTrailingLinebreaks(string) {
- const trailingWhitespace = string.match(/\s*$/)[0];
- const linebreakMatches = trailingWhitespace.match(astUtils.createGlobalLinebreakMatcher());
-
- return linebreakMatches === null ? 0 : linebreakMatches.length;
- }
-
-
-
- function addElementListIndent(elements, startToken, endToken, offset) {
-
-
-
- function getFirstToken(element) {
- let token = sourceCode.getTokenBefore(element);
-
- while (astUtils.isOpeningParenToken(token) && token !== startToken) {
- token = sourceCode.getTokenBefore(token);
- }
- return sourceCode.getTokenAfter(token);
- }
-
-
- offsets.setDesiredOffsets(
- [startToken.range[1], endToken.range[0]],
- startToken,
- typeof offset === "number" ? offset : 1
- );
- offsets.setDesiredOffset(endToken, startToken, 0);
-
-
- if (offset === "first" && elements.length && !elements[0]) {
- return;
- }
- elements.forEach((element, index) => {
- if (!element) {
-
-
- return;
- }
- if (offset === "off") {
-
-
- offsets.ignoreToken(getFirstToken(element));
- }
-
-
- if (index === 0) {
- return;
- }
- if (offset === "first" && tokenInfo.isFirstTokenOfLine(getFirstToken(element))) {
- offsets.matchOffsetOf(getFirstToken(elements[0]), getFirstToken(element));
- } else {
- const previousElement = elements[index - 1];
- const firstTokenOfPreviousElement = previousElement && getFirstToken(previousElement);
- const previousElementLastToken = previousElement && sourceCode.getLastToken(previousElement);
-
- if (
- previousElement &&
- previousElementLastToken.loc.end.line - countTrailingLinebreaks(previousElementLastToken.value) > startToken.loc.end.line
- ) {
- offsets.setDesiredOffsets(
- [previousElement.range[1], element.range[1]],
- firstTokenOfPreviousElement,
- 0
- );
- }
- }
- });
- }
-
-
-
- function addBlocklessNodeIndent(node) {
- if (node.type !== "BlockStatement") {
- const lastParentToken = sourceCode.getTokenBefore(node, astUtils.isNotOpeningParenToken);
-
- let firstBodyToken = sourceCode.getFirstToken(node);
- let lastBodyToken = sourceCode.getLastToken(node);
-
- while (
- astUtils.isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)) &&
- astUtils.isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken))
- ) {
- firstBodyToken = sourceCode.getTokenBefore(firstBodyToken);
- lastBodyToken = sourceCode.getTokenAfter(lastBodyToken);
- }
-
- offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1);
-
-
-
- const lastToken = sourceCode.getLastToken(node);
-
- if (node.type !== "EmptyStatement" && astUtils.isSemicolonToken(lastToken)) {
- offsets.setDesiredOffset(lastToken, lastParentToken, 0);
- }
- }
- }
-
-
-
- function addFunctionCallIndent(node) {
- let openingParen;
-
- if (node.arguments.length) {
- openingParen = sourceCode.getFirstTokenBetween(node.callee, node.arguments[0], astUtils.isOpeningParenToken);
- } else {
- openingParen = sourceCode.getLastToken(node, 1);
- }
- const closingParen = sourceCode.getLastToken(node);
-
- parameterParens.add(openingParen);
- parameterParens.add(closingParen);
- offsets.setDesiredOffset(openingParen, sourceCode.getTokenBefore(openingParen), 0);
-
- addElementListIndent(node.arguments, openingParen, closingParen, options.CallExpression.arguments);
- }
-
-
-
- function addParensIndent(tokens) {
- const parenStack = [];
- const parenPairs = [];
-
- tokens.forEach(nextToken => {
-
-
- if (astUtils.isOpeningParenToken(nextToken)) {
- parenStack.push(nextToken);
- } else if (astUtils.isClosingParenToken(nextToken)) {
- parenPairs.unshift({ left: parenStack.pop(), right: nextToken });
- }
- });
-
- parenPairs.forEach(pair => {
- const leftParen = pair.left;
- const rightParen = pair.right;
-
-
- if (!parameterParens.has(leftParen) && !parameterParens.has(rightParen)) {
- const parenthesizedTokens = new Set(sourceCode.getTokensBetween(leftParen, rightParen));
-
- parenthesizedTokens.forEach(token => {
- if (!parenthesizedTokens.has(offsets.getFirstDependency(token))) {
- offsets.setDesiredOffset(token, leftParen, 1);
- }
- });
- }
-
- offsets.setDesiredOffset(rightParen, leftParen, 0);
- });
- }
-
-
-
- function ignoreNode(node) {
- const unknownNodeTokens = new Set(sourceCode.getTokens(node, { includeComments: true }));
-
- unknownNodeTokens.forEach(token => {
- if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) {
- const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token);
-
- if (token === firstTokenOfLine) {
- offsets.ignoreToken(token);
- } else {
- offsets.setDesiredOffset(token, firstTokenOfLine, 0);
- }
- }
- });
- }
-
-
-
- function isOnFirstLineOfStatement(token, leafNode) {
- let node = leafNode;
-
- while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) {
- node = node.parent;
- }
- node = node.parent;
-
- return !node || node.loc.start.line === token.loc.start.line;
- }
-
-
-
- function hasBlankLinesBetween(firstToken, secondToken) {
- const firstTokenLine = firstToken.loc.end.line;
- const secondTokenLine = secondToken.loc.start.line;
-
- if (firstTokenLine === secondTokenLine || firstTokenLine === secondTokenLine - 1) {
- return false;
- }
-
- for (let line = firstTokenLine + 1; line < secondTokenLine; ++line) {
- if (!tokenInfo.firstTokensByLineNumber.has(line)) {
- return true;
- }
- }
-
- return false;
- }
-
- const ignoredNodeFirstTokens = new Set();
-
- const baseOffsetListeners = {
- "ArrayExpression, ArrayPattern"(node) {
- const openingBracket = sourceCode.getFirstToken(node);
- const closingBracket = sourceCode.getTokenAfter(lodash.findLast(node.elements) || openingBracket, astUtils.isClosingBracketToken);
-
- addElementListIndent(node.elements, openingBracket, closingBracket, options.ArrayExpression);
- },
-
- "ObjectExpression, ObjectPattern"(node) {
- const openingCurly = sourceCode.getFirstToken(node);
- const closingCurly = sourceCode.getTokenAfter(
- node.properties.length ? node.properties[node.properties.length - 1] : openingCurly,
- astUtils.isClosingBraceToken
- );
-
- addElementListIndent(node.properties, openingCurly, closingCurly, options.ObjectExpression);
- },
-
- ArrowFunctionExpression(node) {
- const firstToken = sourceCode.getFirstToken(node);
-
- if (astUtils.isOpeningParenToken(firstToken)) {
- const openingParen = firstToken;
- const closingParen = sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken);
-
- parameterParens.add(openingParen);
- parameterParens.add(closingParen);
- addElementListIndent(node.params, openingParen, closingParen, options.FunctionExpression.parameters);
- }
- addBlocklessNodeIndent(node.body);
- },
-
- AssignmentExpression(node) {
- const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
-
- offsets.setDesiredOffsets([operator.range[0], node.range[1]], sourceCode.getLastToken(node.left), 1);
- offsets.ignoreToken(operator);
- offsets.ignoreToken(sourceCode.getTokenAfter(operator));
- },
-
- "BinaryExpression, LogicalExpression"(node) {
- const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
-
-
-
-
- const tokenAfterOperator = sourceCode.getTokenAfter(operator);
-
- offsets.ignoreToken(operator);
- offsets.ignoreToken(tokenAfterOperator);
- offsets.setDesiredOffset(tokenAfterOperator, operator, 0);
- },
-
- "BlockStatement, ClassBody"(node) {
-
- let blockIndentLevel;
-
- if (node.parent && isOuterIIFE(node.parent)) {
- blockIndentLevel = options.outerIIFEBody;
- } else if (node.parent && (node.parent.type === "FunctionExpression" || node.parent.type === "ArrowFunctionExpression")) {
- blockIndentLevel = options.FunctionExpression.body;
- } else if (node.parent && node.parent.type === "FunctionDeclaration") {
- blockIndentLevel = options.FunctionDeclaration.body;
- } else {
- blockIndentLevel = 1;
- }
-
-
-
- if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) {
- offsets.setDesiredOffset(sourceCode.getFirstToken(node), sourceCode.getFirstToken(node.parent), 0);
- }
- addElementListIndent(node.body, sourceCode.getFirstToken(node), sourceCode.getLastToken(node), blockIndentLevel);
- },
-
- CallExpression: addFunctionCallIndent,
-
-
- "ClassDeclaration[superClass], ClassExpression[superClass]"(node) {
- const classToken = sourceCode.getFirstToken(node);
- const extendsToken = sourceCode.getTokenBefore(node.superClass, astUtils.isNotOpeningParenToken);
-
- offsets.setDesiredOffsets([extendsToken.range[0], node.body.range[0]], classToken, 1);
- },
-
- ConditionalExpression(node) {
- const firstToken = sourceCode.getFirstToken(node);
-
-
-
-
-
-
- if (!options.flatTernaryExpressions ||
- !astUtils.isTokenOnSameLine(node.test, node.consequent) ||
- isOnFirstLineOfStatement(firstToken, node)
- ) {
- const questionMarkToken = sourceCode.getFirstTokenBetween(node.test, node.consequent, token => token.type === "Punctuator" && token.value === "?");
- const colonToken = sourceCode.getFirstTokenBetween(node.consequent, node.alternate, token => token.type === "Punctuator" && token.value === ":");
-
- const firstConsequentToken = sourceCode.getTokenAfter(questionMarkToken);
- const lastConsequentToken = sourceCode.getTokenBefore(colonToken);
- const firstAlternateToken = sourceCode.getTokenAfter(colonToken);
-
- offsets.setDesiredOffset(questionMarkToken, firstToken, 1);
- offsets.setDesiredOffset(colonToken, firstToken, 1);
-
- offsets.setDesiredOffset(firstConsequentToken, firstToken, 1);
-
-
-
- if (lastConsequentToken.loc.end.line === firstAlternateToken.loc.start.line) {
- offsets.setDesiredOffset(firstAlternateToken, firstConsequentToken, 0);
- } else {
-
-
-
- offsets.setDesiredOffset(firstAlternateToken, firstToken, 1);
- }
- }
- },
-
- "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement": node => addBlocklessNodeIndent(node.body),
-
- ExportNamedDeclaration(node) {
- if (node.declaration === null) {
- const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
-
-
- addElementListIndent(node.specifiers, sourceCode.getFirstToken(node, { skip: 1 }), closingCurly, 1);
-
- if (node.source) {
-
-
- offsets.setDesiredOffsets([closingCurly.range[1], node.range[1]], sourceCode.getFirstToken(node), 1);
- }
- }
- },
-
- ForStatement(node) {
- const forOpeningParen = sourceCode.getFirstToken(node, 1);
-
- if (node.init) {
- offsets.setDesiredOffsets(node.init.range, forOpeningParen, 1);
- }
- if (node.test) {
- offsets.setDesiredOffsets(node.test.range, forOpeningParen, 1);
- }
- if (node.update) {
- offsets.setDesiredOffsets(node.update.range, forOpeningParen, 1);
- }
- addBlocklessNodeIndent(node.body);
- },
-
- "FunctionDeclaration, FunctionExpression"(node) {
- const closingParen = sourceCode.getTokenBefore(node.body);
- const openingParen = sourceCode.getTokenBefore(node.params.length ? node.params[0] : closingParen);
-
- parameterParens.add(openingParen);
- parameterParens.add(closingParen);
- addElementListIndent(node.params, openingParen, closingParen, options[node.type].parameters);
- },
-
- IfStatement(node) {
- addBlocklessNodeIndent(node.consequent);
- if (node.alternate && node.alternate.type !== "IfStatement") {
- addBlocklessNodeIndent(node.alternate);
- }
- },
-
- ImportDeclaration(node) {
- if (node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) {
- const openingCurly = sourceCode.getFirstToken(node, astUtils.isOpeningBraceToken);
- const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
-
- addElementListIndent(node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"), openingCurly, closingCurly, options.ImportDeclaration);
- }
-
- const fromToken = sourceCode.getLastToken(node, token => token.type === "Identifier" && token.value === "from");
-
- if (fromToken) {
- offsets.setDesiredOffsets([fromToken.range[0], node.range[1]], sourceCode.getFirstToken(node), 1);
- }
- },
-
- "MemberExpression, JSXMemberExpression, MetaProperty"(node) {
- const object = node.type === "MetaProperty" ? node.meta : node.object;
- const firstNonObjectToken = sourceCode.getFirstTokenBetween(object, node.property, astUtils.isNotClosingParenToken);
- const secondNonObjectToken = sourceCode.getTokenAfter(firstNonObjectToken);
-
- const objectParenCount = sourceCode.getTokensBetween(object, node.property, { filter: astUtils.isClosingParenToken }).length;
- const firstObjectToken = objectParenCount
- ? sourceCode.getTokenBefore(object, { skip: objectParenCount - 1 })
- : sourceCode.getFirstToken(object);
- const lastObjectToken = sourceCode.getTokenBefore(firstNonObjectToken);
- const firstPropertyToken = node.computed ? firstNonObjectToken : secondNonObjectToken;
-
- if (node.computed) {
-
-
- offsets.setDesiredOffset(sourceCode.getLastToken(node), firstNonObjectToken, 0);
- offsets.setDesiredOffsets(node.property.range, firstNonObjectToken, 1);
- }
-
-
-
- const offsetBase = lastObjectToken.loc.end.line === firstPropertyToken.loc.start.line
- ? lastObjectToken
- : firstObjectToken;
-
- if (typeof options.MemberExpression === "number") {
-
-
- offsets.setDesiredOffset(firstNonObjectToken, offsetBase, options.MemberExpression);
-
-
-
- offsets.setDesiredOffset(secondNonObjectToken, node.computed ? firstNonObjectToken : offsetBase, options.MemberExpression);
- } else {
-
-
- offsets.ignoreToken(firstNonObjectToken);
- offsets.ignoreToken(secondNonObjectToken);
-
-
- offsets.setDesiredOffset(firstNonObjectToken, offsetBase, 0);
- offsets.setDesiredOffset(secondNonObjectToken, firstNonObjectToken, 0);
- }
- },
-
- NewExpression(node) {
-
-
- if (node.arguments.length > 0 ||
- astUtils.isClosingParenToken(sourceCode.getLastToken(node)) &&
- astUtils.isOpeningParenToken(sourceCode.getLastToken(node, 1))) {
- addFunctionCallIndent(node);
- }
- },
-
- Property(node) {
- if (!node.shorthand && !node.method && node.kind === "init") {
- const colon = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isColonToken);
-
- offsets.ignoreToken(sourceCode.getTokenAfter(colon));
- }
- },
-
- SwitchStatement(node) {
- const openingCurly = sourceCode.getTokenAfter(node.discriminant, astUtils.isOpeningBraceToken);
- const closingCurly = sourceCode.getLastToken(node);
-
- offsets.setDesiredOffsets([openingCurly.range[1], closingCurly.range[0]], openingCurly, options.SwitchCase);
-
- if (node.cases.length) {
- sourceCode.getTokensBetween(
- node.cases[node.cases.length - 1],
- closingCurly,
- { includeComments: true, filter: astUtils.isCommentToken }
- ).forEach(token => offsets.ignoreToken(token));
- }
- },
-
- SwitchCase(node) {
- if (!(node.consequent.length === 1 && node.consequent[0].type === "BlockStatement")) {
- const caseKeyword = sourceCode.getFirstToken(node);
- const tokenAfterCurrentCase = sourceCode.getTokenAfter(node);
-
- offsets.setDesiredOffsets([caseKeyword.range[1], tokenAfterCurrentCase.range[0]], caseKeyword, 1);
- }
- },
-
- TemplateLiteral(node) {
- node.expressions.forEach((expression, index) => {
- const previousQuasi = node.quasis[index];
- const nextQuasi = node.quasis[index + 1];
- const tokenToAlignFrom = previousQuasi.loc.start.line === previousQuasi.loc.end.line
- ? sourceCode.getFirstToken(previousQuasi)
- : null;
-
- offsets.setDesiredOffsets([previousQuasi.range[1], nextQuasi.range[0]], tokenToAlignFrom, 1);
- offsets.setDesiredOffset(sourceCode.getFirstToken(nextQuasi), tokenToAlignFrom, 0);
- });
- },
-
- VariableDeclaration(node) {
- const variableIndent = Object.prototype.hasOwnProperty.call(options.VariableDeclarator, node.kind)
- ? options.VariableDeclarator[node.kind]
- : DEFAULT_VARIABLE_INDENT;
-
- if (node.declarations[node.declarations.length - 1].loc.start.line > node.loc.start.line) {
-
-
-
- const firstToken = sourceCode.getFirstToken(node);
-
- offsets.setDesiredOffsets(node.range, firstToken, variableIndent, true);
- } else {
- offsets.setDesiredOffsets(node.range, sourceCode.getFirstToken(node), variableIndent);
- }
- const lastToken = sourceCode.getLastToken(node);
-
- if (astUtils.isSemicolonToken(lastToken)) {
- offsets.ignoreToken(lastToken);
- }
- },
-
- VariableDeclarator(node) {
- if (node.init) {
- const equalOperator = sourceCode.getTokenBefore(node.init, astUtils.isNotOpeningParenToken);
- const tokenAfterOperator = sourceCode.getTokenAfter(equalOperator);
-
- offsets.ignoreToken(equalOperator);
- offsets.ignoreToken(tokenAfterOperator);
- offsets.setDesiredOffsets([tokenAfterOperator.range[0], node.range[1]], equalOperator, 1);
- offsets.setDesiredOffset(equalOperator, sourceCode.getLastToken(node.id), 0);
- }
- },
-
- "JSXAttribute[value]"(node) {
- const equalsToken = sourceCode.getFirstTokenBetween(node.name, node.value, token => token.type === "Punctuator" && token.value === "=");
-
- offsets.setDesiredOffsets([equalsToken.range[0], node.value.range[1]], sourceCode.getFirstToken(node.name), 1);
- },
-
- JSXElement(node) {
- if (node.closingElement) {
- addElementListIndent(node.children, sourceCode.getFirstToken(node.openingElement), sourceCode.getFirstToken(node.closingElement), 1);
- }
- },
-
- JSXOpeningElement(node) {
- const firstToken = sourceCode.getFirstToken(node);
- let closingToken;
-
- if (node.selfClosing) {
- closingToken = sourceCode.getLastToken(node, { skip: 1 });
- offsets.setDesiredOffset(sourceCode.getLastToken(node), closingToken, 0);
- } else {
- closingToken = sourceCode.getLastToken(node);
- }
- offsets.setDesiredOffsets(node.name.range, sourceCode.getFirstToken(node));
- addElementListIndent(node.attributes, firstToken, closingToken, 1);
- },
-
- JSXClosingElement(node) {
- const firstToken = sourceCode.getFirstToken(node);
-
- offsets.setDesiredOffsets(node.name.range, firstToken, 1);
- },
-
- JSXExpressionContainer(node) {
- const openingCurly = sourceCode.getFirstToken(node);
- const closingCurly = sourceCode.getLastToken(node);
-
- offsets.setDesiredOffsets(
- [openingCurly.range[1], closingCurly.range[0]],
- openingCurly,
- 1
- );
- },
-
- "*"(node) {
- const firstToken = sourceCode.getFirstToken(node);
-
-
- if (firstToken && !ignoredNodeFirstTokens.has(firstToken)) {
- offsets.setDesiredOffsets(node.range, firstToken, 0);
- }
- }
- };
-
- const listenerCallQueue = [];
-
-
-
- const offsetListeners = lodash.mapValues(
- baseOffsetListeners,
-
-
-
- listener =>
- node =>
- listenerCallQueue.push({ listener, node })
- );
-
-
- const ignoredNodes = new Set();
-
-
-
- function addToIgnoredNodes(node) {
- ignoredNodes.add(node);
- ignoredNodeFirstTokens.add(sourceCode.getFirstToken(node));
- }
-
- const ignoredNodeListeners = options.ignoredNodes.reduce(
- (listeners, ignoredSelector) => Object.assign(listeners, { [ignoredSelector]: addToIgnoredNodes }),
- {}
- );
-
-
-
- return Object.assign(
- offsetListeners,
- ignoredNodeListeners,
- {
- "*:exit"(node) {
-
-
- if (!KNOWN_NODES.has(node.type)) {
- addToIgnoredNodes(node);
- }
- },
- "Program:exit"() {
-
-
- if (options.ignoreComments) {
- sourceCode.getAllComments()
- .forEach(comment => offsets.ignoreToken(comment));
- }
-
-
- listenerCallQueue
- .filter(nodeInfo => !ignoredNodes.has(nodeInfo.node))
- .forEach(nodeInfo => nodeInfo.listener(nodeInfo.node));
-
-
- ignoredNodes.forEach(ignoreNode);
-
- addParensIndent(sourceCode.ast.tokens);
-
-
-
- const precedingTokens = sourceCode.ast.comments.reduce((commentMap, comment) => {
- const tokenOrCommentBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
-
- return commentMap.set(comment, commentMap.has(tokenOrCommentBefore) ? commentMap.get(tokenOrCommentBefore) : tokenOrCommentBefore);
- }, new WeakMap());
-
- sourceCode.lines.forEach((line, lineIndex) => {
- const lineNumber = lineIndex + 1;
-
- if (!tokenInfo.firstTokensByLineNumber.has(lineNumber)) {
-
-
- return;
- }
-
- const firstTokenOfLine = tokenInfo.firstTokensByLineNumber.get(lineNumber);
-
- if (firstTokenOfLine.loc.start.line !== lineNumber) {
-
-
- return;
- }
-
-
- if (validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine))) {
- return;
- }
-
- if (astUtils.isCommentToken(firstTokenOfLine)) {
- const tokenBefore = precedingTokens.get(firstTokenOfLine);
- const tokenAfter = tokenBefore ? sourceCode.getTokenAfter(tokenBefore) : sourceCode.ast.tokens[0];
-
- const mayAlignWithBefore = tokenBefore && !hasBlankLinesBetween(tokenBefore, firstTokenOfLine);
- const mayAlignWithAfter = tokenAfter && !hasBlankLinesBetween(firstTokenOfLine, tokenAfter);
-
-
- if (
- mayAlignWithBefore && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenBefore)) ||
- mayAlignWithAfter && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenAfter))
- ) {
- return;
- }
- }
-
-
- report(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine));
- });
- }
- }
- );
- }
- };
|