<commit_before>/**
 * @license
 * Copyright 2013 Palantir Technologies, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as ts from "typescript";
import * as Lint from "../index";

import * as utils from "tsutils";

const OPTION_DESTRUCTURING_ALL = "all";
const OPTION_DESTRUCTURING_ANY = "any";

interface Options {
    destructuringAll: boolean;
}

export class Rule extends Lint.Rules.AbstractRule {
    /* tslint:disable:object-literal-sort-keys */
    public static metadata: Lint.IRuleMetadata = {
        ruleName: "prefer-const",
        description: "Requires that variable declarations use `const` instead of `let` and `var` if possible.",
        descriptionDetails: Lint.Utils.dedent`
            If a variable is only assigned to once when it is declared, it should be declared using 'const'`,
        hasFix: true,
        optionsDescription: Lint.Utils.dedent`
            An optional object containing the property "destructuring" with two possible values:
            
            * "${OPTION_DESTRUCTURING_ANY}" (default) - If any variable in destructuring can be const, this rule warns for those variables.
            * "${OPTION_DESTRUCTURING_ALL}" - Only warns if all variables in destructuring can be const.`,
        options: {
            type: "object",
            properties: {
                destructuring: {
                    type: "string",
                    enum: [OPTION_DESTRUCTURING_ALL, OPTION_DESTRUCTURING_ANY],
                },
            },
        },
        optionExamples: [
            "true",
            `[true, {"destructuring": "${OPTION_DESTRUCTURING_ALL}"}]`,
        ],
        type: "maintainability",
        typescriptOnly: false,
    };
    /* tslint:enable:object-literal-sort-keys */

    public static FAILURE_STRING_FACTORY = (identifier: string, blockScoped: boolean) => {
        return `Identifier '${identifier}' is never reassigned; use 'const' instead of '${blockScoped ? "let" : "var"}'.`;
    }

    public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
        const options: Options = {
            destructuringAll: this.ruleArguments.length !== 0 &&
                this.ruleArguments[0].destructuring === "all",
        };
        const preferConstWalker = new PreferConstWalker(sourceFile, this.ruleName, options);
        return this.applyWithWalker(preferConstWalker);
    }
}

class Scope {
    public functionScope: Scope;
    public variables = new Map<string, VariableInfo>();
    public reassigned = new Set<string>();
    constructor(functionScope?: Scope) {
        // if no functionScope is provided we are in the process of creating a new function scope, which for consistency links to itself
        this.functionScope = functionScope || this;
    }

    public addVariable(identifier: ts.Identifier, declarationInfo: DeclarationInfo, destructuringInfo?: DestructuringInfo) {
        // block scoped variables go to the block scope, function scoped variables to the containing function scope
        const scope = declarationInfo.isBlockScoped ? this : this.functionScope;
        scope.variables.set(identifier.text, {
            declarationInfo,
            destructuringInfo,
            identifier,
            reassigned: false,
        });
    }
}

interface VariableInfo {
    identifier: ts.Identifier;
    reassigned: boolean;
    declarationInfo: DeclarationInfo;
    destructuringInfo: DestructuringInfo | undefined;
}

interface DeclarationListInfo {
    allInitialized: boolean;
    canBeConst: true;
    declarationList: ts.VariableDeclarationList;
    isBlockScoped: boolean;
    isForLoop: boolean;
    reassignedSiblings: boolean;
}

interface UnchangeableDeclarationInfo {
    canBeConst: false;
    isBlockScoped: boolean;
}

type DeclarationInfo = DeclarationListInfo | UnchangeableDeclarationInfo;

interface DestructuringInfo {
    reassignedSiblings: boolean;
}

class PreferConstWalker extends Lint.AbstractWalker<Options> {
    private scope: Scope;
    public walk(sourceFile: ts.SourceFile) {
        this.scope = new Scope();
        const cb = (node: ts.Node): void => {
            const savedScope = this.scope;
            const boundary = utils.isScopeBoundary(node);
            if (boundary !== utils.ScopeBoundary.None) {
                if (boundary === utils.ScopeBoundary.Function) {
                    this.scope = new Scope();
                    if (utils.isFunctionDeclaration(node) ||
                        utils.isMethodDeclaration(node) ||
                        utils.isFunctionExpression(node) ||
                        utils.isArrowFunction(node)) {
                        // special handling for function parameters
                        // each parameter initializer can only reassign preceding parameters of variables of the containing scope
                        if (node.body !== undefined) {
                            for (const param of node.parameters) {
                                cb(param);
                                this.settle(savedScope);
                            }
                            cb(node.body);
                            this.onScopeEnd(savedScope);
                        }
                        this.scope = savedScope;
                        return;
                    }
                } else {
                    this.scope = new Scope(this.scope.functionScope);
                }
            }
            if (node.kind === ts.SyntaxKind.VariableDeclarationList) {
                this.handleVariableDeclaration(node as ts.VariableDeclarationList);
            } else if (node.kind === ts.SyntaxKind.CatchClause) {
                this.handleBindingName((node as ts.CatchClause).variableDeclaration.name, {
                    canBeConst: false,
                    isBlockScoped: true,<commit_msg>Minor fix for prefer-const (#2343)<commit_after>/**
 * @license
 * Copyright 2013 Palantir Technologies, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as ts from "typescript";
import * as Lint from "../index";

import * as utils from "tsutils";

const OPTION_DESTRUCTURING_ALL = "all";
const OPTION_DESTRUCTURING_ANY = "any";

interface Options {
    destructuringAll: boolean;
}

export class Rule extends Lint.Rules.AbstractRule {
    /* tslint:disable:object-literal-sort-keys */
    public static metadata: Lint.IRuleMetadata = {
        ruleName: "prefer-const",
        description: "Requires that variable declarations use `const` instead of `let` and `var` if possible.",
        descriptionDetails: Lint.Utils.dedent`
            If a variable is only assigned to once when it is declared, it should be declared using 'const'`,
        hasFix: true,
        optionsDescription: Lint.Utils.dedent`
            An optional object containing the property "destructuring" with two possible values:
            
            * "${OPTION_DESTRUCTURING_ANY}" (default) - If any variable in destructuring can be const, this rule warns for those variables.
            * "${OPTION_DESTRUCTURING_ALL}" - Only warns if all variables in destructuring can be const.`,
        options: {
            type: "object",
            properties: {
                destructuring: {
                    type: "string",
                    enum: [OPTION_DESTRUCTURING_ALL, OPTION_DESTRUCTURING_ANY],
                },
            },
        },
        optionExamples: [
            "true",
            `[true, {"destructuring": "${OPTION_DESTRUCTURING_ALL}"}]`,
        ],
        type: "maintainability",
        typescriptOnly: false,
    };
    /* tslint:enable:object-literal-sort-keys */

    public static FAILURE_STRING_FACTORY = (identifier: string, blockScoped: boolean) => {
        return `Identifier '${identifier}' is never reassigned; use 'const' instead of '${blockScoped ? "let" : "var"}'.`;
    }

    public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
        const options: Options = {
            destructuringAll: this.ruleArguments.length !== 0 &&
                this.ruleArguments[0].destructuring === OPTION_DESTRUCTURING_ALL,
        };
        const preferConstWalker = new PreferConstWalker(sourceFile, this.ruleName, options);
        return this.applyWithWalker(preferConstWalker);
    }
}

class Scope {
    public functionScope: Scope;
    public variables = new Map<string, VariableInfo>();
    public reassigned = new Set<string>();
    constructor(functionScope?: Scope) {
        // if no functionScope is provided we are in the process of creating a new function scope, which for consistency links to itself
        this.functionScope = functionScope || this;
    }

    public addVariable(identifier: ts.Identifier, declarationInfo: DeclarationInfo, destructuringInfo?: DestructuringInfo) {
        // block scoped variables go to the block scope, function scoped variables to the containing function scope
        const scope = declarationInfo.isBlockScoped ? this : this.functionScope;
        scope.variables.set(identifier.text, {
            declarationInfo,
            destructuringInfo,
            identifier,
            reassigned: false,
        });
    }
}

interface VariableInfo {
    identifier: ts.Identifier;
    reassigned: boolean;
    declarationInfo: DeclarationInfo;
    destructuringInfo: DestructuringInfo | undefined;
}

interface DeclarationListInfo {
    allInitialized: boolean;
    canBeConst: true;
    declarationList: ts.VariableDeclarationList;
    isBlockScoped: boolean;
    isForLoop: boolean;
    reassignedSiblings: boolean;
}

interface UnchangeableDeclarationInfo {
    canBeConst: false;
    isBlockScoped: boolean;
}

type DeclarationInfo = DeclarationListInfo | UnchangeableDeclarationInfo;

interface DestructuringInfo {
    reassignedSiblings: boolean;
}

class PreferConstWalker extends Lint.AbstractWalker<Options> {
    private scope: Scope;
    public walk(sourceFile: ts.SourceFile) {
        this.scope = new Scope();
        const cb = (node: ts.Node): void => {
            const savedScope = this.scope;
            const boundary = utils.isScopeBoundary(node);
            if (boundary !== utils.ScopeBoundary.None) {
                if (boundary === utils.ScopeBoundary.Function) {
                    this.scope = new Scope();
                    if (utils.isFunctionDeclaration(node) ||
                        utils.isMethodDeclaration(node) ||
                        utils.isFunctionExpression(node) ||
                        utils.isArrowFunction(node) ||
                        utils.isConstructorDeclaration(node)) {
                        // special handling for function parameters
                        // each parameter initializer can only reassign preceding parameters of variables of the containing scope
                        if (node.body !== undefined) {
                            for (const param of node.parameters) {
                                cb(param);
                                this.settle(savedScope);
                            }
                            cb(node.body);
                            this.onScopeEnd(savedScope);
                        }
                        this.scope = savedScope;
                        return;
                    }
                } else {
                    this.scope = new Scope(this.scope.functionScope);
                }
            }
            if (node.kind === ts.SyntaxKind.VariableDeclarationList) {
                this.handleVariableDeclaration(node as ts.VariableDeclarationList);
            } else if (node.kind === ts.SyntaxKind.CatchClause) {
                this.handleBindingName((node as ts.CatchClause).variableDeclaration.name, {
                    canBeConst: false,
                    isBlockScoped: true,
{'fraction_non_alphanumeric': 0.08732020012507817, 'fraction_numerical': 0.001876172607879925, 'mean_word_length': 2.2151294295049007, 'pattern_counts': {'":': 2, '<': 9, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5690798', 'n_tokens_mistral': 3239, 'n_tokens_neox': 3164, 'n_words': 934}