All files / src/abap/types method_parameters.ts

91.6% Statements 371/405
84.67% Branches 116/137
89.47% Functions 17/19
91.6% Lines 371/405

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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 4061x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21602x     21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 21602x 1x 1x     1x 1x 2203x 2203x 1x 1x 64867x 64867x 64867x 28211x 28211x 64867x 64867x 64867x 64867x 64867x 1x 1x 206x   206x 201x 206x 3x 3x 2x 2x 2x 206x 1x 1x 1x 1x 1x 1x 1x 68269x 68269x 1x 1x 1812x 1812x 1812x 2140x 1818x 2140x 2x 2x 320x 320x 1812x 63x     63x 63x 1812x 1812x 1812x 1x 1x 64898x 64898x 1x 1x 66744x 66744x 1x 1x 66281x 66281x 1x 1x     1x 1x 2x 2x 1x 1x 1x 1x 21602x 21602x 21602x 26x 26x 26x 26x 26x 12x 26x 14x 14x 14x 14x 26x 26x 26x 26x 31x 31x 31x 31x 3x 3x 3x 31x 31x 9x 31x 19x 19x       31x 26x 26x 21576x 21576x 21602x 13702x 13702x 4x 4x 1x 1x 4x 13702x 21576x 21576x 21602x 2301x 2301x 21576x 21576x 21602x 4253x 4253x 21576x 21576x 21602x 9400x 9400x 21576x 21576x 21576x 1x 1x 21602x 21602x 38308x 38308x 2x 2x 38306x 38306x 21600x 1x 1x 21602x 38308x 1x 1x 38308x 21602x 1x 1x 21576x 21576x 21576x 21576x 21576x 13x 13x 13x 13x 13x 13x 18x 3x 3x 15x 18x 18x 18x 18x 13x 13x 10x 10x 10x 10x 13x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 13x 21576x 21576x 3x 3x 3x 21576x 21576x 21576x                         21576x 1x 1x 20256x 20256x 26508x 26508x     26508x 26508x 3988x 26508x 18262x 18262x 26508x 5x 5x 26508x 26508x 26508x 26508x 20482x 20482x 26508x 21x 21x 21x 21x 21x 21x 21x 21x 26508x 20256x 17955x 17955x 2301x 2301x 20256x 2322x 2322x 2322x 2301x 1x 1x 1x 1x 1x 20256x 20256x     20256x 20256x 20256x 49098x 20268x 20268x 28830x 28830x 49098x 26508x 26508x 49098x 2322x 2322x         49098x     28830x 28830x 28830x 49098x 24830x 24830x 14x 24830x 13x 13x 24830x 27x 27x 27x 24830x 28830x 49098x 49098x 20256x 1x 1x 28830x 28830x 28830x 28830x 28830x 1x 1x  
/* eslint-disable max-len */
import {StatementNode} from "../nodes/statement_node";
import {MethodDef} from "../2_statements/statements/method_def";
import * as Expressions from "../2_statements/expressions";
import {ExpressionNode} from "../nodes";
import {TypedIdentifier, IdentifierMeta} from "./_typed_identifier";
import {ObjectReferenceType, UnknownType, VoidType} from "./basic";
import {MethodDefReturning} from "../5_syntax/expressions/method_def_returning";
import {MethodParam} from "../5_syntax/expressions/method_param";
import {BasicTypes} from "../5_syntax/basic_types";
import {IMethodParameters} from "./_method_parameters";
import {ObjectOriented} from "../5_syntax/_object_oriented";
import {ReferenceType} from "../5_syntax/_reference";
import {Identifier as IdentifierToken} from "../1_lexer/tokens/identifier";
import {ScopeType} from "../5_syntax/_scope_type";
import {SyntaxInput, syntaxIssue} from "../5_syntax/_syntax_input";
 
// the keywords that can follow a parameter in each section, a plain parameter name is read as them
const KEYWORDS_AFTER: {[section: string]: string[]} = {
  "IMPORTING": ["PREFERRED", "EXPORTING", "CHANGING", "RETURNING", "RAISING", "EXCEPTIONS"],
  "EXPORTING": ["CHANGING", "RETURNING", "RAISING", "EXCEPTIONS"],
  "CHANGING": ["RETURNING", "RAISING", "EXCEPTIONS"],
};
 
// todo:
// this.exceptions = [];
// also consider RAISING vs EXCEPTIONS
 
export class MethodParameters implements IMethodParameters {
  private preferred: string | undefined;
  private returning: TypedIdentifier | undefined;
  private readonly importing: TypedIdentifier[];
  private readonly optional: string[];
  private readonly exporting: TypedIdentifier[];
  private readonly changing: TypedIdentifier[];
  private readonly exceptions: string[]; // todo, not filled
  private readonly defaults: {[index: string]: ExpressionNode};
  private readonly filename: string;
 
  public constructor(node: StatementNode, input: SyntaxInput, abstractMethod: boolean) {
    if (!(node.get() instanceof MethodDef)) {
      throw new Error("MethodDefinition, expected MethodDef as part of input node");
    }
 
    this.importing = [];
    this.exporting = [];
    this.changing = [];
    this.optional = [];
    this.defaults = {};
    this.returning = undefined;
    this.preferred = undefined;
    this.exceptions = [];
    this.filename = input.filename;
 
    // need the scope for LIKE typing inside method parameters
    const parentName = input.scope.getName();
    input.scope.push(ScopeType.MethodDefinition, "method definition", node.getStart(), input.filename);
    try {
      this.parse(node, input, parentName, abstractMethod);
      this.checkNameLengths(input);
      this.checkDuplicateNames();
    } finally {
      input.scope.pop(node.getEnd());
    }
  }
 
  public getFilename(): string {
    return this.filename;
  }
 
  public getOptional(): string[] {
    return this.optional;
  }
 
  public getAll(): TypedIdentifier[] {
    const ret: TypedIdentifier[] = [];
    const returning = this.getReturning();
    if (returning) {
      ret.push(returning);
    }
    ret.push(...this.getImporting());
    ret.push(...this.getExporting());
    ret.push(...this.getChanging());
    return ret;
  }
 
  public getDefaultImporting(): string | undefined {
    if (this.importing.length === 0) {
      return undefined;
    } else if (this.importing.length === 1) {
      return this.importing[0].getName().toUpperCase();
    } else if (this.preferred) {
      return this.preferred;
    }
 
    let candidates = this.importing.map(i => i.getName().toUpperCase());
    candidates = candidates.filter(c => this.optional.indexOf(c) < 0);
    if (candidates.length === 1) {
      return candidates[0];
    }
 
    return undefined;
  }
 
  public getImporting() {
    return this.importing;
  }
 
  public getRequiredParameters() {
    const ret: TypedIdentifier[] = [];
 
    for (const i of this.getImporting()) {
      if (this.getOptional().some(o => o.toUpperCase() === i.getName().toUpperCase()) === true) {
        continue;
      } else if (this.preferred?.toUpperCase() === i.getName().toUpperCase()) {
        continue;
      }
      ret.push(i);
    }
    for (const i of this.getChanging()) {
      if (this.getOptional().some(o => o.toUpperCase() === i.getName().toUpperCase()) === true) {
        continue;
      }
      ret.push(i);
    }
 
    return ret;
  }
 
  public getExporting() {
    return this.exporting;
  }
 
  public getChanging() {
    return this.changing;
  }
 
  public getReturning() {
    return this.returning;
  }
 
  public getExceptions() {
    return this.exceptions;
  }
 
  public getParameterDefault(parameter: string) {
    return this.defaults[parameter.toUpperCase()];
  }
 
///////////////////
 
  private parse(node: StatementNode, input: SyntaxInput, parentName: string, abstractMethod: boolean): void {
 
    const handler = node.findFirstExpression(Expressions.EventHandler);
    if (handler) {
      const nameToken = node.findFirstExpression(Expressions.ClassName)?.getFirstToken();
      const ooName = nameToken?.getStr();
      const def = input.scope.findObjectDefinition(ooName);
      const doVoid = def ? false : !input.scope.getDDIC().inErrorNamespace(ooName);
      if (def) {
        input.scope.addReference(nameToken, def, ReferenceType.ObjectOrientedReference, input.filename);
      } else if (doVoid && ooName) {
        input.scope.addReference(
          nameToken, undefined, ReferenceType.ObjectOrientedVoidReference,
          this.filename, {ooName: ooName.toUpperCase()});
      }
 
      const eventName = node.findFirstExpression(Expressions.EventName)?.getFirstToken().getStr();
      const event = new ObjectOriented(input.scope).searchEvent(def, eventName);
      for (const p of handler.findAllExpressions(Expressions.MethodParamName)) {
        const token = p.getFirstToken();
        const search = token.getStr().toUpperCase().replace("!", "");
        this.optional.push(search); // all parameters optional for event handlers
        if (search === "SENDER" && def) {
          this.importing.push(new TypedIdentifier(token, this.filename, new ObjectReferenceType(def), [IdentifierMeta.EventParameter]));
          continue;
        }
        const found = event?.getParameters().find(p => p.getName().toUpperCase() === search);
        if (found) {
          this.importing.push(new TypedIdentifier(token, this.filename, found.getType(), [IdentifierMeta.EventParameter]));
        } else if (doVoid) {
          this.importing.push(new TypedIdentifier(token, this.filename, VoidType.get(ooName), [IdentifierMeta.EventParameter]));
        } else {
          const type = new UnknownType(`handler parameter not found "${search}"`);
          this.importing.push(new TypedIdentifier(token, this.filename, type, [IdentifierMeta.EventParameter]));
        }
      }
      return;
    }
 
    const importing = node.findFirstExpression(Expressions.MethodDefImporting);
    if (importing) {
      this.add(this.importing, importing, input, [IdentifierMeta.MethodImporting], abstractMethod);
      if (importing.findDirectTokenByText("PREFERRED")) {
        this.preferred = importing.getLastToken().getStr().toUpperCase();
        if (this.preferred.startsWith("!")) {
          this.preferred = this.preferred.substring(1);
        }
      }
    }
 
    const exporting = node.findFirstExpression(Expressions.MethodDefExporting);
    if (exporting) {
      this.add(this.exporting, exporting, input, [IdentifierMeta.MethodExporting], abstractMethod);
    }
 
    const changing = node.findFirstExpression(Expressions.MethodDefChanging);
    if (changing) {
      this.add(this.changing, changing, input, [IdentifierMeta.MethodChanging], abstractMethod);
    }
 
    const returning = node.findFirstExpression(Expressions.MethodDefReturning);
    if (returning) {
      this.returning = MethodDefReturning.runSyntax(returning, input, [IdentifierMeta.MethodReturning]);
    }
 
    this.workaroundRAP(node, input, parentName);
  }
 
  private checkDuplicateNames(): void {
    const names = new Set<string>();
    for (const parameter of this.getAll()) {
      const name = parameter.getName().toUpperCase();
      if (names.has(name)) {
        throw new Error(`Method parameter "${name}" already defined`);
      }
      names.add(name);
    }
  }
 
  private checkNameLengths(input: SyntaxInput): void {
    for (const parameter of this.getAll()) {
      if (parameter.getName().length > 30) {
        input.issues.push(syntaxIssue(input, parameter.getToken(), "Method parameter name longer than 30 characters"));
      }
    }
  }
 
  private workaroundRAP(node: StatementNode, input: SyntaxInput, parentName: string): void {
    const resultName = node.findExpressionAfterToken("RESULT");
    const concat = node.concatTokens().toUpperCase();
    const isRap = node.findExpressionAfterToken("IMPORTING")
      || (concat.includes(" IMPORTING REQUEST ") ? node.findExpressionAfterToken("REQUEST") : undefined);
    if (isRap) {
      // "FOR LOCK" handlers have a well defined signature, so the types can be derived
      const lockEntity = concat.includes(" FOR LOCK ")
        ? node.findExpressionAfterToken("LOCK")?.concatTokens()
        : undefined;
 
      for (const foo of node.findDirectExpressions(Expressions.MethodParamName)) {
        if (foo === resultName) {
          continue;
        }
        const type = lockEntity === undefined
          ? VoidType.get("RapMethodParameter")
          : new BasicTypes(input).rapTableFor(lockEntity);
        this.importing.push(new TypedIdentifier(foo.getFirstToken(), input.filename, type, [IdentifierMeta.MethodImporting]));
      }
 
      if (lockEntity !== undefined) {
        // note: "mapped" is not part of the signature for "FOR LOCK"
        const token = isRap.getFirstToken();
        this.exporting.push(new TypedIdentifier(new IdentifierToken(token.getStart(), "failed"), input.filename, VoidType.get(`RESPONSE FOR FAILED EARLY ${lockEntity}`), [IdentifierMeta.MethodExporting]));
        this.exporting.push(new TypedIdentifier(new IdentifierToken(token.getStart(), "reported"), input.filename, VoidType.get(`RESPONSE FOR REPORTED EARLY ${lockEntity}`), [IdentifierMeta.MethodExporting]));
      } else if (concat.includes(" FOR VALIDATE ")
          || concat.includes(" FOR BEHAVIOR ")
          || concat.includes(" FOR DETERMINE ")
          || concat.includes(" FOR FEATURES ")
          || concat.includes(" FOR INSTANCE FEATURES ")
          || concat.includes(" FOR GLOBAL AUTHORIZATION ")
          || concat.includes(" FOR INSTANCE AUTHORIZATION ")
          || concat.includes(" FOR AUTHORIZATION ")
          || concat.includes(" FOR PRECHECK ")
          || concat.includes(" FOR NUMBERING ")
          || concat.includes(" FOR READ ")
          || concat.includes(" FOR VALIDATION ")
          || concat.includes(" FOR MODIFY ")) {
        const token = isRap.getFirstToken();
        this.exporting.push(new TypedIdentifier(new IdentifierToken(token.getStart(), "failed"), input.filename, VoidType.get("RapMethodParameter"), [IdentifierMeta.MethodExporting]));
        this.exporting.push(new TypedIdentifier(new IdentifierToken(token.getStart(), "mapped"), input.filename, VoidType.get("RapMethodParameter"), [IdentifierMeta.MethodExporting]));
        this.exporting.push(new TypedIdentifier(new IdentifierToken(token.getStart(), "reported"), input.filename, VoidType.get("RapMethodParameter"), [IdentifierMeta.MethodExporting]));
      }
    }
 
    if (resultName) {
      const token = resultName.getFirstToken();
      this.importing.push(new TypedIdentifier(token, input.filename, VoidType.get("RapMethodParameter"), [IdentifierMeta.MethodExporting]));
    }
 
    // its some kind of magic
    if (parentName.toUpperCase() === "CL_ABAP_BEHAVIOR_SAVER") {
      const tempChanging = this.changing.map(c => new TypedIdentifier(c.getToken(), input.filename, VoidType.get("RapMethodParameter"), c.getMeta()));
      while (this.changing.length > 0) {
        this.changing.shift();
      }
      this.changing.push(...tempChanging);

      const tempImporting = this.importing.map(c => new TypedIdentifier(c.getToken(), input.filename, VoidType.get("RapMethodParameter"), c.getMeta()));
      while (this.importing.length > 0) {
        this.importing.shift();
      }
      this.importing.push(...tempImporting);
    }
  }
 
  private add(target: TypedIdentifier[], source: ExpressionNode, input: SyntaxInput, meta: IdentifierMeta[], abstractMethod: boolean): void {
    this.checkKeywordNames(source, input);
    for (const opt of source.findAllExpressions(Expressions.MethodParamOptional)) {
      const p = opt.findDirectExpression(Expressions.MethodParam);
      if (p === undefined) {
        continue;
      }
      const extraMeta: IdentifierMeta[] = [];
      if (this.isPassByValue(p)) {
        extraMeta.push(IdentifierMeta.PassByValue);
      } else if (meta.includes(IdentifierMeta.MethodImporting)) {
        extraMeta.push(IdentifierMeta.ReadOnly);
      }
      if (abstractMethod === true) {
        extraMeta.push(IdentifierMeta.Abstract);
      }
      const id = MethodParam.runSyntax(p, input, [...meta, ...extraMeta]);
      input.scope.addIdentifier(id);
      target.push(id);
      if (opt.findDirectTokenByText("OPTIONAL")) {
        const name = target[target.length - 1].getName().toUpperCase();
        this.optional.push(name);
      } else if (opt.findFirstExpression(Expressions.Default)) {
        const name = target[target.length - 1].getName().toUpperCase();
        this.optional.push(name);
 
        const val = opt.findFirstExpression(Expressions.Default)?.getLastChild();
        if (val && val instanceof ExpressionNode) {
          this.defaults[name] = val;
        }
      }
    }
    if (target.length > 0) {
      return;
    }
 
    const params = source.findAllExpressions(Expressions.MethodParam);
    for (const param of params) {
      const extraMeta = this.isPassByValue(param) ? [IdentifierMeta.PassByValue] : [];
      target.push(MethodParam.runSyntax(param, input, [...meta, ...extraMeta]));
    }
  }
 
  // A system reads a plain parameter name as a keyword wherever that keyword can stand, measured on 758:
  // "val TYPE clike default TYPE i" makes default the DEFAULT addition of val, and then fails
  // with "Unable to interpret ..." on what follows. "!default" and "VALUE(default)" are names
  private checkKeywordNames(section: ExpressionNode, input: SyntaxInput): void {
    const following = KEYWORDS_AFTER[section.getFirstToken().getStr().toUpperCase()];
    if (following === undefined) {
      return;
    }
    // undefined: no parameter before in this section, true: the one before has OPTIONAL or DEFAULT
    let previousHasAddition: boolean | undefined = undefined;
    for (const child of section.getChildren()) {
      if (!(child instanceof ExpressionNode)) {
        continue;
      }
      let param: ExpressionNode | undefined = undefined;
      let optional = false;
      if (child.get() instanceof Expressions.MethodParamOptional) {
        param = child.findDirectExpression(Expressions.MethodParam);
        optional = child.findDirectTokenByText("OPTIONAL") !== undefined;
      } else if (child.get() instanceof Expressions.MethodParam) {
        param = child;
      } else if (child.get() instanceof Expressions.MethodParamName) {
        // "TYPE ANY STRUCTURE", not measured, so never reported after it
        previousHasAddition = true;
        continue;
      }
      if (param === undefined) {
        continue;
      }
 
      const first = param.getFirstToken();
      const name = first.getStr().toUpperCase();
      if (param.getChildren()[0]?.get() instanceof Expressions.MethodParamName) {
        let readAs: string | undefined = undefined;
        if (following.includes(name)) {
          readAs = "the " + (name === "PREFERRED" ? "PREFERRED PARAMETER" : name) + " addition";
        } else if ((name === "DEFAULT" || name === "OPTIONAL") && previousHasAddition === false) {
          readAs = "the " + name + " addition of the parameter before it";
        }
        if (readAs !== undefined) {
          const message = "Parameter \"" + first.getStr() + "\" is read as " + readAs + ", rename it or escape it as !" + first.getStr();
          input.issues.push(syntaxIssue(input, first, message));
        }
      }
 
      previousHasAddition = optional || param.findFirstExpression(Expressions.Default) !== undefined;
    }
  }
 
  private isPassByValue(param: ExpressionNode): boolean {
    // "!" is the identifier escape, generated code has eg. "IMPORTING !VALUE(iv_foo)"
    const first = param.getFirstToken().getStr().toUpperCase();
    return (first === "VALUE" || first === "!VALUE")
      && param.getChildren()[1]?.getFirstToken().getStr() === "(";
  }
 
}