Advanced

Constant folding as a rewrite

A pass that changes the tree is a rewrite. The rewrite is a rule with a shape on the left and a shape on the right, and the shapes are what make it provable.

What you will see

rounds_max 20. The number is the bound that stops the loop.

About 1 min of reading

Try It

Fold and prove equality

1

Write the rule

printf 'left=add num num right=addnum\n' > /tmp/r.txt; cat /tmp/r.txt

Before you run it, say out loud what it will print. Then open the answer.

What it prints
One line with two shapes. Two shapes is a rule.
2

Run to a fixed point

printf 'round 1 matches 2\nround 2 matches 0\n' | awk '{print $4}' | tail -1

Before you run it, say out loud what it will print. Then open the answer.

What it prints
0. Empty matches is the fixed point, which is the answer.
3

Write the bound

printf 'rounds_max 20\n' > /tmp/b.txt; cat /tmp/b.txt

Before you run it, say out loud what it will print. Then open the answer.

What it prints
rounds_max 20. The number is the bound that stops the loop.

Data Flow

A rule to a kept answer
1 The left shape is matched
↓
2 The right shape replaces it
↓
3 Rounds run until nothing matches
↓
4 The answer before equals the answer after
Why this works
Why the rewrite is run to a fixed point

One pass can open a new match. Running to a fixed point is running until the list is empty, and empty is a checkable answer.

The bound is written

A maximum number of rounds. The number is the bound, and the bound is what turns a loop into a decision.

Examples

The rule is two shapes

The left shape is matched, the right shape replaces it. Two shapes is a rule, and a rule is a line in a file.

The rewrite must keep the answer

The answer before equals the answer after. The equality is the claim, and the claim is checked by a test.

A rewrite that never stops is a loop

A rule whose right side matches its left side runs forever. The rule is refused at load, and the refusal is a name.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← A checker that refuses before running
Previous Lesson
A checker that refuses before running
Next Lesson
Passes as a pipeline
Passes as a pipeline →