All files / cnx/TRANSPILE/1-Analyze/helpers StaticInitializers.ts

80.3% Statements 53/66
72.15% Branches 57/79
96.15% Functions 25/26
83.05% Lines 49/59

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                                                                        73x       73x                       2064x   3816x     704x 1124x                                               48x                               29x                   77x 77x 35x     35x         42x 42x                 5x 5x                             1x                                                                           5x                       17x 14x                         17x   18x 16x 16x                       15x 15x 4x 3x                           34x 34x 32x 32x             12x 14x         61x   32x         16x                 13x               3816x             1233x   33x       76x 437x     1124x                 85x 85x 85x 85x                 1124x                    
/**
 * #1735: the values a static-storage initializer holds.
 *
 * A file-scope or scope variable is initialized before the program runs, so C
 * requires each value in its initializer to be a constant expression (C99
 * 6.7.8p4): a `const` object is not one, and neither is ADR-044's clamp helper
 * call. Each is a value fixed at compile time (ADR-044, #1175), `mut` or not.
 * One of a cnx number or bool type that is not written as a literal is
 * folded here, at the type its position holds it at: the one answer 2.1
 * rejects (E0909, E0910) and 2.2 spells. One of any other type (an enum, a
 * struct) has no typed fold, but is asked the same question untyped, so one
 * that reads a variable or calls a function is rejected too (#2018).
 */
import type IProgram from "../../../types/IProgram";
import type TValueBinding from "../../../types/TValueBinding";
import type ISourcePosition from "../../../utils/types/ISourcePosition";
import type IVariableSymbol from "../../../types/symbols/IVariableSymbol";
import type IValuePosition from "../../../types/IValuePosition";
import type TConstExpr from "../../../types/TConstExpr";
import type TSettledConst from "../../../types/TSettledConst";
import type IProgramSyntax from "../../../types/syntax/IProgramSyntax";
import type TMemberDeclaration from "../../../types/syntax/TMemberDeclaration";
import type TExpression from "../../../types/syntax/TExpression";
import ConstExprLowering from "../../../utils/ConstExprLowering";
import ConstExprPrinter from "../../../utils/ConstExprPrinter";
import ConstantEvaluator from "../../../utils/ConstantEvaluator";
import type IConstantEnvironment from "../../../utils/types/IConstantEnvironment";
import ConstantFold from "../../../utils/ConstantFold";
import LengthProperty from "../../../utils/LengthProperty";
import TypeCheckUtils from "../../../utils/TypeCheckUtils";
import TypeText from "../../../utils/TypeText";
import type IStaticValue from "../types/IStaticValue";
import ValuePositions from "./ValuePositions";
 
type TConstName = Extract<TConstExpr, { kind: "name" }>;
 
const WRAPPING_OPERATORS: ReadonlySet<string> = new Set(["+", "-", "*", "<<"]);
type TReason = Extract<TSettledConst, { kind: "notConstant" }>["reason"];
 
/** What a value of no number or bool type has no value for C by */
const UNTYPED_WITHOUT_VALUE: ReadonlySet<TReason> = new Set<TReason>([
  "variable",
  "parameter",
  "call",
]);
 
class StaticInitializers {
  /** Each value to fold in the file's static-storage initializers */
  static values(
    program: IProgramSyntax,
    positions: ReadonlyMap<TExpression, IValuePosition>,
  ): IStaticValue[] {
    return program.members
      .flatMap(({ declaration }) =>
        StaticInitializers.declarations(declaration),
      )
      .flatMap((declaration) =>
        StaticInitializers.leaves(declaration.initializer!).flatMap((value) => {
          return StaticInitializers.isLiteral(value)
            ? []
            : [
                {
                  declaration,
                  value,
                  typeName: StaticInitializers.typeAt(positions, value),
                },
              ];
        }),
      );
  }
 
  /**
   * The value, held at its type, by the fold every pass shares. One of no
   * number or bool type is only asked whether it has a value: null when it
   * does, why not when it does not. A header macro is left to C, as it is
   * written (#1127).
   */
  static settle(
    value: IStaticValue,
    program: IProgram,
    sourceFile: string,
  ): TSettledConst | null {
    return StaticInitializers.settleIn(
      value,
      ConstantFold.environment(program, sourceFile),
    );
  }
 
  /**
   * `settle`, reading each header macro cnx can: what 2.1 checks, so a
   * macro's arithmetic clamps or wraps no more silently than a const's
   * (#1735 review 2). C is still given the macro.
   */
  static check(
    value: IStaticValue,
    program: IProgram,
    sourceFile: string,
  ): TSettledConst | null {
    return StaticInitializers.settleIn(
      value,
      ConstantFold.readingHeaderMacros(program, sourceFile),
    );
  }
 
  private static settleIn(
    value: IStaticValue,
    env: IConstantEnvironment,
  ): TSettledConst | null {
    const lowered = ConstExprLowering.lower(value.value);
    if (value.typeName !== null) {
      const settled = ConstantFold.primitiveValue(lowered, env, value.typeName);
      // A float fold past its type's range is infinite, which C has no
      // constant for (#1735 review 2)
      return settled?.kind === "float" &&
        !Number.isFinite(Number(settled.digits))
        ? { kind: "overflow", typeName: settled.typeName }
        : settled;
    }
    const result = ConstantEvaluator.evaluate(lowered, env);
    return result.kind === "value" ? null : result;
  }
 
  /**
   * Whether the value has none C can be given, which 2.1 reports (E0909):
   * one of a number or bool type that cnx cannot fold and C cannot
   * evaluate; one of any other type that reads a variable or calls a function
   */
  static lacksValue(value: IStaticValue, settled: TSettledConst): boolean {
    Iif (settled.kind !== "notConstant") return false;
    return value.typeName === null
      ? UNTYPED_WITHOUT_VALUE.has(settled.reason)
      : !StaticInitializers.cHasValue(settled);
  }
 
  /**
   * A value C evaluates that reads a cnx const, written as dimensions are
   * (`ConstantFold.settled`): each cnx name as its value, each header name
   * as C spells it -- since C cannot read the const object (#1735 review)
   */
  static cText(
    value: IStaticValue,
    program: IProgram,
    sourceFile: string,
  ): string {
    return ConstExprPrinter.toC(
      ConstExprLowering.lower(value.value),
      ConstantFold.environment(program, sourceFile),
    );
  }
 
  /**
   * Whether the value does arithmetic that can clamp or wrap: what cnx
   * must see every operand of to check (#1735 review 2)
   */
  static wraps(value: IStaticValue): boolean {
    const wraps = (expr: TConstExpr): boolean => {
      switch (expr.kind) {
        case "binary":
          return (
            WRAPPING_OPERATORS.has(expr.op) ||
            wraps(expr.left) ||
            wraps(expr.right)
          );
        case "unary":
          return expr.op === "-" || wraps(expr.operand);
        case "cast":
          return wraps(expr.operand);
        case "ternary":
          return (
            wraps(expr.condition) ||
            wraps(expr.whenTrue) ||
            wraps(expr.whenFalse)
          );
        default:
          return false;
      }
    };
    return wraps(ConstExprLowering.lower(value.value));
  }
 
  /** The value's outermost form, which says what does not fit */
  static formOf(value: IStaticValue): TConstExpr["kind"] {
    return ConstExprLowering.lower(value.value).kind;
  }
 
  /**
   * Whether the value reads a variable, `const` or not: what C rejects in a
   * static initializer, where an enum member or a length property is not
   */
  static readsVariable(
    value: TExpression,
    program: IProgram,
    sourceFile: string,
  ): boolean {
    return StaticInitializers.bindings(value, program, sourceFile).some(
      ({ binding }) => binding.kind === "variable" || binding.kind === "local",
    );
  }
 
  /**
   * What each name the value reads binds to, and where it is written; a
   * length property's subject is a size, which C is never asked to read
   */
  static bindings(
    value: TExpression,
    program: IProgram,
    sourceFile: string,
  ): { readonly binding: TValueBinding; readonly at: ISourcePosition }[] {
    return StaticInitializers.names(ConstExprLowering.lower(value)).flatMap(
      (name) => {
        if (LengthProperty.isLength(name.path.at(-1) ?? "")) return [];
        const target = program.constantTargetOf(sourceFile, name);
        return target === null
          ? []
          : [{ binding: target.binding, at: name.at }];
      },
    );
  }
 
  /**
   * Whether C has a value cnx does not: a char literal, or a name only a
   * header declares, reached directly or through the consts it is read from
   */
  static cHasValue(settled: TSettledConst): boolean {
    Iif (settled.kind === "foreign") return true;
    if (settled.kind !== "notConstant") return false;
    if (settled.reason === "character") return true;
    return settled.reason === "unfolded" && settled.because !== undefined
      ? StaticInitializers.cHasValue(settled.because)
      : false;
  }
 
  /**
   * The const a value names alone, as `CH` or `S.LIMIT` -- what C is given
   * when cnx has no value for it but C does (`cHasValue`) -- or null
   */
  static namedConst(
    value: TExpression,
    program: IProgram,
    sourceFile: string,
  ): IVariableSymbol | null {
    const lowered = ConstExprLowering.lower(value);
    if (lowered.kind !== "name") return null;
    const target = program.constantTargetOf(sourceFile, lowered);
    return target?.binding.kind === "variable" && target.rest.length === 0
      ? target.binding.symbol
      : null;
  }
 
  /** Each bare name the value reads (`N`, not `this.N` or `S.N`) */
  static bareNames(value: TExpression): TConstName[] {
    return StaticInitializers.names(ConstExprLowering.lower(value)).filter(
      (name) => name.root === null && name.path.length === 1,
    );
  }
 
  private static names(expr: TConstExpr): TConstName[] {
    switch (expr.kind) {
      case "name":
        return [expr];
      case "cast":
      case "unary":
        return StaticInitializers.names(expr.operand);
      case "binary":
        return [
          ...StaticInitializers.names(expr.left),
          ...StaticInitializers.names(expr.right),
        ];
      case "ternary":
        return [expr.condition, expr.whenTrue, expr.whenFalse].flatMap(
          StaticInitializers.names,
        );
      default:
        return [];
    }
  }
 
  /** The file's file-scope and scope variables that have an initializer */
  private static declarations(
    declaration: TMemberDeclaration,
  ): IStaticValue["declaration"][] {
    return declaration.kind === "variableDeclaration" && declaration.initializer
      ? [declaration]
      : [];
  }
 
  /** The values an initializer holds: an array's elements, a struct's fields */
  private static leaves(expr: TExpression): TExpression[] {
    switch (expr.kind) {
      case "arrayInitializer":
        return expr.fill === null
          ? expr.elements.flatMap(StaticInitializers.leaves)
          : StaticInitializers.leaves(expr.fill);
      case "structInitializer":
        return expr.fields.flatMap((field) =>
          StaticInitializers.leaves(field.value),
        );
      default:
        return [expr];
    }
  }
 
  /** The number or bool type the value's position holds it at, or null */
  private static typeAt(
    positions: ReadonlyMap<TExpression, IValuePosition>,
    value: TExpression,
  ): string | null {
    const typeText = ValuePositions.at(positions, value).typeText;
    Iif (typeText === null) return null;
    const typeName = TypeText.withoutDimensions(typeText);
    return TypeCheckUtils.isInteger(typeName) ||
      TypeCheckUtils.isFloat(typeName) ||
      typeName === "bool"
      ? typeName
      : null;
  }
 
  /** A literal is written as it stands, so it keeps its notation (`0xAB`) */
  private static isLiteral(value: TExpression): boolean {
    return (
      value.kind === "literal" ||
      (value.kind === "unary" &&
        value.operator === "-" &&
        value.operand.kind === "literal")
    );
  }
}
 
export default StaticInitializers;