Skip to content

Evaluate Constant Expressions

Robert L. Bocchino Jr. edited this page Apr 18, 2024 · 3 revisions

This algorithm traverses the source model and computes the values of constant symbols and expressions.

Input

  1. A list tul of translation units.

  2. An analysis data structure a representing the results of analysis so far. Evaluate Implied Enum Constants must have already been run.

Output

  1. The analysis a with an updated value map, if the check passes; otherwise an error.

Procedure

  1. Visit each translation unit in tul with input a, yielding either a new analysis a' or an error.

AST Visitor Methods

Each method accepts an analysis data structure a as input and yields either a new analysis data structure a' or an error as output.

Translation Units

For each translation unit tu, visit each definition appearing in tu.

Definitions

For each constant definition d:

  1. If d is not in the value map of a, then

    1. Visit each expression appearing in d, threading the analysis through the visits. Let a' be the resulting analysis.

    2. Use the value map of a' to compute the value v of d.

    3. Let a'' be the analysis data structure that results from adding the mapping from d to v to the value map of a'.

    4. Yield a'' as the result.

  2. Otherwise we have already visited d; yield a as the result.

For each enum definition d, check that the enumerated constants of d all have different values.

Type Names and Expressions

For each AST node n that represents an expression:

  1. Compute the value v of n:

    1. If the value of n is directly available (for example, the value of the integer literal 1 is 1), then use that as v.

    2. Otherwise if n represents a use, then

      1. Look in the use-def map of n to get the symbol s corresponding to n. Throw an internal error if it is not there.

      2. Visit the definition corresponding to s.

      3. Look in the value map of a to get the value v of s. Throw an internal error if it is not there.

      4. Use v as the value of n.

    3. Otherwise

      1. Visit the child expressions of v.

      2. Use the child values to compute the value v of n.

  2. Update the value map with the mapping of n to v.