All files / src/rules redundant_conversion.ts

92.12% Statements 316/343
81.69% Branches 116/142
100% Functions 12/12
92.12% Lines 316/343

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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 3441x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 42221x 42221x 42221x 42221x 42221x 1x 21123x 21123x 21123x 21123x 21123x 21123x 21123x 21123x 21123x 21123x 21123x 21123x 21123x 21123x 21123x 164152x 164152x 164152x 164152x 164152x 164152x 164152x 164152x 164152x 164152x 164152x 164152x 164152x 164152x 164152x 164152x 164152x 164152x 21123x 21123x 20205x 20205x 21123x 21123x 375x 375x 21123x 21123x 465x 465x 465x 21123x 21123x 675x 675x     675x 675x 208x 208x 467x 467x 675x 9x 9x 458x 458x 675x 468x 468x 13x 13x 455x 455x 455x 455x 468x 432x 111x 111x 432x 455x 455x 468x 432x 347x 347x 85x 85x 85x 432x 432x 432x     85x 85x 432x     85x 85x 85x 85x 432x     432x 432x 432x 432x 432x 432x 432x 432x 31x 31x 54x 54x 54x 432x     54x 54x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 455x 458x 458x 458x 21123x 21123x 85x 85x 85x 85x 85x 85x 85x 75x 75x 10x 10x 85x     10x 85x 85x     10x 10x 10x 85x 85x 21123x 21123x 21123x 82x 82x 82x 82x 82x 82x 82x 1x 1x 81x 81x 81x 81x 82x 82x 3x 3x 78x 78x 78x 82x 82x 82x 82x 82x 82x 82x 82x 19x 19x 59x 59x 59x 59x 59x 248x 248x 248x 248x 194x 194x 54x 248x 59x 82x 4x 4x 55x 55x 82x 82x 21123x 21123x 85x 85x 85x 85x 85x 85x 85x 85x 2x 85x 1x 1x 84x 85x 97x 2x 97x 58x 58x 1x 1x 95x 16x     16x 16x 5x 5x 37x 5x 21x 2x 16x   14x 10x 10x 10x 14x 4x 4x 97x 64x 85x     64x 64x 21123x 21123x 21123x 21123x 16x 16x     16x 16x     16x 62x 16x 16x 4x 4x 12x 12x 16x 6x 6x 5x 5x 1x 1x 21123x 21123x 5x   5x   5x     5x 5x 21123x  
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 {DataReference, EnumType, FloatType, HexType, IntegerType, StringType} 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";
import {chainType, typedIdentifierAt} from "./_type_lookup";
import {identicalTypes} from "./_procedure_analysis";
 
export class RedundantConversionConf extends BasicRuleConfig {
  /** Also report a CONV that is the whole right-hand side of an assignment whose target already has the
   *  conversion type, e.g. "count = CONV i( text )." with count TYPE i, the assignment converts by itself */
  public assignmentTarget: boolean = true;
}
 
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( ).
 
With option assignmentTarget, also reports a CONV that is the whole right-hand side of an assignment
whose target already has the conversion's type, "count = CONV i( text )." with count TYPE i, the
assignment converts by itself. Not reported for inline declarations, enumerated types, LET, and operands
with a generic type.`,
      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;
      }
 
      const sources = structure.findAllExpressionsRecursive(Expressions.Source);
      // Sources that are an operand of an enclosing Source, e.g. "2 * CONV i( a + b )" or "- CONV i( a + b )"
      const operands = new Set<ExpressionNode>();
      for (const source of sources) {
        if (source.getChildren().length > 1) {
          source.findDirectExpressions(Expressions.Source).forEach(operand => operands.add(operand));
        }
      }
 
      // recursive, a CONV can be the argument of a built-in function, which is itself a Source
      for (const source of sources) {
        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 = typedIdentifierAt(scope, typeExpression.getFirstToken().getStart(), [ReferenceType.InferredType]);
        const operandType = this.sourceType(bodySource, scope);
 
        if (!(target instanceof TypedIdentifier)) {
          continue;
        }
        const operandHasSameType = operandType !== undefined && identicalTypes(target.getType(), operandType);
        const arithmeticHasSameContext = this.arithmeticUsesSameTargetType(
          source, bodySource, file, scope, target.getType());
        const assignmentHasSameType = this.conf.assignmentTarget !== false
          && this.assignmentTargetHasSameType(source, file, scope, target.getType());
        if (operandHasSameType === false
            && arithmeticHasSameContext === false
            && assignmentHasSameType === false) {
          continue;
        }
 
        const closingParen = source.getDirectTokens().find(token =>
          token.getStr() === ")" && token.getStart().isAfter(bodySource.getLastToken().getStart()));
        if (closingParen === undefined) {
          continue;
        }
        // parentheses are only needed when the CONV takes part in a surrounding operation,
        // "CONV type ( body )" alone has 5 children, more means a trailing operator
        const partOfOperation = source.getChildren().length !== 5 || operands.has(source);
        const preserveParentheses = partOfOperation
          && (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 = typedIdentifierAt(scope, targetToken.getStart(), [ReferenceType.DataWriteReference]);
 
    return assignmentTarget instanceof TypedIdentifier
      && identicalTypes(conversionType, assignmentTarget.getType());
  }
 
  /** "target = CONV i( text )." where target has the conversion type, the assignment converts the same way */
  private assignmentTargetHasSameType(
    conversion: ExpressionNode,
    file: ABAPFile,
    scope: ISpaghettiScopeNode,
    conversionType: AbstractType): boolean {
 
    // CONV converts the base type to an enumerated type, a plain assignment does not compile
    if (conversionType instanceof EnumType) {
      return false;
    }
 
    const body = conversion.findDirectExpression(Expressions.ConvBody);
    if (body === undefined
        || body.findDirectExpression(Expressions.Let) !== undefined
        // "CONV type ( body )" without a trailing operator
        || conversion.getChildren().length !== 5) {
      return false;
    }
 
    // "target = CONV ...", not "+=", "?=", "a = b = CONV ..." or MOVE
    const statement = file.getStatements().find(candidate => candidate.includesToken(conversion.getFirstToken()));
    const children = statement?.getChildren() ?? [];
    const target = children[0];
    if (!(statement?.get() instanceof Statements.Move)
        || children.length !== 4
        || !(target instanceof ExpressionNode)
        || !(target.get() instanceof Expressions.Target)
        || children[1].concatTokens() !== "="
        || children[2] !== conversion) {
      return false;
    }
 
    // a generic operand gets its type from the CONV, also "ref->*" with ref TYPE REF TO data
    const bodyStart = body.getFirstToken().getStart();
    const bodyEnd = body.getLastToken().getEnd();
    const genericOperand = scope.getData().references.some(reference => {
      if (reference.referenceType !== ReferenceType.DataReadReference
          || reference.position.getFilename() !== file.getFilename()
          || reference.position.getStart().isBetween(bodyStart, bodyEnd) === false
          || !(reference.resolved instanceof TypedIdentifier)) {
        return false;
      }
      const type = reference.resolved.getType();
      return type.isGeneric() || (type instanceof DataReference && type.getType().isGeneric());
    });
    if (genericOperand === true) {
      return false;
    }
 
    const targetType = chainType(target.getChildren(), scope);
    return targetType !== undefined && identicalTypes(conversionType, targetType);
  }
 
  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 = chainType(child.getChildren(), 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 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;
  }
}