INTERCAL patterns

Verified patterns for writing non-trivial programs in INTERCAL. Every snippet here was compiled with this repo's bootstrap (src/bootstrap/intercalc.sh) and the behavior observed empirically. Intended as reference for the Phase 4 self-hosted compiler work (src/compiler/stage3.i), where these patterns will need to be generated by codegen.

Zero test

Input: scalar .N. Output: .R = 0 iff .N == 0, else .R = 1.

DO .R <- '.N ~ .N' ~ #1

Why it works: .N ~ .N packs every set bit of .N into the low bits of the result (select-from-self). If .N == 0, no bits are selected, result is 0. Then ~ #1 extracts bit 0. So .R = 1 iff .N != 0.

Verified with .N ∈ {0, 1, 42} → output 0, 1, 1 respectively.

Equality test

Input: scalars .A, .B. Output: .R = 0 iff .A == .B, else nonzero.

DO STASH .1 .2 .3 .4
DO .1 <- .A
DO .2 <- .B
PLEASE DO (1010) NEXT        DON'T NOTE .3 = .1 - .2 (wraps unsigned)
DO .R <- .3
DO RETRIEVE .1 .2 .3 .4

.R == 0 iff the values were equal. For a strict 0/1 predicate, chain with the zero test:

DO .EQ <- '.R ~ .R' ~ #1     DON'T NOTE 0 if equal, 1 if different
DO :20 <- '.EQ $ #1'
DO :21 <- '?:20'
DO .NEQ <- ':21 ~ #1'        DON'T NOTE 1 if equal, 0 if different

Adding two scalars

Input: .A, .B. Output: .S = .A + .B, wraps mod 2^16 via 1009; 1000 raises ICL1999I on overflow.

DO STASH .1 .2 .3 .4
DO .1 <- .A
DO .2 <- .B
PLEASE DO (1000) NEXT
DO .S <- .3
DO RETRIEVE .1 .2 .3 .4

Use 1009 if overflow should not be fatal: .4 == 1 when no overflow, .4 == 2 when overflow.

In-place increment / decrement

DO (1020) NEXT with .1 = N sets .1 = N + 1 (wraps). No 1021 exists; to decrement use 1010 with .2 = #1.

Convert 0/1 boolean to 1/2 selector

Needed for computed RESUME (see "Early exit" below).

Given .B ∈ {0, 1}, want .S = 2 when .B == 0, .S = 1 when .B == 1:

DO :20 <- '.B $ #2'
DO :21 <- '?:20'
DO .S <- ':21 ~ #3'

The other direction (.S = 1 when .B == 0) uses $ #1 instead of $ #2:

DO :20 <- '.B $ #1'
DO :21 <- '?:20'
DO .S <- ':21 ~ #3'

Verified both; result matches the truth table exactly.

COME FROM infinite loop

(200) DO COME FROM (219)
      DON'T NOTE body goes here
      PLEASE DO READ OUT .COUNTER
      DON'T NOTE decrement COUNTER via syslib 1010
(219) DO .99 <- #0
      PLEASE DO GIVE UP     DON'T NOTE unreachable; loop never exits on its own

Each time (219) executes, control jumps to the statement AFTER (200) (the body start). Verified by running and observing the counter underflow from 0 to 65535 and continue decrementing.

To make the loop terminate: abstain (200). Once (200) is abstained, the COME FROM no longer fires and (219) falls through to the statement after it.

Early exit / unwind ("two-way branch")

RESUME N pops N entries from the NEXT stack and returns to the N-th popped address (the oldest, furthest-back). This is the language's only mechanism for conditional control flow in the same frame.

(A) DO COME FROM ...
    DO BODY
    DO .SEL <- 1-or-2
    DO (X) NEXT            DON'T NOTE push addr-after-this
    DO (Y) NEXT            DON'T NOTE push addr-after-this
    PLEASE DO RESUME .SEL  DON'T NOTE when .SEL=1, return to the most recent NEXT;
                           DON'T NOTE when .SEL=2, return 2 levels up (the caller of A).

Important caveat observed empirically: (X) and (Y) both execute sequentially if they use RESUME #1 to return normally. The branching happens only when the targets do NOT return normally (typical: DO FORGET #1 to drop the NEXT push, then DO RESUME #1 to unwind the caller's stack instead). See src/syslib/syslib.i label 1000 for the canonical usage.

This pattern cannot select one of two code branches in the same scope, it unwinds to an ancestor. For same-scope conditional execution, use the ABSTAIN pattern below.

Conditional ABSTAIN (same-scope if-then)

To run statement S only when .COND == 1:

  1. Place S with a label (S_LABEL).
  2. Place a companion (GUARD) DON'T ABSTAIN FROM (S_LABEL) that starts abstained (DON'T makes a statement initially inactive).
  3. When you want S to fire on the NEXT iteration, DO REINSTATE (GUARD). On the next visit, (GUARD) runs and abstains S_LABEL, preventing S from firing THAT iteration, wait, that's backwards.

The cleaner shape (inverse logic):

  • (S_LABEL) DO STATEMENT: runs every iteration by default.
  • To prevent it running: DO ABSTAIN FROM (S_LABEL).
  • To let it run again: DO REINSTATE (S_LABEL).

But we need the ABSTAIN/REINSTATE calls themselves to be conditional, which recurses the problem. The fully general solution requires the COMPUTED RESUME pattern wrapping each conditional ABSTAIN call; in practice this is verbose (~10 statements per conditional).

Loop with break

Given the above, a bounded loop follows this shape:

(LOOP) DO COME FROM (LOOP_END)
       DO <body>
       DO <decrement-or-advance>
       DO <check-termination>   DON'T NOTE compute .SB = 1 if should break
       DO <if .SB, abstain (LOOP)>
(LOOP_END) DO .99 <- #0

Because the "if .SB, abstain" step requires the unwind-based computed RESUME, the realistic minimum size of this construct is ~20 statements including the politeness-padding needed to stay within [1/5, 1/3].

Practical recommendation

For stage3.i, prefer:

  • Unrolled operations where the iteration count is small and known.
  • Calling syslib routines that already encapsulate loops internally (arithmetic, bit operations).
  • Avoiding loops entirely until a dedicated "loop intrinsic" can be added as a compiler feature and implemented once in assembly.

When an actual loop is unavoidable (e.g., scanning 60000-byte source), the expected cost is ~30 statements of scaffolding around a small body, still feasible but worth factoring into the compiler structure.

Empirically: the unwind dance fails at top level

Several attempts at the standard (NEXT_A) (NEXT_B) (RESUME .sel) pattern revealed that it ONLY works when there are at least N pending NEXT-stack entries, where N is the maximum value of .sel. At top level of _main, the NEXT stack is empty, so any RESUME N (N >= 1) immediately fires ICL632I PROGRAM ENDED VIA RESUME INSTEAD OF GIVE UP.

Even inside a function, the pattern is fragile: (801) at the first NEXT always wins because it FORGETs its own push and unwinds. The second NEXT and the RESUME .sel line are unreachable in the normal flow. Empirically verified by testing syslib label 1000 with .1=#65535, .2=#1: it should error on overflow per the spec but actually returns silently, exit 0, no ICL code. The (1801) "no overflow" path always wins; the (1802) error path is dead code.

So the syslib's promised "error on overflow" for 1000 is documentation-only. Behavior matches 1009 (silent wrap).

Conditional ADD without a branch

A pattern that DOES work and avoids the conditional execution problem entirely:

DON'T NOTE compute .B = 1 if .A == .CMP else 0
DO STASH .1 .2 .3 .4
DO .1 <- .A
DO .2 <- .CMP
PLEASE DO (1010) NEXT          DON'T NOTE .3 = .A - .CMP (wraps)
DO .D <- .3
DO RETRIEVE .1 .2 .3 .4
DO .Z1 <- '.D ~ .D'             DON'T NOTE pack any set bit to LSB
DO .Z <- '.Z1 ~ #1'             DON'T NOTE 0 if .D=0, 1 otherwise
DO :T1 <- '.Z $ #1'             DON'T NOTE flip via mingle+xor: .B = NOT .Z
DO :T2 <- '?:T1'
DO .B <- ':T2 ~ #1'             DON'T NOTE .B = 1 if .A==.CMP, 0 otherwise
DON'T NOTE then unconditionally accumulate
DO STASH .1 .2 .3 .4
DO .1 <- .COUNTER
DO .2 <- .B
PLEASE DO (1000) NEXT           DON'T NOTE .COUNTER += 0 or 1
DO .COUNTER <- .3
DO RETRIEVE .1 .2 .3 .4

This is what stage3.i Stage 3.1.d uses to compute "is first byte equal to 'D'" without any branch instruction. ~15 statements per equality test, but no abstain dance, no unwind, no branch needed.

Status of the stage3.i loop work

Three attempts have been logged. Each ended at the same blocker: a clean conditional break in INTERCAL needs either a multi-statement abstain dance with computed REINSTATE, or the unwind pattern wrapped in a function with at least one ancestor frame. Both work in principle; both require careful design more than translation from a plan.

The pragmatic decision documented in TODO.md and the project status memory: the v0.1 release ships with the MVP template-passthrough self-hosted compiler (functionally complete for all 25 test programs). stage3.i continues to evolve via feature-by-feature unrolled additions (3.1.a byte count, 3.1.b first byte, 3.1.c last byte, 3.1.d is-first-D boolean...). Real loops with breaks deferred to v0.2+.

Politeness budget

Every statement that is DO, PLEASE, PLEASE DO, DON'T, or PLEASE DON'T counts. That includes DON'T NOTE comments.

Rule (enforced only when stmt_count >= 5):

  • polite * 5 >= stmt_count (at least 1/5 polite)
  • polite * 3 <= stmt_count (at most 1/3 polite)

tools/lint_intercal.sh computes this statically. tools/pipeline_dump.sh prints the exact count and verdict for a given source.

Writing safe expressions

  • Never nest '...' inside another '...'. Never nest "..." inside another "...". Sparks and rabbit-ears MUST alternate.
  • When an expression would require same-type nesting, split into multiple statements using an intermediate twospot variable:
DO :TMP <- '?:INPUT'
DO .OUT <- ':TMP ~ #1'

This is strict; the bootstrap rejects bad nesting at parse time.

STASH/RETRIEVE discipline

Before calling a syslib routine, STASH every .1-.4 / :1-:4 that you need to preserve. After the call, RETRIEVE them immediately. Do not STASH inside a loop without a matching RETRIEVE, the stash stacks grow without bound.

DO STASH .1 .2 .3 .4
DO .1 <- .X
DO .2 <- .Y
PLEASE DO (1000) NEXT
DO .RESULT <- .3
DO RETRIEVE .1 .2 .3 .4

Expected gotchas (observed, documented in bugs_learned)

  • PLEASE NOTE executes as an UNKNOWN statement and triggers ICL000I at runtime. Use DON'T NOTE for comments.
  • syslib.i must be APPENDED to source, not prepended. If prepended, syslib code runs before your program.
  • DON'T is a single token with the apostrophe (byte 0x27). The tokenizer treats it as a keyword.
  • Assigning a 32-bit expression to a 16-bit scalar raises ICL275I at runtime.