Skip to content

CLICK Python Codegen

ladder_to_pyrung() and ladder_to_pyrung_project() convert CLICK ladder data back into executable pyrung Python source. This is the reverse of pyrung_to_ladder(), which exports to CLICK.

CSV operands accept supported CLICK expressions, not arbitrary Python calls. Unsupported syntax raises ValueError during generation. Imported names, comments, and string values are rendered as data. The generated project itself is still Python. Running its files runs that code with your account's permissions, as any Python script does.

Single-file codegen

ladder_to_pyrung() accepts a file path (to a CSV or directory) or a LadderBundle for in-memory round-trip without disk I/O.

from pyrung.click import ladder_to_pyrung

code = ladder_to_pyrung("main.csv")                    # from CSV file
code = ladder_to_pyrung("ladder_dir/")                  # from directory with subroutines/*.csv
code = ladder_to_pyrung(bundle)                         # from LadderBundle (no disk)
code = ladder_to_pyrung("main.csv", output_path="generated.py")  # write to file

Round-trip

from pyrung.click import pyrung_to_ladder, ladder_to_pyrung

bundle = pyrung_to_ladder(logic, mapping)
code = ladder_to_pyrung(bundle)          # no CSV files needed

Nickname substitution

Three ways to provide nicknames for readable variable names:

  1. nickname_csv= is the path to a CLICK nickname CSV (Address.csv). It is recommended, because it also enables structured type inference (see below).
  2. nicknames= is a pre-parsed {operand: nickname} dict (for example, {"X001": "start_button"}).
  3. With neither, codegen uses the raw operand names as they are (X001, DS1, and so on).

You can't pass both nickname_csv and nicknames.

code = ladder_to_pyrung("main.csv", nickname_csv="Address.csv")

code = ladder_to_pyrung("main.csv", nicknames={"X001": "start_button", "Y001": "motor"})

Structured type inference

When nickname_csv= is provided, codegen calls TagMap.from_nickname_file() internally. It reconstructs semantic metadata only from explicit markers such as :block, :udt, and :named_array(...). Bare tags remain grouping-only, so the generated code keeps them as flat tags or raw bank ranges instead of inventing pyrung structures.

Without nickname_csv, a named-array group comes back as slot aliases:

ds.slot(101, name='Channel1_Id')
ds.slot(102, name='Channel1_Val')
ds.slot(103, name='Channel2_Id')
ds.slot(104, name='Channel2_Val')
Channel1_Id = ds[101]
Channel1_Val = ds[102]
Channel2_Id = ds[103]
Channel2_Val = ds[104]

# in the program:
copy(Channel1_Id, Channel2_Val)

# TagMap is empty — tags are block aliases, not standalone objects
mapping = TagMap({})

With nickname_csv= pointing to a CSV that has named-array markers:

@named_array(Int, count=2)
class Channel:
    Id = 0
    Val = 0

# in the program:
copy(Channel[1].Id, Channel[2].Val)

# in TagMap:
mapping = TagMap([
    *Channel.map_to(ds.select(101, 104)),
], include_system=False)

Named-array instance windows round-trip as whole-instance selects when the ladder uses an exact aligned span:

blockcopy(RecipeProfile.instance(2), WorkingRecipe.select(1, 3))
fill(0, RecipeProfile.instance_select(1, 2))

This works for both dense and sparse layouts. The range length must be an exact multiple of the stride, and the range must start at an instance boundary.

For UDTs (fields spanning different memory banks), per-field map_to is emitted:

@udt(count=2)
class Motor:
    Running: Bool = False
    Speed: Int = 0

mapping = TagMap([
    Motor.Running.map_to(c.select(101, 102)),
    Motor.Speed.map_to(ds.select(1001, 1002)),
], include_system=False)

Singleton structures (count=1) use dotted access without indexing, as Config.Timeout and not Config[1].Timeout. If the CSV uses numbered names for a singleton (for example, Config1_Timeout), the importer infers always_number=True and emits @named_array(Int, always_number=True).

For details on @named_array and @udt syntax, see the Tag Structures guide. For the CSV marker format, see CSV marker format.

What codegen infers

Codegen infers these from the ladder:

  • tag types from operand prefixes (X→Bool, DS→Int, and so on)
  • block ranges from DS100..DS102 notation
  • OR expansion via Or()
  • branch conditions
  • timer and counter pin chains
  • for/next loops
  • comments

For the CSV format that codegen reads, see the laddercodec CSV format guide.

Round-trip guarantee

The generated code round-trips. exec() the output, and pyrung_to_ladder(logic, mapping) reproduces the original ladder CSV.

Codegen always emits the CLICK-first style (slot aliases, no standalone tag constructors). If you started with pyrung-first code (hand-written Int("SpeedCmd") + TagMap), exporting to CLICK and re-importing produces the CLICK-first form.

Range instructions use integer addresses (ds.select(1, 100)) with boundary nickname comments (# SpeedCmd..SpeedFbk) when the endpoints have nicknames, because a CLICK range is bound to its addresses. For remappable ranges, add :named_array markers to the nickname CSV, which gives you RecipeProfile.instance_select(1, 2) instead of raw addresses.

A Math formula

from pyrung.click import parse_click_formula

parse_click_formula("DS1 - DS2 + DS3 * DS4")        # the tree, in CLICK's order
parse_click_formula("- DH1 * DH2", hex_mode=True)  # None

parse_click_formula() returns the tree of a Math formula, grouped the way a CLICK computes it. It returns None when the value can depend on an order that nobody has checked on a CLICK. It raises ValueError for text that is not a formula.

A rung that laddercodec could not decode

laddercodec writes a marker rung in place of a rung that it cannot decode. Codegen reads the marker as undecoded():

from pyrung.click import undecoded

comment("UNDECODED: CLICK rung 5, row 1: unknown instruction (40 bytes)")
with rung():
    undecoded("unknown instruction (40 bytes)", rung=4, row=0, column=31, stop="end")

rung, row and column count from 0, as laddercodec counts them. CLICK counts the comment's numbers from 1, so the comment says rung 5 for rung=4.

When laddercodec stops reading partway through a file, one marker stands for that rung and every rung after it (to_the_end=True).

The scan stops at undecoded(). In the main program the scan ends there (stop="end"). In a subroutine the subroutine returns there (stop="return"). The debugger console names each marker and why it is there. mapping.validate(logic) reports each marker as undecoded-rung.

pyrung leaves out the rungs after undecoded(). A breakpoint on one of them does not bind.

The export to CLICK and the CircuitPython code refuse undecoded(). Write the rung's logic in its place, or remove the rung. Codegen refuses a marker inside a For loop. If a next() has no for() above it but comes after a marker, codegen writes an empty rung in its place, because the marker may have replaced the for(). The debugger console and the undecoded-rung finding name that next().

Multi-file project codegen

ladder_to_pyrung_project() generates a complete Python project instead of a single file. Each subroutine gets its own file with a @subroutine decorator. Tags and the TagMap live in tags.py. main.py ties everything together.

from pyrung.click import ladder_to_pyrung_project

files = ladder_to_pyrung_project("ladder_dir/")
files = ladder_to_pyrung_project("ladder_dir/", nickname_csv="Address.csv")
files = ladder_to_pyrung_project("ladder_dir/", output_dir="pump_project_py/")

The project has two kinds of guide:

  • README.pyrung.md, AGENTS.pyrung.md and click-cheatsheet.md belong to pyrung. They cover setup, running and testing, the export to CLICK, the program's shape and pyrung's syntax. pyrung writes them again each time it generates the project.
  • README.md, AGENTS.md and CLAUDE.md belong to the user. pyrung writes each one only if it does not exist yet. After that, pyrung changes only the line that holds <!-- pyrung:guidance -->. That line links the guides. In CLAUDE.md it imports them with @, so Claude Code loads them. With overwrite=True, pyrung writes these files again in full.
files = ladder_to_pyrung_project(
    "ladder_dir/",
    output_dir="pump_project_py/",
    host_guides=["AGENTS.mytool.md", "README.mytool.md"],
)

A tool that builds the project can write its own guides beside pyrung's and list them in host_guides. pyrung then links them:

  • each AGENTS.<name>.md from AGENTS.md, AGENTS.pyrung.md and CLAUDE.md
  • each README.<name>.md from README.md and README.pyrung.md

The tool's guides then replace some of pyrung's text:

  • With an AGENTS.<name>.md, AGENTS.pyrung.md leaves out how to start a debug session and how to get changes into CLICK.
  • With a README.<name>.md, README.pyrung.md leaves out its link on how to get changes into CLICK.

pyrung never reads, writes or deletes the tool's files.

The return value is a dict[str, str] mapping relative paths to content. These are the files that hold the program:

src/plc/
  tags.py                  # slot aliases, structures, TagMap
  main.py                  # Program context, main rungs, call() statements
  subroutines/
    __init__.py
    _sub_startup.py        # @subroutine("startup") decorated function
    _sub_alarm_handler.py

How subroutines are represented

Each subroutine file defines a decorated function that auto-registers with the Program when called:

# subroutines/_sub_startup.py
from pyrung import rung, subroutine, out
from ..tags import SubLight

@subroutine("startup")
def _sub_startup():
    with rung():
        out(SubLight)

main.py imports and calls it by reference (not by string name):

from .subroutines._sub_startup import _sub_startup

with Program() as logic:
    with rung(Button):
        call(_sub_startup)

The decorator keeps the CLICK subroutine name. The _sub_ prefix stops the function's name from clashing with a CLICK nickname.

Per-file imports

Each generated file imports only what it uses. A subroutine that touches X001 and Y001 won't import X002 or DS1. tags.py is the single source of truth for all tag declarations. Other files import from it.

Nickname and structure support

This works as it does for ladder_to_pyrung(). Pass nickname_csv= for readable variable names and automatic @named_array / @udt inference. Pass nicknames= for a pre-parsed dict.