Documentation
¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var PreferConstRule = rule.Rule{ Name: "prefer-const", RequiresTypeInfo: true, Run: func(ctx rule.RuleContext, options any) rule.RuleListeners { if ctx.TypeChecker == nil { return rule.RuleListeners{} } opts := parseOptions(options) return rule.RuleListeners{ ast.KindVariableDeclarationList: func(node *ast.Node) { declList := node.AsVariableDeclarationList() if declList == nil || node.Flags&ast.NodeFlagsLet == 0 || declList.Declarations == nil { return } if isInForStatement(node) { return } isForInOrOf := isInForInOrOf(node) // Collect candidates across ALL declarators in the VDL to determine // if the entire VDL can be auto-fixed (let → const). var allConstCandidates []*candidateInfo totalBindings := 0 totalConstBindings := 0 allHaveInit := true for _, decl := range declList.Declarations.Nodes { varDecl := decl.AsVariableDeclaration() if varDecl == nil || varDecl.Name() == nil { continue } hasInit := varDecl.Initializer != nil || isForInOrOf if !hasInit { allHaveInit = false } candidates := collectBindingNames(varDecl.Name(), hasInit) if len(candidates) == 0 { continue } totalBindings += len(candidates) // Check each candidate var constCandidates []*candidateInfo for i := range candidates { c := &candidates[i] if shouldReport(c, decl, &ctx, opts) { constCandidates = append(constCandidates, c) } } isDestructuring := varDecl.Name().Kind == ast.KindObjectBindingPattern || varDecl.Name().Kind == ast.KindArrayBindingPattern if isDestructuring && opts.destructuring == "all" { if len(constCandidates) != len(candidates) { continue } } if opts.destructuring == "all" { var filtered []*candidateInfo for _, c := range constCandidates { if c.reportNode != nil && !allDestructuringWriteTargetsConst(c.reportNode, &ctx) { continue } filtered = append(filtered, c) } constCandidates = filtered } totalConstBindings += len(constCandidates) allConstCandidates = append(allConstCandidates, constCandidates...) } canFix := allHaveInit && totalBindings > 0 && totalConstBindings == totalBindings if canFix { firstDecl := declList.Declarations.Nodes[0] for _, c := range allConstCandidates { if c.reportNode != nil { if isInUnfixableDestructuring(c.reportNode, firstDecl) { canFix = false break } } } } for _, c := range allConstCandidates { name := c.nameNode.Text() reportOn := c.nameNode if c.reportNode != nil { reportOn = c.reportNode } msg := rule.RuleMessage{ Id: "useConst", Description: "'" + name + "' is never reassigned. Use 'const' instead.", } if canFix { letRange := utils.GetVarKeywordRange(node, ctx.SourceFile) ctx.ReportNodeWithFixes(reportOn, msg, rule.RuleFixReplaceRange(letRange, "const")) } else { ctx.ReportNode(reportOn, msg) } } }, } }, }
Functions ¶
This section is empty.
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.