This site is version 0.0.1. Most of the code on this site is drafted by an agent and needs review. I apologize for the AI-speak, we are working on rewriting it!
viv-lang.org

Notebooks · lib/cas/codegen

Straight-line Viv from CAS expressions, with common subexpressions computed once

A generator states what a kernel computes as expressions in the store (lib/cas/store), one per output: S[12] = X R1 + 2 R2. This module turns the list of outputs into straight-line Viv, one assignment per line.

Common subexpressions. The store keeps one node per distinct expression, so a subexpression that two outputs share is one node with two parents. cg_emit counts the parents of every node reachable from the outputs; a node with two or more becomes a local (t1 = ...) computed once, before its first use, and every other node is written inline. Leaves (numbers, symbols) are always inline.

Products. A product in the store is flat: ex ey ez w has four factors and no node for ex ey. Two products that share a prefix of factors in the term order (ex ey ez w1 and ex ey ez w2) would each multiply it out. The generator therefore writes a product of k >= 3 factors as the product of its first k - 1 factors, made a node of its own, times the last one, so shared prefixes become shared nodes and are counted like any other. The order of the factors is the store's term order (symbols by name), which the caller uses to put the factors it wants shared first.

Numbers. An integer power b^n is written as n - 1 products; a negative one as 1.0 / (...). A rational p/q is written as the double nearest it, which is what the division p / q gives. A symbol is written as its name, unless cg_symtext gave it a text: the generators use that for numeric coefficients that are not rational (the Cartesian-to-spherical factors), which the store keeps as symbols and the kernel gets as literals.

Use.

cg_reset()
cg_out("S[3]", e1)
cg_out("S[4]", e2)
lines = cg_emit("    ")

cg_emit returns the lines, the locals first where they are needed, then the assignments in the order they were given. cg_stats() is the number of locals and of operations (each +, -, *, / counted once), for the headers the generators write.

Used with import cas.codegen.

Look inside this program

  • Atlas

    The program’s map: every function and which calls which.

  • There’s no recorded run of this program yet.

Shift+Enter in a cell runs it and moves to the next. Running a cell runs every cell above it too, as one program.

[1]lines 46–373