All files / src/rules keyword_case.ts

92.54% Statements 273/295
87.96% Branches 95/108
100% Functions 11/11
92.54% Lines 273/295

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 2951x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 23064x 23064x 23064x 23064x 23064x 23064x 23064x 23064x 23064x 23064x 23064x 23064x 23064x 23064x 23064x 1x 1x 1x 1x 1x 1x 1x 1x 359x 359x 1x 1x 1575x 1575x 1575x 1575x 1575x 1575x 1575x 31x 31x 1544x 1575x 35x 35x 1x 1x 35x 1x 1x 35x 4x 4x 35x 29x 12x 12x 35x 1526x 1575x 7x 7x 2x 2x 7x 2x 2x 5x 1x 1x 7x 1521x 1575x 2x 2x 1x 1x 1x     1x     2x 1520x 1520x 1520x 1x 1x 1x 1x 11548x 11548x 11548x 11548x 34470x 34470x 34470x 34470x 34470x 34470x 34470x 34470x 34470x 34470x 11548x 11548x 11724x 11724x 11548x 11548x 275x 275x 1x 1x 275x 1x 1x 275x     275x 11548x 11548x 364x 364x 364x 364x 364x 53x 53x 5x 5x 53x 359x 359x 364x     359x 359x 359x 364x 1575x 55x 55x 1520x 1520x 1575x 55x 8x 8x 55x 7x 7x 7x 47x 47x 55x     47x 47x 1512x 1575x     1575x 359x 359x 359x 11548x 11548x 11548x 11548x 47x 47x 47x 47x 47x 47x 47x 36x 47x 11x 11x 47x 47x 47x 63x 63x 63x 48x 23x 48x 25x 25x 63x 15x 15x 63x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 11548x 11548x 11548x 4883x 4883x 4883x 4883x 10340x 10340x 10340x 1751x 1751x 1751x 1751x 121x 121x 1630x 1630x 1630x 1751x     1630x 1751x 4x 4x 1626x 1626x 1751x   1751x     1751x 18x 18x 10340x 5226x 5226x 74x 74x 8589x 3363x 3363x     10340x 4883x 4883x 4883x 11548x 11548x 5315x 10x 10x 5315x 272x 5315x 5033x 5033x       11548x 11548x
import {Issue} from "../issue";
import {ABAPRule} from "./_abap_rule";
import {StatementNode, ExpressionNode, TokenNode, TokenNodeRegex} from "../abap/nodes";
import {Unknown, Comment, MacroContent, MacroCall, IStatement, NativeSQL} from "../abap/2_statements/statements/_statement";
import {Identifier} from "../abap/1_lexer/tokens";
import {IObject} from "../objects/_iobject";
import {Class} from "../objects";
import {BasicRuleConfig} from "./_basic_rule_config";
import * as Statements from "../abap/2_statements/statements";
import * as Expressions from "../abap/2_statements/expressions";
import {AbstractToken} from "../abap/1_lexer/tokens/abstract_token";
import {IRuleMetadata, RuleTag} from "./_irule";
import {DDIC} from "../ddic";
import {VirtualPosition} from "../virtual_position";
import {ABAPFile} from "../abap/abap_file";
import {EditDraft} from "../edit_helper";
import {IFile} from "../files/_ifile";
 
export enum KeywordCaseStyle {
  Upper = "upper",
  Lower = "lower",
}
 
export class KeywordCaseConf extends BasicRuleConfig {
  public style: KeywordCaseStyle = KeywordCaseStyle.Upper;
  /** Ignore global exception classes */
  public ignoreExceptions: boolean = true;
  public ignoreLowerClassImplmentationStatement: boolean = true;
  public ignoreGlobalClassDefinition: boolean = false;
  public ignoreGlobalInterface: boolean = false;
  public ignoreFunctionModuleName: boolean = false;
  // this ignores keywords in CLASS/ENDCLASS statements of a global class (and only in them, the rest is checked)
  public ignoreGlobalClassBoundaries: boolean = false;
 
  /** A list of keywords to be ignored */
  public ignoreKeywords?: string[] = [];
  public maxIssuesPerFile: number | undefined = 10;
}
 
class Skip {
  private readonly conf: KeywordCaseConf;
  private skip = false;
  private isGlobalClass = false;
  private isGlobalIf = false;
 
  public constructor(conf: KeywordCaseConf) {
    this.conf = conf;
  }
 
  public skipStatement(statement: StatementNode): boolean {
    const get = statement.get();
    if (get instanceof Unknown
      || get instanceof NativeSQL
      || get instanceof MacroContent
      || get instanceof MacroCall
      || statement.getFirstToken().getStart() instanceof VirtualPosition
      || get instanceof Comment) {
      return true;
    }
 
    if (this.conf.ignoreGlobalClassBoundaries) {
      const node = get;
      if (node instanceof Statements.Interface && statement.findFirstExpression(Expressions.ClassGlobal)) {
        this.isGlobalIf = true;
        return true;
      } else if (this.isGlobalIf === true && node instanceof Statements.EndInterface) {
        return true;
      }
      if (node instanceof Statements.ClassDefinition && statement.findFirstExpression(Expressions.ClassGlobal)) {
        this.isGlobalClass = true;
        return true;
      } else if (this.isGlobalClass === true
        && (node instanceof Statements.EndClass || node instanceof Statements.ClassImplementation)) {
        return true;
      }
    }
 
    if (this.conf.ignoreGlobalClassDefinition) {
      if (get instanceof Statements.ClassDefinition
        && statement.findFirstExpression(Expressions.ClassGlobal)) {
        this.skip = true;
        return true;
      } else if (this.skip === true && get instanceof Statements.EndClass) {
        this.skip = false;
        return true;
      } else if (this.skip === true) {
        return true;
      }
    }
 
    if (this.conf.ignoreGlobalInterface) {
      if (get instanceof Statements.Interface
        && statement.findFirstExpression(Expressions.ClassGlobal)) {
        this.skip = true;
        return true;
      } else if (this.skip === true && get instanceof Statements.EndInterface) {
        this.skip = false;
        return true;
      } else if (this.skip === true) {
        return true;
      }
    }
 
    return false;
  }
}
 
type TokenAndKeyword = {token: AbstractToken, keyword: boolean};
 
export class KeywordCase extends ABAPRule {
  private conf = new KeywordCaseConf();
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "keyword_case",
      title: "Keyword case",
      shortDescription: `Checks that keywords have the same case. Non-keywords must be lower case.`,
      extendedInformation: `https://github.com/SAP/styleguides/blob/main/clean-abap/CleanABAP.md#use-your-pretty-printer-team-settings`,
      tags: [RuleTag.Styleguide, RuleTag.SingleFile, RuleTag.Quickfix],
      badExample: `write 'hello world'.`,
      goodExample: `WRITE 'hello world'.`,
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public setConfig(conf: KeywordCaseConf) {
    this.conf = conf;
    if (this.conf === undefined) {
      this.conf = new KeywordCaseConf();
    }
    if (this.conf.style === undefined) {
      this.conf = new KeywordCaseConf();
    }
    if (this.conf.ignoreExceptions === undefined) {
      this.conf.ignoreExceptions = new KeywordCaseConf().ignoreExceptions;
    }
  }
 
  public runParsed(file: ABAPFile, obj: IObject) {
    const issues: Issue[] = [];
    const ddic = new DDIC(this.reg);
    const MAX_ISSUES = 100;
 
    if (this.conf.ignoreExceptions && obj instanceof Class) {
      const definition = obj.getClassDefinition();
      if (definition === undefined || ddic.isException(definition, obj)) {
        return [];
      }
    }
 
    let max = this.getConfig().maxIssuesPerFile;
    if (max === undefined || max < 1) {
      max = 10;
    }
 
    const skip = new Skip(this.getConfig());
    let prev: AbstractToken | undefined = undefined;
    for (const statement of file.getStatements()) {
      if (skip.skipStatement(statement) === true) {
        continue;
      }
 
      let result = this.traverse(statement, statement.get());
      if (result.length > 0) {
        if (prev && result[0].token.getStart().equals(prev.getStart())) {
          continue;
        }
        if (statement.getColon() !== undefined) {
          // if its a chained statement, go token by token
          result = [result[0]];
        }
        const issue = this.build(result, file);
        issues.push(issue);
        if (issues.length > MAX_ISSUES) {
          break;
        }
        prev = result[0].token;
      }
 
      if (issues.length >= max) {
        break;
      }
    }
 
    return issues;
  }
 
//////////////////
 
  private build(tokens: TokenAndKeyword[], file: IFile): Issue {
    const first = tokens[0];
    const firstToken = tokens[0].token;
    const lastToken = tokens[tokens.length - 1].token;
    const firstTokenValue = firstToken.getStr();
 
    let description = "";
    if (first.keyword === true) {
      description = `Keyword should be ${this.conf.style} case: "${firstTokenValue}"`;
    } else {
      description = `Identifiers should be lower case: "${firstTokenValue}"`;
    }
 
    const draft = new EditDraft(file);
    for (const token of tokens) {
      const str = token.token.getStr();
      const pos = token.token.getStart();
      if (token.keyword === true) {
        if (this.conf.style === KeywordCaseStyle.Lower) {
          draft.replace(pos, str.toLowerCase());
        } else {
          draft.replace(pos, str.toUpperCase());
        }
      } else {
        draft.replace(pos, str.toLowerCase());
      }
    }
    const fix = draft.toEdit();
 
    return Issue.atRange(
      file,
      firstToken.getStart(),
      lastToken.getEnd(),
      description,
      this.getMetadata().key,
      this.conf.severity,
      fix);
  }
 
  /** returns a list of tokens which violates the keyword_case rule */
  private traverse(s: StatementNode | ExpressionNode, parent: IStatement): TokenAndKeyword[] {
    let ret: TokenAndKeyword[] = [];
 
    const children = s.getChildren();
    for (let i = 0; i < children.length; i++) {
      const child = children[i];
 
      if (child instanceof TokenNodeRegex) {
        const next = children[i + 1];
 
        if (this.conf.ignoreLowerClassImplmentationStatement
          && parent instanceof Statements.ClassImplementation) {
          continue;
        }
        const str = child.get().getStr();
        const upper = str.toUpperCase();
        // todo, this is a hack, the parser should recongize OTHERS/TEXT as a keyword
        if (upper === "OTHERS" || (upper === "TEXT" && next?.concatTokens() === "-")) {
          continue;
        }
        if (this.conf.ignoreFunctionModuleName === true
          && parent instanceof Statements.FunctionModule && upper !== "FUNCTION") {
          continue;
        }
        // todo, this is a hack, the parser should recigize SCREEN as a keyword
        if (upper === "SCREEN"
            && (parent instanceof Statements.ModifyDatabase
              || parent instanceof Statements.ModifyInternal
              || parent instanceof Statements.Loop)) {
          continue;
        }
        if (str !== str.toLowerCase() && child.get() instanceof Identifier) {
          ret.push({token: child.get(), keyword: false});
        }
      } else if (child instanceof TokenNode) {
        const str = child.get().getStr();
        if (this.violatesRule(str) && child.get() instanceof Identifier) {
          ret.push({token: child.get(), keyword: true});
        }
      } else if (child instanceof ExpressionNode) {
        ret = ret.concat(this.traverse(child, parent));
      } else {
        throw new Error("keyword_case, traverseStatement, unexpected node type");
      }
    }
 
    return ret;
  }
 
  public violatesRule(keyword: string): boolean {
    if (this.conf.ignoreKeywords && this.conf.ignoreKeywords.map(k => {return k.toUpperCase();}).includes(keyword.toUpperCase())) {
      return false;
    }
    if (this.conf.style === KeywordCaseStyle.Lower) {
      return keyword !== keyword.toLowerCase();
    } else if (this.conf.style === KeywordCaseStyle.Upper) {
      return keyword !== keyword.toUpperCase();
    }

    return false;
  }
 
}