All files / src/rules cds_check_syntax.ts

97.29% Statements 648/666
92.06% Branches 232/252
100% Functions 27/27
97.29% Lines 648/666

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 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 6671x 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 1x 1x 1x 1x 1x 1x 1x 1x 21212x 21212x 21212x 21212x 21212x 21212x 103557x 103557x 103557x 103557x 103557x 103557x 103557x 103557x 103557x 103557x 103557x 103557x 21212x 21212x 20205x 20205x 21212x 21212x 374x 374x 21212x 21212x 488x 488x 488x 488x 21212x 21212x 698x 580x 580x 118x 118x 118x 698x 2x 2x 116x 116x 116x 116x 116x 116x 116x 698x 115x 115x 116x 116x 116x 116x 116x 116x 116x 698x 19x 19x 116x 116x 116x 116x 21212x 21212x 116x 116x 116x 90x 2x 2x 88x 88x 88x 88x 90x 20x 20x 20x 88x 90x 88x 88x 90x 116x 116x 116x 21212x 21212x 116x 20x 20x 20x 11x 11x 11x 20x 116x 21212x 21212x 116x 38x 38x 18x 18x 20x 20x 38x 5x 5x 5x 38x 116x 21212x 21212x 21212x 116x 116x 116x 114x 114x 2x 2x 2x 116x     2x 2x 2x 2x 116x 1x 1x 1x 1x 1x 1x 21212x 21212x 21212x 115x 115x 103x 103x 12x 12x 115x 2x 2x 10x 10x 115x     10x 10x 10x 115x 3x 3x 7x 7x 115x     7x 7x 115x 115x 3x 3x 4x 4x 4x 4x 4x 4x 4x 115x 2x 2x 2x 2x 2x 2x 2x 2x 21212x 21212x 21212x 4x     4x 4x 4x 10x 10x     10x 10x 1x 1x 1x 1x 1x 10x 5x 5x 1x 1x 5x 10x 2x 2x 10x 4x 4x 4x 4x 21212x 21212x 21212x 116x 88x 88x 88x 88x 176x 176x 6x 6x 176x 88x 82x 82x 6x 6x 88x 9x 9x 9x     9x 9x 9x 9x 18x 18x 9x 9x 9x 18x 5x 5x 18x 9x 88x 1x 1x 5x 5x 88x 1x 1x 88x 21x 23x 23x 7x 7x 16x 16x 23x 13x 13x 3x 3x 3x 3x 3x 21x 5x 116x 21212x 21212x 21212x 63x 63x 129x 64x 129x 23x 65x 42x 42x 129x 63x 63x 21212x 21212x 116x 116x 102x 102x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 116x 180x 114x 22x 22x 22x 114x 180x 8x 66x 36x 14x 14x 36x 22x 22x 58x 22x 22x 22x 22x 22x 22x 22x 180x 14x 14x 116x 22x 13x 13x 9x 9x 22x 22x 22x 22x 5x 5x 5x 5x 5x 5x 4x 4x 22x 1x 1x 1x 1x 1x 1x 3x 3x 3x 22x 1x 1x 1x 1x 1x 22x 14x 21212x 21212x 22x 22x 22x 3x 22x 2x 2x 17x 17x 22x 4x 4x 4x 4x 4x 13x 13x 21212x 21212x 9x 9x 9x 9x 4x 4x 4x 4x 4x 5x 5x 21212x 21212x 3x 1x 1x 3x 2x 2x 2x 3x 21212x 21212x 116x 60x 60x 50x 50x 10x 10x 10x 10x 10x 10x 2x 2x 2x 2x 10x 10x 60x 116x 21212x 21212x 116x 116x 44x 44x 72x 116x 38x 38x 76x 76x 76x 73x 73x 3x 3x 3x 3x 38x 72x 21212x 21212x 116x 116x 116x 59x 59x 3x 59x 3x 3x 59x 113x 116x 1x 1x 1x 1x 1x 116x 21212x 21212x 115x 104x 104x 11x 11x 21212x 21212x 116x 223x     223x 223x 223x 120x 120x 120x 223x     223x 223x 223x 10x 10x 10x 223x 116x 21212x 21212x 21212x 116x 116x 116x 107x 107x 9x 9x 9x 116x 6x 4x 6x 2x 2x 116x 2x 2x 9x 116x 5x 5x 4x 4x 4x 116x 116x 116x 116x 21212x 21212x 116x 116x 116x 8x 8x 8x 8x 8x 8x 116x 116x 223x 223x 6x 6x 217x 217x 223x     217x 217x 223x 30x 30x 187x 223x 25x 25x 13x 13x 12x 25x 4x 4x 4x 12x 12x 162x 162x 223x 48x 48x 114x 114x 114x 223x 88x 88x 223x 5x 5x 5x 223x 116x 21212x 21212x 21212x 11x 11x 21212x 21212x 625x 625x 21212x  
import {ExpressionNode, TokenNode} from "../abap/nodes";
import {StructureType, UnknownType, VoidType} from "../abap/types/basic";
import {
  CDSAggregate, CDSAnnotation, CDSArithParen, CDSArithmetics, CDSAs, CDSAssociation, CDSCase, CDSCast, CDSComposition,
  CDSCondition, CDSDefineAbstract, CDSDefineProjection, CDSDefineView, CDSElement, CDSFunction, CDSGroupBy, CDSHaving,
  CDSInteger, CDSName, CDSPrefixedName, CDSProviderContract, CDSRelation, CDSSelect, CDSString, CDSType, CDSWhere,
} from "../cds/expressions";
import {readRelation, readSources} from "../cds/_cds_nodes";
import {findNamed} from "../cds/_names";
import {CDSParameterChecks} from "../cds/cds_parameter_checks";
import {DDIC} from "../ddic";
import {IFile} from "../files/_ifile";
import {Issue} from "../issue";
import {DataDefinition, DataElement} from "../objects";
import {IObject} from "../objects/_iobject";
import {IRegistry} from "../_iregistry";
import {BasicRuleConfig} from "./_basic_rule_config";
import {IRule, IRuleMetadata, RuleTag} from "./_irule";
 
export class CDSCheckSyntaxConf extends BasicRuleConfig {
}
 
type Source = {
  /** as listed in ParsedDataDefinition */
  name: string,
  as: string | undefined,
  /** the entity, for a path expression its first one, the target is not resolved */
  entity: string,
  kind: "entity" | "path",
  type: StructureType | UnknownType | VoidType,
  object: IObject | undefined,
};
 
const KNOWN_QUAN_DATA_ELEMENTS = ["MENGE_D"];
const KNOWN_CURR_DATA_ELEMENTS = ["BWERT", "DZWERT"];
 
// Reserved names, cannot be used as element names, see DDIC table TRESE
const RESERVED_ELEMENT_NAMES = ["BEGIN", "NUMBER", "POSITION", "ZONE", "HANDLER", "SECTION"];
 
// EndUserText.label is defined as String(60)
const MAX_LABEL_LENGTH = 60;
 
// Annotations which are not supported in CDS view entities
const VIEW_ENTITY_FORBIDDEN_ANNOTATIONS = ["Semantics.unitOfMeasure", "Semantics.currencyCode"];
 
// Select list elements which are expressions, ie. not plain fields
const CALCULATED_ELEMENT = [CDSCast, CDSCase, CDSArithmetics, CDSArithParen, CDSFunction, CDSAggregate, CDSString, CDSInteger];
 
export class CDSCheckSyntax implements IRule {
  private reg: IRegistry;
  private conf = new CDSCheckSyntaxConf();
  private businessObjectTargets: Set<string> | undefined;
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "cds_check_syntax",
      title: "CDS Check Syntax",
      shortDescription: "Checks CDS source, field, type, and semantic annotation references",
      extendedInformation: `Performs semantic checks which require other DDIC objects to be available.
 
Missing objects are only reported when their names match the configured errorNamespace.
 
SOURCE_TYPE in the abapGit XML is checked to match the DDL source, W view entity, P projection view, V DDIC-based view.`,
      tags: [RuleTag.Syntax],
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public setConfig(conf: CDSCheckSyntaxConf) {
    this.conf = conf;
  }
 
  public initialize(reg: IRegistry): IRule {
    this.reg = reg;
    this.businessObjectTargets = undefined;
    return this;
  }
 
  public run(object: IObject): Issue[] {
    if (!(object instanceof DataDefinition)) {
      return [];
    }
 
    const tree = object.getTree();
    const file = object.findSourceFile();
    if (tree === undefined || file === undefined) {
      return [];
    }
 
    const issues: Issue[] = [];
    const ddic = new DDIC(this.reg);
    const sources = this.findSources(tree, ddic, issues, file);
 
    this.checkRelations(tree, ddic, issues, file);
    this.checkTypes(tree, ddic, issues, file);
    if (this.checkRootProjection(tree, ddic, issues, file) === false) {
      this.checkTransactionalProjection(tree, ddic, issues, file);
    }
    this.checkCalculatedAssociationPaths(tree, issues, file);
    this.checkFieldAnnotations(tree, ddic, issues, file);
    this.checkLabels(tree, issues, file);
    this.checkViewEntityAnnotations(tree, issues, file);
    this.checkSearchable(tree, issues, file);
    this.checkReservedNames(tree, issues, file);
    this.checkFields(tree, sources, object, issues, file);
    for (const finding of new CDSParameterChecks(ddic).run(tree)) {
      issues.push(Issue.atToken(file, finding.token, finding.message, this.getMetadata().key, this.conf.severity));
    }
    this.checkSourceType(tree, object, issues);
 
    return issues;
  }
 
  private findSources(tree: ExpressionNode, ddic: DDIC, issues: Issue[], file: IFile): Source[] {
    const sources: Source[] = [];
 
    for (const found of readSources(tree)) {
      if (found.entity.kind === "function") {
        continue;
      }
 
      const entity = found.entity.name;
      const lookup = ddic.lookupTableOrView(entity);
 
      if (lookup.type instanceof UnknownType && lookup.object === undefined && this.reg.inErrorNamespace(entity)) {
        issues.push(Issue.atToken(file, found.entity.token, `CDS source "${entity}" not found`,
                                  this.getMetadata().key, this.conf.severity));
      }
 
      if (lookup.type instanceof StructureType || lookup.type instanceof UnknownType || lookup.type instanceof VoidType) {
        sources.push({name: found.name, as: found.alias, entity, kind: found.entity.kind, type: lookup.type, object: lookup.object});
      }
    }
 
    return sources;
  }
 
  private checkRelations(tree: ExpressionNode, ddic: DDIC, issues: Issue[], file: IFile) {
    for (const relation of tree.findAllExpressionsRecursive(CDSRelation)) {
      const {name: entity, token} = readRelation(relation);
      const lookup = ddic.lookupTableOrView(entity);
      if (lookup.type instanceof UnknownType && lookup.object === undefined && this.reg.inErrorNamespace(entity)) {
        issues.push(Issue.atToken(file, token, `CDS source "${entity}" not found`,
                                  this.getMetadata().key, this.conf.severity));
      }
    }
  }
 
  private checkTypes(tree: ExpressionNode, ddic: DDIC, issues: Issue[], file: IFile) {
    for (const typeNode of tree.findAllExpressionsRecursive(CDSType)) {
      const typeName = typeNode.findDirectExpressions(CDSName).map(n => this.name(n)).join(".");
      if (typeName === "" || typeName.toUpperCase().startsWith("ABAP.")) {
        continue;
      }
 
      const lookup = ddic.lookup(typeName);
      if (lookup.type instanceof UnknownType && lookup.object === undefined && this.reg.inErrorNamespace(typeName)) {
        issues.push(Issue.atToken(file, typeNode.getFirstToken(), `CDS type "${typeName}" not found`,
                                  this.getMetadata().key, this.conf.severity));
      }
    }
  }
 
  /** returns true if an issue was reported */
  private checkRootProjection(tree: ExpressionNode, ddic: DDIC, issues: Issue[], file: IFile): boolean {
    const projection = tree.findFirstExpression(CDSDefineProjection);
    const rootToken = projection?.findDirectTokenByText("ROOT");
    if (projection === undefined || rootToken === undefined) {
      return false;
    }
 
    const names = projection.findDirectExpressions(CDSName);
    const projectedEntityNode = names[1];
    if (projectedEntityNode === undefined) {
      return false;
    }
 
    const projectedEntityName = this.name(projectedEntityNode);
    const projectedEntity = ddic.lookupTableOrView(projectedEntityName).object;
    if (projectedEntity instanceof DataDefinition
        && projectedEntity.getTree()?.findDirectTokenByText("ROOT") === undefined) {
      const message = `ROOT keyword not valid since ${projectedEntityName} is not a root property`;
      issues.push(Issue.atToken(file, rootToken, message, this.getMetadata().key, this.conf.severity));
      return true;
    }
    return false;
  }
 
  /** a transactional projection(no provider contract or TRANSACTIONAL_QUERY) requires a business object entity */
  private checkTransactionalProjection(tree: ExpressionNode, ddic: DDIC, issues: Issue[], file: IFile) {
    const projection = tree.findFirstExpression(CDSDefineProjection);
    if (projection === undefined || projection.findDirectTokenByText("TRANSIENT") !== undefined) {
      return;
    }
 
    const contract = projection.findDirectExpression(CDSProviderContract);
    if (contract !== undefined && contract.findDirectTokenByText("TRANSACTIONAL_QUERY") === undefined) {
      return;
    }
 
    const projectedEntityNode = projection.findDirectExpressions(CDSName)[1];
    if (projectedEntityNode === undefined) {
      return;
    }
 
    const projectedEntityName = this.name(projectedEntityNode);
    const projectedEntity = ddic.lookupTableOrView(projectedEntityName).object;
    if (!(projectedEntity instanceof DataDefinition)) {
      return;
    }
    const projectedTree = projectedEntity.getTree();
    // only plain select based views are checked, ie. not projections, abstract or custom entities
    if (projectedTree === undefined || !(projectedTree.get() instanceof CDSDefineView)) {
      return;
    }
 
    if (projectedTree.findDirectTokenByText("ROOT") !== undefined
        || projectedTree.findAllExpressionsRecursive(CDSComposition).length > 0
        || projectedTree.findAllExpressionsRecursive(CDSAssociation).some(a => a.findDirectTokenByText("PARENT") !== undefined)) {
      return;
    }
 
    const candidates = [projectedEntityName.toUpperCase(), projectedEntity.getName().toUpperCase()];
    const definitionName = projectedEntity.getDefinitionName();
    if (definitionName !== undefined) {
      candidates.push(definitionName.toUpperCase());
    }
    const targets = this.findBusinessObjectTargets();
    if (candidates.some(c => targets.has(c))) {
      return;
    }
 
    const message = `Transactional projection on ${projectedEntityName} not possible, ` +
      `${projectedEntityName} is not a root entity or part of a composition`;
    issues.push(Issue.atToken(file, projectedEntityNode.getFirstToken(), message,
                              this.getMetadata().key, this.conf.severity));
  }
 
  /** names of entities targeted by a composition or an association to parent in any DDLS in the registry */
  private findBusinessObjectTargets(): Set<string> {
    if (this.businessObjectTargets !== undefined) {
      return this.businessObjectTargets;
    }
 
    const targets = new Set<string>();
    for (const obj of this.reg.getObjectsByType("DDLS")) {
      const tree = (obj as DataDefinition).getTree();
      if (tree === undefined) {
        continue;
      }
      const relations: ExpressionNode[] = [];
      for (const composition of tree.findAllExpressionsRecursive(CDSComposition)) {
        const relation = composition.findDirectExpression(CDSRelation);
        if (relation) {
          relations.push(relation);
        }
      }
      for (const association of tree.findAllExpressionsRecursive(CDSAssociation)) {
        const relation = association.findDirectExpression(CDSRelation);
        if (relation && association.findDirectTokenByText("PARENT") !== undefined) {
          relations.push(relation);
        }
      }
      for (const relation of relations) {
        targets.add(readRelation(relation).name.toUpperCase());
      }
    }
 
    this.businessObjectTargets = targets;
    return targets;
  }
 
  /** path expressions are not possible via an association whose ON condition uses a calculated element */
  private checkCalculatedAssociationPaths(tree: ExpressionNode, issues: Issue[], file: IFile) {
    for (const select of tree.findAllExpressionsRecursive(CDSSelect)) {
      const elements = select.findDirectExpressions(CDSElement);
 
      const calculated = new Map<string, string>();
      for (const element of elements) {
        const name = element.findDirectExpression(CDSAs)?.findDirectExpression(CDSName);
        if (name !== undefined && element.findDirectExpressionsMulti(CALCULATED_ELEMENT).length > 0) {
          calculated.set(this.name(name).toUpperCase(), this.name(name));
        }
      }
      if (calculated.size === 0) {
        continue;
      }
 
      const marked = new Map<string, string>();
      for (const association of select.findDirectExpressions(CDSAssociation)) {
        const relation = association.findDirectExpression(CDSRelation);
        const condition = association.findDirectExpression(CDSCondition);
        if (relation === undefined || condition === undefined) {
          continue;
        }
        const read = readRelation(relation);
        const alias = read.alias ?? read.name;
 
        for (const prefixed of condition.findAllExpressionsRecursive(CDSPrefixedName)) {
          const names = prefixed.findDirectExpressions(CDSName);
          if (names.length !== 2 || this.name(names[0]).toUpperCase() !== "$PROJECTION") {
            continue;
          }
          const element = calculated.get(this.name(names[1]).toUpperCase());
          if (element !== undefined && marked.has(alias.toUpperCase()) === false) {
            marked.set(alias.toUpperCase(), element);
          }
        }
      }
      if (marked.size === 0) {
        continue;
      }
 
      const usages: ExpressionNode[] = [...elements];
      for (const clause of select.findDirectExpressionsMulti([CDSWhere, CDSGroupBy, CDSHaving])) {
        usages.push(clause);
      }
      for (const usage of usages) {
        for (const prefixed of this.findPrefixedNames(usage)) {
          const names = prefixed.findDirectExpressions(CDSName);
          if (names.length < 2) {
            continue;
          }
          const alias = this.name(names[0]);
          const element = marked.get(alias.toUpperCase());
          if (element === undefined) {
            continue;
          }
          const message = `Path expression via ${alias} not possible, ` +
            `its ON condition uses calculated element ${element}`;
          issues.push(Issue.atToken(file, names[0].getFirstToken(), message,
                                    this.getMetadata().key, this.conf.severity));
        }
      }
    }
  }
 
  /** outermost prefixed names, skipping annotations */
  private findPrefixedNames(node: ExpressionNode): ExpressionNode[] {
    const ret: ExpressionNode[] = [];
    for (const child of node.getChildren()) {
      if (!(child instanceof ExpressionNode) || child.get() instanceof CDSAnnotation) {
        continue;
      } else if (child.get() instanceof CDSPrefixedName) {
        ret.push(child);
      } else {
        ret.push(...this.findPrefixedNames(child));
      }
    }
    return ret;
  }
 
  private checkFieldAnnotations(tree: ExpressionNode, ddic: DDIC, issues: Issue[], file: IFile) {
    const definition = tree.findFirstExpression(CDSDefineAbstract);
    if (definition === undefined) {
      return;
    }
 
    let definitionNameSeen = false;
    let fieldName: ExpressionNode | undefined;
    let annotations: ExpressionNode[] = [];
    const fields: {
      name: string,
      node: ExpressionNode,
      annotations: string[],
      semanticType: "QUAN" | "CURR" | undefined,
    }[] = [];
 
    for (const child of definition.getChildren()) {
      if (child instanceof TokenNode) {
        if (child.get().getStr() === ";") {
          fieldName = undefined;
          annotations = [];
        }
        continue;
      } else if (child.get() instanceof CDSAnnotation) {
        annotations.push(child);
      } else if (child.get() instanceof CDSName) {
        if (definitionNameSeen === false) {
          definitionNameSeen = true;
          annotations = [];
        } else {
          fieldName = child;
        }
      } else if (child.get() instanceof CDSType && fieldName !== undefined) {
        const semanticType = this.determineSemanticType(child, ddic);
        const normalizedAnnotations = annotations.map(a => a.concatTokens().replace(/\s/g, ""));
        fields.push({name: this.name(fieldName), node: fieldName, annotations: normalizedAnnotations, semanticType});
 
        fieldName = undefined;
        annotations = [];
      }
    }
 
    const reportedCompanionFields = new Set<string>();
    for (const field of fields) {
      if (field.semanticType === undefined) {
        continue;
      }
 
      const quantity = field.semanticType === "QUAN";
      const referenceAnnotation = quantity ? "@Semantics.quantity.unitOfMeasure" : "@Semantics.amount.currencyCode";
      const companionAnnotation = quantity ? "@Semantics.unitOfMeasure: true" : "@Semantics.currencyCode: true";
      const reference = this.findSemanticReference(field.annotations, field.semanticType);
      if (reference === undefined) {
        const kind = quantity ? "quantity" : "amount";
        const message = `CDS ${kind} field "${field.name}" requires ${referenceAnnotation}`;
        issues.push(Issue.atToken(file, field.node.getFirstToken(), message,
                                  this.getMetadata().key, this.conf.severity));
        continue;
      }
 
      const companion = fields.find(f => f.name.toUpperCase() === reference.toUpperCase());
      if (companion === undefined) {
        const kind = quantity ? "unit" : "currency";
        const message = `CDS field "${field.name}" references missing ${kind} field "${reference}"`;
        issues.push(Issue.atToken(file, field.node.getFirstToken(), message,
                                  this.getMetadata().key, this.conf.severity));
        continue;
      }
 
      const companionKey = field.semanticType + ":" + companion.name.toUpperCase();
      if (reportedCompanionFields.has(companionKey) === false
          && this.hasCompanionAnnotation(companion.annotations, field.semanticType) === false) {
        const message = `CDS field "${companion.name}" requires ${companionAnnotation}`;
        issues.push(Issue.atToken(file, companion.node.getFirstToken(), message,
                                  this.getMetadata().key, this.conf.severity));
        reportedCompanionFields.add(companionKey);
      }
    }
  }
 
  private determineSemanticType(typeNode: ExpressionNode, ddic: DDIC): "QUAN" | "CURR" | undefined {
    const typeName = typeNode.findDirectExpressions(CDSName).map(n => this.name(n)).join(".");
    const upper = typeName.toUpperCase();
    if (upper === "ABAP.QUAN" || KNOWN_QUAN_DATA_ELEMENTS.includes(upper)) {
      return "QUAN";
    } else if (upper === "ABAP.CURR" || KNOWN_CURR_DATA_ELEMENTS.includes(upper)) {
      return "CURR";
    }
 
    const object = ddic.lookup(typeName).object;
    if (object instanceof DataElement) {
      const dataType = object.getDataType(this.reg)?.toUpperCase();
      if (dataType === "QUAN" || dataType === "CURR") {
        return dataType;
      }
    }
    return undefined;
  }
 
  private findSemanticReference(annotations: string[], type: "QUAN" | "CURR"): string | undefined {
    const expression = type === "QUAN"
      ? /(?:SEMANTICS\.QUANTITY|SEMANTICS:\{QUANTITY:\{)\.?UNITOFMEASURE:'([^']+)'/i
      : /(?:SEMANTICS\.AMOUNT|SEMANTICS:\{AMOUNT:\{)\.?CURRENCYCODE:'([^']+)'/i;
    for (const annotation of annotations) {
      const match = annotation.match(expression);
      if (match) {
        return match[1];
      }
    }
    return undefined;
  }
 
  private hasCompanionAnnotation(annotations: string[], type: "QUAN" | "CURR"): boolean {
    if (type === "QUAN") {
      return annotations.some(a => a.toUpperCase().includes("@SEMANTICS.UNITOFMEASURE:TRUE")
        || a.toUpperCase().includes("@SEMANTICS:{UNITOFMEASURE:TRUE"));
    } else {
      return annotations.some(a => a.toUpperCase().includes("@SEMANTICS.CURRENCYCODE:TRUE")
        || a.toUpperCase().includes("@SEMANTICS:{CURRENCYCODE:TRUE"));
    }
  }
 
  private checkLabels(tree: ExpressionNode, issues: Issue[], file: IFile) {
    for (const annotation of tree.findAllExpressionsRecursive(CDSAnnotation)) {
      const concatenated = annotation.concatTokens();
      if (/@\s*<?\s*EndUserText/i.test(concatenated) === false) {
        continue;
      }
 
      const expression = /label\s*:\s*'((?:[^']|'')*)'/gi;
      let match = expression.exec(concatenated);
      while (match !== null) {
        const label = match[1].replace(/''/g, "'");
        if (label.length > MAX_LABEL_LENGTH) {
          const message = `CDS label is ${label.length} characters, maximum is ${MAX_LABEL_LENGTH}`;
          issues.push(Issue.atToken(file, annotation.getFirstToken(), message,
                                    this.getMetadata().key, this.conf.severity));
        }
        match = expression.exec(concatenated);
      }
    }
  }
 
  private checkViewEntityAnnotations(tree: ExpressionNode, issues: Issue[], file: IFile) {
    const view = tree.findFirstExpression(CDSDefineView);
    if (view === undefined || view.findDirectTokenByText("ENTITY") === undefined) {
      return;
    }
 
    for (const annotation of tree.findAllExpressionsRecursive(CDSAnnotation)) {
      const normalized = annotation.concatTokens().replace(/\s/g, "").toUpperCase().replace(/^@</, "@");
      for (const forbidden of VIEW_ENTITY_FORBIDDEN_ANNOTATIONS) {
        const upper = forbidden.toUpperCase();
        if (normalized.startsWith("@" + upper) === false
            && normalized.startsWith("@" + upper.replace(".", ":{")) === false) {
          continue;
        }
        const message = `Annotation ${forbidden} is not allowed in view entities`;
        issues.push(Issue.atToken(file, annotation.getFirstToken(), message,
                                  this.getMetadata().key, this.conf.severity));
      }
    }
  }
 
  private checkSearchable(tree: ExpressionNode, issues: Issue[], file: IFile) {
    let searchable: ExpressionNode | undefined;
 
    for (const annotation of tree.findAllExpressionsRecursive(CDSAnnotation)) {
      const normalized = annotation.concatTokens().replace(/\s/g, "").toUpperCase().replace(/^@</, "@");
      if (this.hasSearchAnnotation(normalized, /[.{,]DEFAULTSEARCHELEMENT:TRUE/)) {
        return;
      } else if (searchable === undefined && this.hasSearchAnnotation(normalized, /[.{,]SEARCHABLE:TRUE/)) {
        searchable = annotation;
      }
    }
 
    if (searchable !== undefined) {
      const message = "@Search.defaultSearchElement: true required on at least one element " +
        "when @Search.searchable: true";
      issues.push(Issue.atToken(file, searchable.getFirstToken(), message,
                                this.getMetadata().key, this.conf.severity));
    }
  }
 
  private hasSearchAnnotation(normalized: string, annotation: RegExp): boolean {
    if (normalized.startsWith("@SEARCH") === false) {
      return false;
    }
    return annotation.test(normalized);
  }
 
  private checkReservedNames(tree: ExpressionNode, issues: Issue[], file: IFile) {
    for (const element of tree.findAllExpressionsRecursive(CDSElement)) {
      if (element.findDirectTokenByText("INCLUDE") !== undefined) {
        continue;
      }
 
      let nameNode = element.findDirectExpression(CDSAs)?.findDirectExpression(CDSName);
      if (nameNode === undefined) {
        const names = element.findDirectExpression(CDSPrefixedName)?.findDirectExpressions(CDSName) || [];
        nameNode = names[names.length - 1];
      }
      if (nameNode === undefined) {
        continue;
      }
 
      const name = this.name(nameNode);
      if (RESERVED_ELEMENT_NAMES.includes(name.toUpperCase())) {
        issues.push(Issue.atToken(file, nameNode.getFirstToken(), `CDS element name "${name}" is reserved`,
                                  this.getMetadata().key, this.conf.severity));
      }
    }
  }
 
  /** SOURCE_TYPE in the XML must match the DDL source, only the confirmed W/P/V mappings are checked */
  private checkSourceType(tree: ExpressionNode, object: DataDefinition, issues: Issue[]) {
    const sourceType = object.getSourceType();
    const xmlFile = object.getXMLFile();
    if (sourceType === undefined || xmlFile === undefined || ["W", "P", "V"].includes(sourceType) === false) {
      return;
    }
 
    // other definitions(abstract, custom, table functions, etc.) are skipped
    let expected: string | undefined = undefined;
    if (tree.get() instanceof CDSDefineView && tree.findDirectTokenByText("WRITABLE") === undefined) {
      if (tree.findDirectTokenByText("ENTITY") !== undefined) {
        expected = "W";
      } else if (object.getSQLViewName() !== undefined) {
        expected = "V";
      }
    } else if (tree.get() instanceof CDSDefineProjection && tree.findDirectTokenByText("ENTITY") !== undefined) {
      expected = "P";
    }
 
    if (expected === undefined || expected === sourceType) {
      return;
    }
 
    const xml = xmlFile.getRaw();
    const index = xml.indexOf("<SOURCE_TYPE>");
    const row = index < 0 ? 1 : xml.substring(0, index).split("\n").length;
    const message = `SOURCE_TYPE "${sourceType}" does not match DDL source, expected "${expected}"`;
    issues.push(Issue.atRow(xmlFile, row, message, this.getMetadata().key, this.conf.severity));
  }
 
  private checkFields(tree: ExpressionNode, sources: Source[], object: DataDefinition,
                      issues: Issue[], file: IFile) {
    const associations = [...object.getParsedData()?.associations || []];
    for (const composition of tree.findAllExpressionsRecursive(CDSComposition)) {
      const relation = composition.findDirectExpression(CDSRelation);
      if (relation !== undefined) {
        const {name, alias} = readRelation(relation);
        associations.push({name, as: alias});
      }
    }
 
    for (const element of tree.findAllExpressionsRecursive(CDSElement)) {
      const prefixed = element.findDirectExpression(CDSPrefixedName);
      if (prefixed === undefined) {
        continue;
      }
 
      const names = prefixed.findDirectExpressions(CDSName);
      if (names.length === 0) {
        continue;
      }
 
      const first = this.name(names[0]);
      if (first === "*" || first.startsWith("$") || first.startsWith("#") || findNamed(associations, first) !== undefined) {
        continue;
      }
 
      if (names.length > 1) {
        const source = findNamed(sources, first);
        if (source === undefined || source.kind === "path" || !(source.type instanceof StructureType)) {
          continue;
        }
        const field = this.name(names[1]);
        if (field !== "*" && source.type.getComponentByName(field) === undefined && this.exposesAssociation(source, field) === false) {
          issues.push(Issue.atToken(file, names[1].getFirstToken(), `CDS field "${field}" not found in "${source.entity}"`,
                                    this.getMetadata().key, this.conf.severity));
        }
        continue;
      }
 
      // Do not guess across joins or when a dependency is absent.
      if (sources.length !== 1) {
        continue;
      }
 
      const source = sources[0];
      const sourceType = source.type;
      if (source.kind === "path" || !(sourceType instanceof StructureType)) {
        continue;
      }
      if (sourceType.getComponentByName(first) === undefined && this.exposesAssociation(source, first) === false) {
        issues.push(Issue.atToken(file, names[0].getFirstToken(), `CDS field "${first}" not found in "${source.entity}"`,
                                  this.getMetadata().key, this.conf.severity));
      }
    }
  }
 
  /** associations exposed by the source are not part of its structure type */
  private exposesAssociation(source: Source, name: string): boolean {
    return source.object instanceof DataDefinition && source.object.exposesAssociation(name);
  }
 
  private name(node: ExpressionNode): string {
    return node.concatTokens().replace(/ /g, "");
  }
}