All files / src/rules prefer_inline.ts

94.96% Statements 264/278
82.6% Branches 95/115
100% Functions 12/12
94.96% Lines 264/278

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 2781x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14704x 14704x 14704x 14704x 14704x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 114515x 14704x 14704x 14120x 14120x 14704x 14704x 290x 290x 290x 14704x 14704x 264x 264x 14704x 14704x 387x 387x 20x 20x 367x 367x 387x   387x 80x 80x 287x 287x 387x 7x 7x 280x 280x 280x 387x 85x 85x 280x 280x 280x 14704x 14704x 14704x 14704x 85x 85x 85x 85x 88x 88x 88x 88x 51x 88x 1x 37x 2x 2x 34x 34x 88x 21x 21x 13x 13x 13x 88x   88x 2x 2x 11x 11x 88x     88x 88x   88x 2x 2x 9x 9x 9x 88x 88x 88x 88x 88x 5x 5x 4x 4x 88x 88x     4x 88x 4x 4x 4x 4x 4x 4x 4x 4x 4x 85x 85x 85x 14704x 14704x 14704x 14704x 13x 13x 13x     13x 13x 315x 13x 13x 315x       14704x 14704x 34x 34x 34x 93x 93x 2x 2x 93x 32x 32x 34x 77x 77x 65x 65x 12x 12x 12x 12x 77x 32x 32x 34x 72x 72x 56x 56x 16x 16x 16x 16x 72x 32x 34x 20x 34x 8x 12x 3x 3x 3x 4x 1x 1x     14704x 14704x 11x 25x 25x 25x 25x 20x 25x 5x 2x 2x 25x 9x 9x 9x 14704x 14704x 88x 88x 88x 45x 88x 43x 43x 88x 14704x 14704x 1236x 1236x 1236x 85x 85x 1151x 1151x 1236x 956x 956x 1151x 1151x 14704x 14704x
import * as Statements from "../abap/2_statements/statements";
import {BasicRuleConfig} from "./_basic_rule_config";
import {Issue} from "../issue";
import {IRegistry} from "../_iregistry";
import {IRuleMetadata, RuleTag, IRule} from "./_irule";
import {LanguageVersion, Release, releaseAtLeast} from "../version";
import {IObject} from "../objects/_iobject";
import {ABAPObject} from "../objects/_abap_object";
import {SyntaxLogic} from "../abap/5_syntax/syntax";
import {ISpaghettiScopeNode} from "../abap/5_syntax/_spaghetti_scope";
import {IdentifierMeta, TypedIdentifier} from "../abap/types/_typed_identifier";
import {ScopeType} from "../abap/5_syntax/_scope_type";
import {AbstractToken} from "../abap/1_lexer/tokens/abstract_token";
import {ReferenceType} from "../abap/5_syntax/_reference";
import {Identifier} from "../abap/4_file_information/_identifier";
import {EditHelper, IEdit} from "../edit_helper";
import {StatementNode} from "../abap/nodes";
 
interface IVariableReference {
  position: Identifier,
  resolved: Identifier
}
 
export class PreferInlineConf extends BasicRuleConfig {
 
}
 
export class PreferInline implements IRule {
  private reg: IRegistry;
  private conf = new PreferInlineConf();
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "prefer_inline",
      title: "Prefer Inline Declarations",
      shortDescription: `Prefer inline to up-front declarations.`,
      extendedInformation: `EXPERIMENTAL
 
Activates if language version is v740sp02 or above.
 
Variables must be local(METHOD or FORM).
 
No generic or void typed variables. No syntax errors.
 
First position used must be a full/pure write.
 
Move statment is not a cast(?=)
 
https://github.com/SAP/styleguides/blob/main/clean-abap/CleanABAP.md#prefer-inline-to-up-front-declarations`,
      tags: [RuleTag.Styleguide, RuleTag.Upport, RuleTag.Experimental, RuleTag.Quickfix],
      badExample: `DATA foo TYPE i.
foo = 2.
DATA percentage TYPE decfloat34.
percentage = ( comment_number / abs_statement_number ) * 100.`,
      goodExample: `DATA(foo) = 2.
DATA(percentage) = CONV decfloat34( comment_number / abs_statement_number ) * 100.`,
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public initialize(reg: IRegistry) {
    this.reg = reg;
    return this;
  }
 
  public setConfig(conf: PreferInlineConf): void {
    this.conf = conf;
  }
 
  public run(obj: IObject): readonly Issue[] {
 
    if (obj.getType() === "INTF") {
      return [];
    }
 
    if (!releaseAtLeast(this.reg.getConfig().getRelease(), Release.v740sp02)
        && this.reg.getConfig().getLanguageVersion() !== LanguageVersion.Cloud) {
      return [];
    } else if (!(obj instanceof ABAPObject)) {
      return [];
    }
 
    const run = new SyntaxLogic(this.reg, obj).run();
    if (run.issues.length > 0) {
      return [];
    }
    const scopes = this.findScopeCandidates(run.spaghetti.getTop());
 
    const ret: Issue[] = [];
    for (const s of scopes) {
      ret.push(...this.analyzeScope(s, obj));
    }
 
    return ret;
  }
 
///////////////////////////
 
  private analyzeScope(node: ISpaghettiScopeNode, obj: ABAPObject): Issue[] {
    const ret: Issue[] = [];
 
    const vars = node.getData().vars;
    for (const name in vars) {
      const identifier = vars[name];
      if (this.isLocalDefinition(node, identifier) === false
          || identifier.getMeta().includes(IdentifierMeta.InlineDefinition)
          || identifier.getMeta().includes(IdentifierMeta.FormParameter)) {
        continue;
      } else if (identifier.getType().isGeneric() === true) {
        continue;
      } else if (identifier.getType().containsVoid() === true) {
        continue;
      }
 
      const write = this.firstUseIsWrite(node, identifier);
      if (write === undefined) {
        continue;
      }
 
      // check that it is a pure write, eg not sub component assignment
      const next = this.findNextToken(write, obj);
      if (next === undefined) {
        continue;
      } else if (next?.getStart().equals(write.position.getEnd()) && next.getStr() !== "." && next.getStr() !== ",") {
        continue;
      }
      const file = obj.getABAPFileByName(identifier.getFilename());
      const writeStatement = EditHelper.findStatement(next, file);
      if (writeStatement === undefined) {
        continue;
      }
      const statementType = writeStatement?.get();
      if (statementType === undefined) {
        continue;
      } else if (this.statementHasGenericRead(node, writeStatement)) {
        continue;
      }
 
      // for now only allow some specific target statements, todo refactor
      if (!(statementType instanceof Statements.Move
          || statementType instanceof Statements.Catch
          || statementType instanceof Statements.ReadTable
          || statementType instanceof Statements.Loop)
          || writeStatement?.concatTokens()?.includes("?=")
          || writeStatement?.concatTokens()?.includes(" #(")) {
        continue;
      }
 
      const statement = EditHelper.findStatement(identifier.getToken(), file);
      const concat = statement?.concatTokens().toUpperCase();
      if (concat?.includes("BEGIN OF")) {
        continue;
      }
      let fix: IEdit | undefined = undefined;
      if (file && statement) {
        const fix1 = EditHelper.deleteStatement(file, statement);
        const name = identifier.getName();
        const replace = name.startsWith("<") ? "FIELD-SYMBOL(" + name + ")" : "DATA(" + name + ")";
        const fix2 = EditHelper.replaceRange(file, write.position.getStart(), write.position.getEnd(), replace);
        fix = EditHelper.merge(fix1, fix2);
      }
      const message = this.getMetadata().title + ", " + name;
      ret.push(Issue.atIdentifier(identifier, message, this.getMetadata().key, this.conf.severity, fix));
    }
 
    return ret;
  }
 
////////////////////////
 
  private findNextToken(ref: IVariableReference, obj: ABAPObject): AbstractToken | undefined {
 
    const file = obj.getABAPFileByName(ref.resolved.getFilename());
    if (file === undefined) {
      return undefined;
    }
 
    for (const t of file.getTokens()) {
      if (t.getStart().isAfter(ref.position.getEnd())) {
        return t;
      }
    }

    return undefined;
  }
 
  private firstUseIsWrite(node: ISpaghettiScopeNode, identifier: TypedIdentifier): IVariableReference | undefined {
// assumption: variables are local, so only the current scope must be searched
 
    for (const r of node.getData().references) {
      if (r.referenceType === ReferenceType.TypeReference
          && r.resolved?.getStart().equals(identifier.getStart()) === true) {
        return undefined;
      }
    }
 
    let firstRead: IVariableReference | undefined = undefined;
    for (const r of node.getData().references) {
      if (r.referenceType !== ReferenceType.DataReadReference
          || r.resolved?.getStart().equals(identifier.getStart()) === false) {
        continue;
      }
      if (r.resolved) {
        firstRead = {position: r.position, resolved: r.resolved};
        break;
      }
    }
 
    let firstWrite: IVariableReference | undefined = undefined;
    for (const w of node.getData().references) {
      if (w.referenceType !== ReferenceType.DataWriteReference
          || w.resolved?.getStart().equals(identifier.getStart()) === false) {
        continue;
      }
      if (w.resolved) {
        firstWrite = {position: w.position, resolved: w.resolved};
        break;
      }
    }
 
    if (firstRead === undefined) {
      return firstWrite;
    } else if (firstWrite === undefined) {
      return undefined;
    } else if (firstWrite.position.getStart().getRow() === firstRead.position.getStart().getRow()) {
// if the same statement both reads and write the same variable
// note that currently just the line number is compared, this is not correct, it should check if its the same statement
      return undefined;
    } else if (firstWrite.position.getStart().isBefore(firstRead.position.getStart())) {
      return firstWrite;
    }
    return undefined;
  }
 
  private statementHasGenericRead(node: ISpaghettiScopeNode, statement: StatementNode): boolean {
    for (const ref of node.getData().references) {
      if (ref.referenceType !== ReferenceType.DataReadReference
          || ref.resolved === undefined
          || statement.includesToken(ref.position.getToken()) === false
          || !(ref.resolved instanceof TypedIdentifier)) {
        continue;
      } else if (ref.resolved.getType().isGeneric() === true
          || ref.resolved.getType().containsVoid() === true) {
        return true;
      }
    }
 
    return false;
  }
 
  private isLocalDefinition(node: ISpaghettiScopeNode, identifier: TypedIdentifier): boolean {
    const {start, end} = node.calcCoverage();
 
    if (identifier.getStart().isAfter(start) && identifier.getStart().isBefore(end)) {
      return true;
    } else {
      return false;
    }
  }
 
  private findScopeCandidates(node: ISpaghettiScopeNode): ISpaghettiScopeNode[] {
 
    if (node.getIdentifier().stype === ScopeType.Form
        || node.getIdentifier().stype === ScopeType.Method) {
      return [node];
    }
 
    let ret: ISpaghettiScopeNode[] = [];
    for (const c of node.getChildren()) {
      ret = ret.concat(this.findScopeCandidates(c));
    }
    return ret;
  }
 
}