All files / PARSE/4-Resolve TargetDescriptions.ts

97.79% Statements 133/136
92.77% Branches 77/83
100% Functions 22/22
97.74% Lines 130/133

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                                            129x   129x 129x 129x     129x     129x         129x                                     129x     2580x 2193x             129x                       25524x   500883x 1x     25524x 13x     25511x       25511x       25511x 25511x                   25524x 25524x 25524x 510480x 510480x 9598x 8x   9598x   500882x 500882x 5x     25524x 8x   25524x         25511x 25511x 51022x 127555x 127555x 127555x 2x       25511x             25511x 510220x 510220x 500630x 510220x                       31x   120x                         3189x 3189x   3189x         3189x 44647x         3189x 3189x 15945x 15945x 15912x   33x           3189x 6378x 1x           3189x 25x       3164x               44647x 25512x 25512x 14x 15x   25498x               25496x   25512x   19135x 15945x 15945x 15945x               15945x     15945x   15945x   3190x 1x                         41443x 1x 1x   41442x 1x 1x   41441x 41441x                 268x 268x                   501150x 501150x   1x 1x   501149x 169135x   332014x 4x   332010x 1x   332009x       501150x 332015x   169135x               3189x 3189x 1x         3189x 63780x         3189x           3189x                 6378x 6378x       6378x 70158x 70158x 1x     70157x 1x         6378x 70158x 1x             70157x 12754x   57403x 41458x   15945x          
/**
 * ADR-049: the one judge of a target description.
 *
 * A description is a set of field values, and it arrives two ways: as a row of
 * the target catalog, and (ADR-049, "Inline description") as a program's
 * description pragmas. Both are checked here, against the one schema in
 * `TARGET_DESCRIPTION_FIELDS`, so a catalog row and a pragma cannot be held to
 * different rules.
 *
 * A defect in the shipped catalog is an installation defect, not a user
 * diagnostic, so `catalog()` throws once, listing every problem, rather than
 * reporting a code.
 */
import TARGET_DESCRIPTION_FIELDS from "./TARGET_DESCRIPTION_FIELDS";
import invariant from "../../utils/invariant";
import type ITargetCatalogEntry from "../../types/ITargetCatalogEntry";
import type ITargetCatalogSource from "../../types/ITargetCatalogSource";
import type ITargetDescription from "../../types/ITargetDescription";
import type ITargetFieldSpec from "./types/ITargetFieldSpec";
import type TTargetFieldValue from "../../types/TTargetFieldValue";
 
/** The catalog schema versions this compiler reads */
const SCHEMA_VERSION = 1;
 
const DESCRIPTION_STRUCT = "TargetDescription";
const ALIAS_STRUCT = "TargetAlias";
const VERSION_CONST = "TARGET_SCHEMA_VERSION";
 
/** A name is one pragma word, so `#pragma target <name>` can spell it */
const PRAGMA_WORD = /^\w[\w.+-]*$/;
 
/** The C relations a description must satisfy, smallest first */
const ORDERED_WIDTHS: readonly (readonly (keyof ITargetDescription)[])[] = [
  ["short_bits", "int_bits", "long_bits", "long_long_bits"],
  ["float_bits", "double_bits", "long_double_bits"],
];
 
const ALIAS_MEMBERS: ReadonlyMap<string, string> = new Map([
  ["name", "string"],
  ["target", "string"],
]);
 
/** What `catalog()` has read so far */
interface ICollected {
  readonly names: Set<string>;
  readonly descriptions: Map<string, ITargetDescription>;
  readonly aliases: { name: string; target: string; line: number }[];
}
 
class TargetDescriptions {
  /**
   * The facts that define a platform: every schema field but the name and
   * the optional toolchain fields. Two descriptions are one platform when
   * these agree (`equal`), and they are what a program's description
   * pragmas give (#1760 review: RunTarget spelled this rule a second time).
   */
  static readonly PLATFORM_FACTS: readonly string[] = Object.entries(
    TARGET_DESCRIPTION_FIELDS,
  )
    .filter(([field, spec]) => field !== "name" && !spec.optional)
    .map(([field]) => field);
 
  /**
   * PlatformIO platforms whose boards are all one target, to its catalog
   * name. `catalog()` checks each name is the catalog's, so renaming a row
   * fails the installation rather than a user's build (#1760 review).
   */
  static readonly PLATFORM_TARGETS: ReadonlyMap<string, string> = new Map([
    ["atmelavr", "avr"],
    ["native", "host"],
  ]);
 
  /**
   * Check one description's fields. Returns the description, or every problem
   * with it -- never both.
   */
  static check(
    fields: ReadonlyMap<string, TTargetFieldValue>,
  ): { description: ITargetDescription } | { errors: string[] } {
    const errors = [
      ...[...fields.keys()]
        .filter((field) => !Object.hasOwn(TARGET_DESCRIPTION_FIELDS, field))
        .map((field) => `unknown field '${field}'`),
      ...TargetDescriptions.schemaProblems(fields),
    ];
    if (errors.length > 0) {
      return { errors };
    }
 
    const description: Record<string, unknown> = Object.fromEntries(fields);
    // Checked against the schema, not cast (#1668 review): the fields above
    // were validated one by one, and this says so in a form the compiler
    // can hold the result to
    invariant(
      TargetDescriptions.isDescription(description),
      "every field of a validated description has its schema's type",
    );
    const disordered = TargetDescriptions.orderProblems(description);
    return disordered.length > 0 ? { errors: disordered } : { description };
  }
 
  /**
   * Each schema field's problem, in schema order, then the required fields
   * that are absent
   */
  private static schemaProblems(
    fields: ReadonlyMap<string, TTargetFieldValue>,
  ): string[] {
    const errors: string[] = [];
    const missing: string[] = [];
    for (const [field, spec] of Object.entries(TARGET_DESCRIPTION_FIELDS)) {
      const value = fields.get(field);
      if (value === undefined) {
        if (!spec.optional) {
          missing.push(field);
        }
        continue;
      }
      const problem = TargetDescriptions.valueProblem(field, spec, value);
      if (problem) {
        errors.push(problem);
      }
    }
    if (missing.length > 0) {
      errors.push(`missing: ${missing.join(", ")}`);
    }
    return errors;
  }
 
  /** The C width relations a description breaks, narrowest first */
  private static orderProblems(description: ITargetDescription): string[] {
    const errors: string[] = [];
    for (const chain of ORDERED_WIDTHS) {
      for (let i = 1; i < chain.length; i++) {
        const narrower = chain[i - 1];
        const wider = chain[i];
        if (Number(description[narrower]) > Number(description[wider])) {
          errors.push(`${narrower} is wider than ${wider}`);
        }
      }
    }
    return errors;
  }
 
  /** Whether every schema field is present, or optional, with its kind's type */
  private static isDescription(
    value: Record<string, unknown>,
  ): value is Record<string, unknown> & ITargetDescription {
    return Object.entries(TARGET_DESCRIPTION_FIELDS).every(([field, spec]) => {
      const present = value[field];
      if (present === undefined) return spec.optional;
      const jsType = spec.kind === "unsigned" ? "number" : spec.kind;
      return typeof present === jsType;
    });
  }
 
  /**
   * Whether two descriptions describe the same platform: every required fact
   * equal, whatever the names. So an alias agrees with its target, and an
   * inline description agrees with the catalog row it spells out. The
   * toolchain fields are not compared -- they never change a program's
   * meaning.
   */
  static equal(a: ITargetDescription, b: ITargetDescription): boolean {
    return TargetDescriptions.PLATFORM_FACTS.every(
      (field) =>
        a[field as keyof ITargetDescription] ===
        b[field as keyof ITargetDescription],
    );
  }
 
  /**
   * Every name the catalog defines, aliases included, mapped to the
   * description it denotes. Throws on any defect, listing all of them.
   */
  static catalog(
    source: ITargetCatalogSource,
    path: string,
  ): ReadonlyMap<string, ITargetDescription> {
    const errors = [...source.errors];
    TargetDescriptions.checkSchema(source, errors);
 
    const collected: ICollected = {
      names: new Set(),
      descriptions: new Map(),
      aliases: [],
    };
    for (const entry of source.entries) {
      TargetDescriptions.collect(entry, collected, errors);
    }
 
    // Resolved against descriptions only, so an alias of an alias is refused
    // rather than silently followed.
    const targets = new Map(collected.descriptions);
    for (const alias of collected.aliases) {
      const description = collected.descriptions.get(alias.target);
      if (description) {
        targets.set(alias.name, description);
      } else {
        errors.push(
          `line ${alias.line}: alias '${alias.name}' names '${alias.target}', which is not a ${DESCRIPTION_STRUCT}`,
        );
      }
    }
 
    for (const [platform, name] of TargetDescriptions.PLATFORM_TARGETS) {
      if (!targets.has(name)) {
        errors.push(
          `PlatformIO platform '${platform}' maps to '${name}', which the catalog does not name`,
        );
      }
    }
 
    if (errors.length > 0) {
      throw new Error(
        `The target catalog ${path} is invalid; the compiler installation is broken:\n  ${errors.join("\n  ")}`,
      );
    }
    return targets;
  }
 
  private static collect(
    entry: ITargetCatalogEntry,
    collected: ICollected,
    errors: string[],
  ): void {
    if (entry.typeName === DESCRIPTION_STRUCT) {
      const result = TargetDescriptions.check(entry.fields);
      if ("errors" in result) {
        for (const error of result.errors) {
          errors.push(`line ${entry.line}: ${entry.constName}: ${error}`);
        }
      } else if (
        TargetDescriptions.claim(
          result.description.name,
          entry.line,
          collected,
          errors,
        )
      ) {
        collected.descriptions.set(result.description.name, result.description);
      }
      return;
    }
    if (entry.typeName === ALIAS_STRUCT) {
      const name = entry.fields.get("name");
      const target = entry.fields.get("target");
      Iif (
        typeof name !== "string" ||
        typeof target !== "string" ||
        entry.fields.size !== 2
      ) {
        errors.push(
          `line ${entry.line}: ${entry.constName}: an alias gives exactly a name and a target`,
        );
      E} else if (
        TargetDescriptions.claim(name, entry.line, collected, errors)
      ) {
        collected.aliases.push({ name, target, line: entry.line });
      }
      return;
    }
    if (entry.constName !== VERSION_CONST) {
      errors.push(
        `line ${entry.line}: '${entry.constName}' is neither a ${DESCRIPTION_STRUCT} nor a ${ALIAS_STRUCT}`,
      );
    }
  }
 
  /** Whether `name` may be defined: one pragma word, not defined before */
  private static claim(
    name: string,
    line: number,
    collected: ICollected,
    errors: string[],
  ): boolean {
    if (!PRAGMA_WORD.test(name)) {
      errors.push(`line ${line}: '${name}' is not one pragma word`);
      return false;
    }
    if (collected.names.has(name)) {
      errors.push(`line ${line}: '${name}' is defined twice`);
      return false;
    }
    collected.names.add(name);
    return true;
  }
 
  /**
   * What is wrong with one field's value, or null. The same judgement a
   * catalog row gets, for a description pragma.
   */
  static fieldProblem(field: string, value: TTargetFieldValue): string | null {
    const spec: ITargetFieldSpec | undefined =
      TARGET_DESCRIPTION_FIELDS[field as keyof ITargetDescription];
    return spec
      ? TargetDescriptions.valueProblem(field, spec, value)
      : `unknown field '${field}'`;
  }
 
  private static valueProblem(
    field: string,
    spec: ITargetFieldSpec,
    value: TTargetFieldValue,
  ): string | null {
    const kind = TargetDescriptions.kindOf(value);
    if (kind !== spec.kind) {
      const expected =
        spec.kind === "unsigned" ? "an unsigned integer" : `a ${spec.kind}`;
      return `${field} must be ${expected}`;
    }
    if (typeof value !== "number") {
      return null;
    }
    if (spec.allowed && !spec.allowed.includes(value)) {
      return `${field} must be one of ${spec.allowed.join(", ")}`;
    }
    if (spec.min !== undefined && value < spec.min) {
      return `${field} must be at least ${spec.min}`;
    }
    return null;
  }
 
  private static kindOf(value: TTargetFieldValue): ITargetFieldSpec["kind"] {
    if (typeof value === "number") {
      return "unsigned";
    }
    return typeof value === "boolean" ? "boolean" : "string";
  }
 
  /** The version constant and both structs, member for member */
  private static checkSchema(
    source: ITargetCatalogSource,
    errors: string[],
  ): void {
    const version = source.entries.find((e) => e.constName === VERSION_CONST);
    if (version?.value !== SCHEMA_VERSION) {
      errors.push(
        `${VERSION_CONST} must be ${SCHEMA_VERSION}, the schema version this compiler reads`,
      );
    }
 
    const expected = new Map(
      Object.entries(TARGET_DESCRIPTION_FIELDS).map(([field, spec]) => [
        field,
        spec.kind,
      ]),
    );
    TargetDescriptions.checkStruct(
      source,
      DESCRIPTION_STRUCT,
      expected,
      errors,
    );
    TargetDescriptions.checkStruct(source, ALIAS_STRUCT, ALIAS_MEMBERS, errors);
  }
 
  private static checkStruct(
    source: ITargetCatalogSource,
    struct: string,
    expected: ReadonlyMap<string, string>,
    errors: string[],
  ): void {
    const members = source.structs.get(struct);
    Iif (!members) {
      errors.push(`struct ${struct} is missing`);
      return;
    }
    for (const [member, type] of members) {
      const kind = expected.get(member);
      if (kind === undefined) {
        errors.push(
          `struct ${struct} has '${member}', which the schema does not`,
        );
      } else if (TargetDescriptions.memberKind(type) !== kind) {
        errors.push(
          `struct ${struct}: '${member}' must hold a ${kind}, not ${type}`,
        );
      }
    }
    for (const member of expected.keys()) {
      if (!members.has(member)) {
        errors.push(`struct ${struct} lacks '${member}'`);
      }
    }
  }
 
  /** The schema kind a C-Next member type holds, or the type itself */
  private static memberKind(type: string): string {
    if (type === "bool") {
      return "boolean";
    }
    if (/^u(?:8|16|32|64)$/.test(type)) {
      return "unsigned";
    }
    return /^string<\d+>$/.test(type) ? "string" : type;
  }
}
 
export default TargetDescriptions;