All files / src/rules redundant_conversion.ts

84.01% Statements 268/319
77.77% Branches 91/117
91.66% Functions 11/12
84.01% Lines 268/319

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 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 3201x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14683x 14683x 14683x 14683x 14683x 14683x 14683x 14683x 14683x 14683x 14683x 14683x 14683x 14683x 14683x 100419x 100419x 100419x 100419x 100419x 100419x 100419x 100419x 100419x 100419x 100419x 100419x 100419x 14683x 14683x 14120x 14120x 14683x 14683x 264x 264x 14683x 14683x 310x 310x 310x 14683x 14683x 407x 407x     407x 407x 80x 80x 327x 327x 407x 8x 8x 319x 319x 407x 329x 329x 12x 12x 317x 317x 329x 176x 138x 138x 38x 38x 38x 176x 176x 176x     38x 38x 176x     38x 38x 140x 176x 176x 176x 176x     176x 176x 176x 176x 8x 8x 30x 30x 30x 176x     30x 176x 176x 176x 176x 176x 176x 176x 176x 176x 176x 176x 176x 176x 176x 176x 176x 176x 317x 319x 319x 319x 14683x 14683x 38x 38x 38x 38x 38x 38x 38x 33x 33x 5x 5x 38x     5x 38x 38x     5x 7x 38x 38x 38x 38x 38x 14683x 14683x 38x 38x 38x 38x 38x 38x 38x 38x 2x 38x 1x 1x 37x 38x 44x 2x 44x 21x 21x     21x 13x     13x 13x 2x 2x 21x   8x 2x 8x   6x 5x 5x 5x 6x 1x 1x 44x 29x 38x     29x 29x 14683x 14683x 14683x 14683x 13x 13x     13x 13x     13x 26x 13x 13x 1x 1x 12x 12x 13x 6x 6x 5x 5x 1x 1x 14683x 14683x 21x 58x 21x 21x     21x 21x 21x 25x 25x 23x 25x 2x     2x     2x 2x         25x 21x 21x 14683x 14683x                   14683x 14683x 34x 34x 34x 34x 34x 34x     34x 34x 4x 4x 30x 34x         30x 30x 30x 14683x  
import * as Expressions from "../abap/2_statements/expressions";
import * as Statements from "../abap/2_statements/statements";
import {ABAPFile} from "../abap/abap_file";
import {ReferenceType} from "../abap/5_syntax/_reference";
import {ISpaghettiScopeNode} from "../abap/5_syntax/_spaghetti_scope";
import {Constant as ConstantSyntax} from "../abap/5_syntax/expressions/constant";
import {SyntaxLogic} from "../abap/5_syntax/syntax";
import {ExpressionNode} from "../abap/nodes";
import {TypedIdentifier} from "../abap/types/_typed_identifier";
import {AbstractType} from "../abap/types/basic/_abstract_type";
import {FloatType, HexType, IntegerType, StringType, StructureType, TableType, UnknownType, VoidType} from "../abap/types/basic";
import {Issue} from "../issue";
import {ABAPObject} from "../objects/_abap_object";
import {IObject} from "../objects/_iobject";
import {BasicRuleConfig} from "./_basic_rule_config";
import {IRule, IRuleMetadata, RuleTag} from "./_irule";
import {IRegistry} from "../_iregistry";
import {EditHelper} from "../edit_helper";
import {Release, releaseAtLeast} from "../version";
 
export class RedundantConversionConf extends BasicRuleConfig {
}
 
export class RedundantConversion implements IRule {
  private reg: IRegistry;
  private conf = new RedundantConversionConf();
 
  // built-in functions that always return a string, whatever their arguments
  private static readonly stringResult = new Set([
    "BOOLC", "CONCAT_LINES_OF", "CONDENSE", "ESCAPE", "FROM_MIXED", "INSERT", "REPEAT", "REPLACE",
    "REVERSE", "SEGMENT", "SHIFT_LEFT", "SHIFT_RIGHT", "SUBSTRING", "SUBSTRING_AFTER", "SUBSTRING_BEFORE",
    "SUBSTRING_FROM", "SUBSTRING_TO", "TO_LOWER", "TO_MIXED", "TO_UPPER", "TRANSLATE"]);
  // built-in functions that always return an i
  private static readonly integerResult = new Set([
    "CHARLEN", "COUNT", "COUNT_ANY_NOT_OF", "COUNT_ANY_OF", "DBMAXLEN", "DISTANCE", "FIND", "FIND_ANY_NOT_OF",
    "FIND_ANY_OF", "FIND_END", "LINES", "NUMOFCHAR", "STRLEN", "XSTRLEN"]);
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "redundant_conversion",
      title: "Redundant Conversion",
      shortDescription: `Find redundant CONV expressions`,
      extendedInformation: `Reports CONV expressions whose operand already has the conversion's target type,
including the result of a built-in function with a fixed result type, like to_upper( ) or strlen( ).`,
      tags: [RuleTag.Quickfix],
      badExample: `DATA text TYPE string.
text = CONV string( text ).`,
      goodExample: `DATA text TYPE string.
text = text.`,
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public setConfig(conf: RedundantConversionConf) {
    this.conf = conf;
  }
 
  public initialize(reg: IRegistry) {
    this.reg = reg;
    return this;
  }
 
  public run(obj: IObject): readonly Issue[] {
    if (!releaseAtLeast(this.reg.getConfig().getRelease(), Release.v740sp02)
        && !this.reg.getConfig().isOpenABAP()) {
      return [];
    }
 
    if (!(obj instanceof ABAPObject)) {
      return [];
    }
 
    const syntax = new SyntaxLogic(this.reg, obj).run();
    if (syntax.issues.length > 0) {
      return [];
    }
 
    const issues: Issue[] = [];
    for (const file of obj.getABAPFiles()) {
      const structure = file.getStructure();
      if (structure === undefined) {
        continue;
      }
 
      // recursive, a CONV can be the argument of a built-in function, which is itself a Source
      for (const source of structure.findAllExpressionsRecursive(Expressions.Source)) {
        if (source.getFirstToken().getStr().toUpperCase() !== "CONV") {
          continue;
        }
 
        const typeExpression = source.findDirectExpression(Expressions.TypeNameOrInfer);
        const bodySource = source.findDirectExpression(Expressions.ConvBody)
          ?.findDirectExpression(Expressions.Source);
        if (typeExpression === undefined
            || bodySource === undefined) {
          continue;
        }
 
        const scope = syntax.spaghetti.lookupPosition(source.getFirstToken().getStart(), file.getFilename());
        if (scope === undefined) {
          continue;
        }
 
        const target = scope.getData().references.find(reference =>
          reference.referenceType === ReferenceType.InferredType
          && reference.position.getStart().equals(typeExpression.getFirstToken().getStart()))?.resolved;
        const operandType = this.sourceType(bodySource, scope);
 
        if (!(target instanceof TypedIdentifier)) {
          continue;
        }
        const operandHasSameType = operandType !== undefined && this.sameType(target.getType(), operandType);
        const arithmeticHasSameContext = this.arithmeticUsesSameTargetType(
          source, bodySource, file, scope, target.getType());
        if (operandHasSameType === false && arithmeticHasSameContext === false) {
          continue;
        }
 
        const closingParen = source.getDirectTokens().find(token =>
          token.getStr() === ")" && token.getStart().isAfter(bodySource.getLastToken().getStart()));
        if (closingParen === undefined) {
          continue;
        }
        const preserveParentheses = bodySource.findDirectExpression(Expressions.ArithOperator) !== undefined
          || bodySource.findDirectTokenByText("&&") !== undefined;
        // Apply the later edit first so the original positions remain valid when
        // both parts of the CONV wrapper are changed on the same line.
        const fix = EditHelper.merge(
          EditHelper.replaceRange(
            file, bodySource.getLastToken().getEnd(), closingParen.getEnd(), preserveParentheses ? ")" : ""),
          EditHelper.replaceRange(
            file, source.getFirstToken().getStart(), bodySource.getFirstToken().getStart(), preserveParentheses ? "(" : ""));
        issues.push(Issue.atRange(
          file,
          source.getFirstToken().getStart(),
          closingParen.getEnd(),
          "Redundant CONV expression",
          this.getMetadata().key,
          this.conf.severity,
          fix));
      }
    }
 
    return issues;
  }
 
  private arithmeticUsesSameTargetType(
    conversion: ExpressionNode,
    bodySource: ExpressionNode,
    file: ABAPFile,
    scope: ISpaghettiScopeNode,
    conversionType: AbstractType): boolean {
 
    if (bodySource.findDirectExpression(Expressions.ArithOperator) === undefined) {
      return false;
    }
 
    const statement = file.getStatements().find(candidate => candidate.includesToken(conversion.getFirstToken()));
    if (!(statement?.get() instanceof Statements.Move)) {
      return false;
    }
 
    const targetToken = statement.findDirectExpression(Expressions.Target)?.getFirstToken();
    if (targetToken === undefined) {
      return false;
    }
    const assignmentTarget = scope.getData().references.find(reference =>
      reference.referenceType === ReferenceType.DataWriteReference
      && reference.position.getStart().equals(targetToken.getStart()))?.resolved;
 
    return assignmentTarget instanceof TypedIdentifier
      && this.sameType(conversionType, assignmentTarget.getType());
  }
 
  private sourceType(source: ExpressionNode, scope: ISpaghettiScopeNode): AbstractType | undefined {
    let context: AbstractType | undefined;
 
    // boolc( <condition> ) is not a MethodCallChain, xsdbool( ) has the same shape but is not reported
    const first = source.getFirstToken();
    if (first.getStr().toUpperCase() === "BOOLC"
        && source.findDirectExpression(Expressions.Cond) !== undefined
        && source.getChildren().length === 4
        && scope.getData().references.some(reference =>
          reference.referenceType === ReferenceType.BuiltinMethodReference
          && reference.position.getStart().equals(first.getStart()))) {
      return StringType.get();
    }
 
    for (const child of source.getChildren()) {
      if (!(child instanceof ExpressionNode)) {
        continue;
      } else if (child.get() instanceof Expressions.FieldChain) {
        context = this.fieldChainType(child, scope);
        if (context === undefined) {
          return undefined;
        }
      } else if (child.get() instanceof Expressions.MethodCallChain) {
        if (source.getChildren().length !== 1) {
          return undefined;
        }
        context = this.builtinResultType(child, scope);
        if (context === undefined) {
          return undefined;
        }
      } else if (child.get() instanceof Expressions.Constant) {
        context = this.infer(context, ConstantSyntax.runSyntax(child));
      } else if (child.get() instanceof Expressions.StringTemplate) {
        context = StringType.get();
      } else if (child.get() instanceof Expressions.Source) {
        context = this.infer(context, this.sourceType(child, scope));
      } else if (child.get() instanceof Expressions.ArithOperator) {
        // the CONV sets the calculation type of arithmetic expressions, only redundant
        // if the assignment target has the same type, see arithmeticUsesSameTargetType
        return undefined;
      } else {
        return undefined;
      }
    }
 
    if (source.findDirectTokenByText("&&")) {
      return StringType.get();
    }
    return context;
  }
 
  /** The result type of a call to a built-in function whose result type does not depend on its arguments,
   *  undefined for anything else, e.g. abs( ) or xsdbool( ), or a method of the same name */
  private builtinResultType(chain: ExpressionNode, scope: ISpaghettiScopeNode): AbstractType | undefined {
    const children = chain.getChildren();
    if (children.length !== 1 || !(children[0].get() instanceof Expressions.MethodCall)) {
      return undefined;
    }
    const name = (children[0] as ExpressionNode).findDirectExpression(Expressions.MethodName)?.getFirstToken();
    if (name === undefined) {
      return undefined;
    }
    const isBuiltin = scope.getData().references.some(reference =>
      reference.referenceType === ReferenceType.BuiltinMethodReference
      && reference.position.getStart().equals(name.getStart()));
    if (isBuiltin === false) {
      return undefined;
    }
 
    const upper = name.getStr().toUpperCase();
    if (RedundantConversion.stringResult.has(upper)) {
      return StringType.get();
    } else if (RedundantConversion.integerResult.has(upper)) {
      return IntegerType.get();
    }
    return undefined;
  }
 
  private fieldChainType(fieldChain: ExpressionNode, scope: ISpaghettiScopeNode): AbstractType | undefined {
    const operand = scope.getData().references.find(reference =>
      reference.referenceType === ReferenceType.DataReadReference
      && reference.position.getStart().equals(fieldChain.getFirstToken().getStart()))?.resolved;
    if (!(operand instanceof TypedIdentifier)) {
      return undefined;
    }
 
    let type: AbstractType | undefined = operand.getType();
    for (const child of fieldChain.getChildren()) {
      if (!(child instanceof ExpressionNode)
          || child.get() instanceof Expressions.SourceField) {
        continue;
      } else if (child.get() instanceof Expressions.ComponentName) {
        if (type instanceof TableType) {
          type = type.getRowType();
        }
        if (!(type instanceof StructureType)) {
          return undefined;
        }
        type = type.getComponentByName(child.concatTokens());
      } else {
        // Offsets, table expressions, attributes, and dereferences need more
        // context than the initial data reference provides.
        return undefined;
      }
    }
    return type;
  }
 
  private infer(context: AbstractType | undefined, found: AbstractType | undefined): AbstractType | undefined {
    if (context instanceof FloatType && found instanceof IntegerType) {
      return context;
    } else if (context instanceof IntegerType && found instanceof HexType) {
      return context;
    } else if ((context instanceof IntegerType || context instanceof FloatType) && found?.isGeneric()) {
      return context;
    }
    return found;
  }
 
  private sameType(first: AbstractType, second: AbstractType): boolean {
    if (first instanceof UnknownType
        || second instanceof UnknownType
        || first instanceof VoidType
        || second instanceof VoidType
        || first.isGeneric()
        || second.isGeneric()) {
      return false;
    }
 
    if (first.constructor !== second.constructor) {
      return false;
    }
 
    if (first instanceof StructureType || first instanceof TableType) {
      const firstName = first.getQualifiedName()?.toUpperCase();
      const secondName = second.getQualifiedName()?.toUpperCase();
      return firstName !== undefined && firstName === secondName;
    }
 
    return first.toABAP() === second.toABAP();
  }
}