Skip to content

Ladder Lints: Static Checks for Ladder Logic

ModeCommand = Int("ModeCommand", external=True)
InvalidMode = Bool("InvalidMode")

with Program() as logic:
    with rung(ModeCommand < 1, ModeCommand > 3):
        out(InvalidMode)

The rung intends to turn on InvalidMode when the command falls outside 1..3. Rung arguments are ANDed, though, and no value can be both less than 1 and greater than 3. The mistake does not need a scan to surface:

report = logic.check()
for finding in report:
    print(finding)
[RUNG_CONTRADICTION] error
 --> Main:R1
  |
  |  with rung(ModeCommand < 1, ModeCommand > 3):
  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can't both be true
  |
  = hint: did you mean Or(ModeCommand < 1, ModeCommand > 3)?

Contacts placed in series mean AND, and contacts on parallel branches mean OR. Multiple rung(...) arguments preserve the series relationship, while Or(...) preserves the parallel one.

The corrected guard uses parallel logic:

with rung(Or(ModeCommand < 1, ModeCommand > 3)):
    out(InvalidMode)

logic.check() runs a core set of rules across the whole ladder. Broader checks such as stuck coils and comparison style are opt-in.

For a CI gate that fails on errors:

report = logic.check()
assert not report.errors(), report.summary()

A clean report is not a proof that the program is correct or that every path is reachable. Use Test Coverage for behavior observed across tests.

Reading a report

ValidationReport is iterable. Each finding carries a .code, .severity, .target_name, and .message:

for finding in logic.check():
    print(finding)

The four severities are:

Severity Meaning
error The program is provably wrong as written.
warning A high-confidence bug pattern that usually needs a repair.
info A consistency or completeness issue worth reviewing.
advisory An intent heuristic that is too uncertain for a warning.

The report is truthy when it contains any finding. Use assert not report when every severity must be clean.

Selecting rules

The core rules run when select is omitted. select replaces that set. extend_select adds to it. ignore excludes rules. Selectors accept complete codes, prefixes, or ALL:

logic.check(select={"RUNG"})
logic.check(select={"COIL_STUCK_HIGH", "COIL_STUCK_LOW"})
logic.check(ignore={"CMP_STATIC_ON_LEFT"})
logic.check(extend_select={"CMP"})
logic.check(select={"ALL"})
logic.check(select=set())  # Explicitly run no checks.

Categories are the prefixes before the first underscore:

Category Checks
RUNG Contradictory, ineffective, and redundant rung conditions
COIL Conflicting and one-sided coil writes
CMP Comparisons that cannot behave as intended
TAG Writes that violate tag declarations
PTR Unsafe indirect-pointer defaults
CALL Unreachable or recursive subroutine calls
MATH Definite arithmetic faults
PHYS Physical-link completeness and realism
STEP State-machine steps with no available escape

The most specific matching selector wins, and ignore wins a tie. report.checked_rules records the actual selection, including checks that produced no findings.

The core set is TAG_READONLY_WRITE, TAG_CHOICES_VIOLATION, TAG_RANGE_VIOLATION, TAG_FINAL_MULTIPLE_WRITERS, TAG_DEAD_WRITE, COIL_CONFLICTING_OUTPUT, PTR_DEFAULT_BEFORE_BLOCK_START, PTR_MAY_ESCAPE_BLOCK, RUNG_CONTRADICTION, RUNG_TAUTOLOGY, RUNG_ORDER_DEPENDENT, CMP_ALWAYS_FALSE, CMP_EQ_ON_MONOTONE, CALL_RECURSION, and MATH_DIV_ZERO.

Project settings

[tool.pyrung.check]
extend-select = ["CMP", "PTR_UNGUARDED_ACCESS"]
ignore = ["CMP_STATIC_ON_LEFT", "CMP_REPEATED_STATE_VALUE"]

Omit select to retain core defaults, or use select = ["ALL"] to enable everything. Prefixes also select matching checks added in later versions.

pyrung check starts in the current directory and reads the nearest ancestor pyproject.toml that contains this section. --config path/to/pyproject.toml chooses a file explicitly. Command-line --select and --ignore replace their project values. --extend-select adds to the project's extend-select list.

logic.check() does not read [tool.pyrung.check]. Pass select and ignore to it.

Command line

Run the same checks against a module containing one Program:

pyrung check my_program
pyrung check my_program --select RUNG CMP
pyrung check my_program --ignore CMP_STATIC_ON_LEFT

Use module:variable when a module contains more than one program. The command prints every finding and exits with status 1 when the report contains an error.

Against a program already loaded by the debugger:

pyrung live check
pyrung live check RUNG

Rule reference

Rung conditions

Code Severity What it detects
RUNG_CONTRADICTION Error A rung condition conjunction that is provably unsatisfiable, so the rung can never fire.
RUNG_TAUTOLOGY Warning A top-level Or(...) term that is provably always true and therefore gates nothing.
RUNG_REDUNDANT_TERM Info An exact duplicate or provably subsumed Boolean/range term.
RUNG_ORDER_DEPENDENT Warning A branch, a .continued() rung, or a box's pin (.reset(), .jump(), .jog(), .clock(), .down(), a drum event) reads a tag written by an instruction above it in the same rung (or chain of continued rungs), so it sees the new value (how a rung evaluates).

The check ignores instruction operands, because they always see every write above them. Move the read to a rung of its own below the write, or the write to a rung above, so the order no longer matters.

Coils

Code Severity What it detects
COIL_CONFLICTING_OUTPUT Error Multiple out/timer/counter/drum/shift instructions target the same tag from paths that are not provably mutually exclusive. Whichever wrote last wins.
COIL_STUCK_HIGH Warning A tag is latched but never reset. An out that a scan can skip counts as a latch. See Outputs that a scan can skip.
COIL_STUCK_LOW Warning A tag is reset but never latched anywhere in the program.

For conflicting outputs, the lint treats two paths as mutually exclusive in these cases:

  • equality comparisons against different constants
  • complementary Boolean contacts
  • complementary ranges such as </>= or <=/>
  • different subroutines whose caller conditions are provably exclusive

When the lint cannot prove exclusivity statically, it keeps the finding.

Comparisons

Code Severity What it detects
CMP_ALWAYS_FALSE Warning A comparison that is false for every value its operand can hold, as set by its Bool type, its choices=, its integer bounds, or the values the rungs that write it produce.
CMP_ALWAYS_TRUE Info An equality or inequality comparison that is true for every value in a complete domain.
CMP_EQ_ON_MONOTONE Warning Equality against a timer or counter accumulator that can step past the exact value.
CMP_EQ_ON_COMPUTED_REAL Advisory == or != on a REAL the ladder computes with math() (or copies from one), where rounding can step over the exact value. The mean() of an integer range counts only against a value that the mean cannot equal exactly, such as 3.3333 against the mean of three slots. Use a range or a tolerance.
CMP_OPERAND_NO_WRITER Advisory A numeric comparison operand has no ladder writer or declared outside source.
CMP_PRESET_STAYS_ZERO Warning A preset is a tag that starts at 0 and no rung writes. The preset is a timer's, a counter's, a drum step's, or the time of a debounce(), flasher() or timed() coil. A timer, counter or drum step with such a preset finishes at once.
CMP_STEPPER_VALUE_NOT_SET Warning A step tag (one the program moves through a set of values) is compared with a value no rung sets it to.
CMP_REPEATED_STATE_VALUE Advisory Literal equality comparisons against the same discrete values are repeated heavily or spread across the program.
CMP_TRUE_AT_RESET Warning A timer or counter completion comparison is already true when the accumulator resets.
CMP_STATIC_ON_LEFT Advisory An ordered comparison may read backwards because the changing value is on the right.

Tags

Code Severity What it detects
TAG_READONLY_WRITE Error A write instruction targets a readonly tag declared with readonly=True.
TAG_CHOICES_VIOLATION Error A literal write is not present in the target tag's choices keys.
TAG_RANGE_VIOLATION Error A literal write falls outside the target tag's declared min/max limits.
TAG_FINAL_MULTIPLE_WRITERS Error More than one write site targets a tag declared with final=True. Mutual exclusivity does not exempt the writers.
TAG_DEAD_WRITE Warning A write that a later write in the same scan always overwrites before anything reads it.

Pointers

Code Severity What it detects
PTR_DEFAULT_BEFORE_BLOCK_START Warning An exact indirect dereference such as DS[Ptr] uses a pointer whose default is below the block start. This usually means a 1-based block is indexed by a tag with the implicit default=0.
PTR_MAY_ESCAPE_BLOCK Warning A pointer can still point outside its block where it is used, even with the conditions that guard that use.
PTR_UNGUARDED_ACCESS Advisory Nothing limits the pointer's values, and its guards don't check both ends of the block.

These checks cover scalar Block[Ptr] accesses.

with rung(Ptr >= 1, Ptr <= 100):
    copy(Data[Ptr], Result)

A guard covers the access only if nothing writes Ptr between the guard's read and the access.

Calls and arithmetic

Code Severity What it detects
CALL_NEVER_CALLED Info A program-owned subroutine with no call path from Main.
CALL_RECURSION Error A subroutine that calls itself, directly or through other subroutines.
MATH_DIV_ZERO Error A /, //, or % divisor in math that is proved zero whenever the instruction can execute.

Physical behavior

Code Severity What it detects
PHYS_MISSING_PROFILE Info A tag has a Physical relationship through link, but the linked analog tag has no ramp_on or approach_to response.
PHYS_ANTITOGGLE Warning A feedback-linked command can pulse or change state faster than its declared feedback timing.
PHYS_LINK_UNKNOWN Warning A tag's link names an enable the program never reads or writes, so the harness has nothing to drive its feedback from.

The physical checks, including TAG_RANGE_VIOLATION, use the scan interval passed as dt:

report = logic.check(dt=0.05)

State-machine steps

Code Severity What it detects
STEP_NO_ESCAPE Warning A step's only advance requires something the program cannot supply, with no escape that can fire unaided. The machine can remain in that step forever. See Wait edges without escape.

Outputs that a scan can skip

An out coil de-energizes only on scans where its instruction runs. If a conditional call skips the subroutine, or return_early() or end_early() skips the rung, the coil retains its last value. The out therefore needs another path that can reset it:

with rung(Running):
    call("run_cycle")

with subroutine("run_cycle"):
    with rung(HeaterDemand):
        out(Heater)  # COIL_STUCK_HIGH: Heater stays on when Running drops

The rung condition is not the issue. A reached rung that evaluates false still drives its out coil low. The issue is whether the scan reaches the instruction at all.

A coil is safe when its out instructions collectively run on every scan. One out in the main program does that. Mutually exclusive subroutines can also cover the full domain:

Mode = Int("Mode", choices={1: "run", 2: "hold", 3: "stop"})

with rung(Mode == 1):
    call("run")
with rung(Mode == 2):
    call("hold")
with rung(Mode == 3):
    call("stop")  # every Mode value drives Heater: no finding

The state tag needs a closed domain through choices= or min/max. Without one, Mode == 7 remains possible and the lint reports the coil. A Bool discriminator such as Enable/~Enable already has a closed domain. An edge-gated call such as rise(Request) never provides full coverage because the edge is false on nearly every scan.

Target validation

Core ladder lints and target portability checks run separately:

logic.check()
mapping.validate(logic, mode="strict")  # CLICK
hw.validate(logic, mode="strict")       # CircuitPython

The two validate() calls check whether a program can run on that target. They do not also run the ladder lints. See CLICK PLC validation and CircuitPython validation for their rule sets.

mapping.validate(logic) reports CLK_NOP_NO_COIL for a rung whose contacts feed only a NOP (with rung(C1): pass, or a nop() in a branch(C2) beside a coil). CLICK's Syntax Check reports it as C0003. Export writes the rung and warns. pyrung cannot draw a bare wire in parallel with a contact, so CLICK's C0002 "Short circuit error" has no finding.