Skip to content

one-liners: -n/-p have no persistent state across lines and no END/last — sums, counts, uniq, tail, last line, regex ranges are inexpressible #957

Closed

Description

@ehartford

What

A sed/awk parity matrix (2026-09-03, seed v0.15.1.7-g54651442e) run as real with -n / with -p one-liners. Eight idioms pass (sed -n A,Bp via nr, sed /pat/d, s/old/new/, s with regex and backrefs, 3i, NR%2, grep -i, regex capture $1). Every failure below is one gap class: a -n/-p snippet runs inside the per-line loop (spec §18.5b.3 shows the desugaring), so a variable it declares is re-created per line, a name it assigns without declaring is "undefined variable", and there is no END position or last binding.

sed '$p'                         with -n 'if last: print(line)'                           → undefined variable `last`
sed -n '/START/,/END/p'          with -n 'if line == "START": inrange = true …'          → undefined variable `inrange`
awk '{s+=$2} END{print s}'       with -n 'total = total + …'                              → undefined variable `total`
awk '!seen[$0]++'                with -n 'if not seen.contains(line): …; seen.insert(…)'  → undefined variable `seen`
wc -l                            with -n 'if last: print(f"{nr}")'                        → undefined variable `last`
tail -n 1                        with -n 'if last: print(line)'                           → undefined variable `last`

-e can express these today, verbosely (var n = 0 / for l in stdin.lines(): … / print after the loop works), so the language is not missing anything — the one-liner modes are. And stdin.lines() already returns the whole input as Vec[str] (lib/std/io.w:59), so END and last cost nothing.

Spec

§18.5b promises line and nr only; it says nothing about state or END, so this is a feature gap, not a compliance bug. Fixing it touches §18.5b.1's binding table and §18.5b.3's desugaring, i.e. Eric blesses the words.

Proposal (least ceremony; awk's model without awk's implicit globals)

  1. Hoist top-level var declarations of a -n/-p snippet out of the loop: var total = 0 in the snippet is declared once, before the first line, and persists — no new syntax, and var seen: HashMap[str, i32] = HashMap.new() covers uniq. The rest of the snippet stays per line.
  2. Bind last: bool (true on the final line) — with the input materialized this is nr == lines.len(). Covers $p, tail -n 1, wc -l, END-style sums.
  3. Optionally -E CODE for a block after the loop (awk's END), if last reads as a trick.

Acceptance: the matrix above lands as cases in the cli-selfhost-one-liner-tests lane (build/selfhost.w), one per idiom, so the parity is a battery invariant, not a memory.

Companions: #958 (file operands and -i), #959 (whitespace fields and integer parsing on str).

Activity

  1. ehartford commented on Oct 25, 2026

    @ehartford
    ContributorAuthor

    Triage 2026-10-25, with v0.15.3.0 (main a261b65): reproduced, and the next step is a spec ruling.

    $ printf 'a\nb\nc\n' | with -n 'if last: print(nr)'
    error: undefined variable
     --> <cli -n #1>:1:4
    rc=1
    

    What the spec says. §18.5b.3 (docs/spec/018_modules.md) defines -n CODE as var nr: i64 = 0 then for line in stdin.lines(): nr = nr + 1; CODE. Under that desugaring a var in the snippet is re-created per line and there is no last, so the compiler conforms and awk '{s+=$2} END{print s}', wc -l and tail -n 1 have no -n spelling.

    The question. Should §18.5b.3 change so that a snippet's top-level var declarations are hoisted out of the loop (state persists across lines) and last: bool is bound (true on the final line)? This is the proposal in improve_oneliners.md item 1. The alternative is to keep -n stateless and point users to -e with a loop over stdin.lines().

    Pre-release if ruled yes: one-liners are a stated priority, and the change is one desugaring in one place.

  2. added this to the post-v0.16.0 milestone on Oct 28, 2026
  3. joshhickson commented on Oct 30, 2026

    @joshhickson
    Contributor

    Some data for the ruling, from the one-liner scoreboard (every one-liner in the two Perl books, 264 tasks; lengths are counted after the program name, measured on 2026-10-09). With -n/-p hoisting top-level var out of the loop and binding last:

    task Perl With today with #957
    wc -l -nE '}{say $.' (14), -e 'say lines.Int' (18) -e 'print(stdin.lines().len())' (31) -n 'if last:print(nr)' (22)
    tail -1 -ne 'print if eof' (18) -e 'let a=stdin.lines();print(a[a.len()-1])' (44) -n 'if last:print(line)' (24)
    longest line -ne '$l = $_ if length($_) > length($l); END { print $l }' (58) -e 'var m="";for l in stdin.lines():if l.len()>m.len():m=l;print(m)' (68) -n 'var m="";if line.len()>m.len():m=line;if last:print(m)' (59)
    number non-empty lines -ne 'print ++$a." $_" if /./' (29) -e 'var n=0;for l in stdin.lines():if l>""{n+=1;print(f"{n} {l}")}' (67) -n 'var n=0;if line>""{n+=1;print(f"{n} {line}")}' (50)

    Across the scoreboard, #957 alone shortens at least 6 of the 264, and 2 come under 1.5x (wc -l against Perl 6, and tail -1). With the other line-mode shorthands from my 10-09 note as well (a bare /re/ matches the line, a bool prints it), 12 get shorter and 4 come under 1.5x.

    The "With today" column is the alternative you name: -e with a loop over stdin.lines().

  4. ehartford commented on Oct 30, 2026

    @ehartford
    ContributorAuthor

    What do you think we should do?

  5. ehartford commented on Oct 30, 2026

    @ehartford
    ContributorAuthor

    What's the most withy thing, consult mission.md

  6. joshhickson commented on Nov 1, 2026

    @joshhickson
    Contributor

    Going by mission.md: bind last, don't hoist var, and let -e code run before and after the -n loop.

    last: yes. The generated loop already holds every line (stdin.lines() is a List[str]), so "this is the final line" is a fact the compiler has. Today you get it only by leaving -n for -e and writing the loop by hand. That's law 1, the same reason line and nr are bound.

    Hoisting top-level var: no. In -n the snippet is a loop body, and a var in a loop body is per-iteration everywhere else in With; hoisting gives the same text a second meaning here. One-liners use the first one: of the 111 scoreboard tasks with an -n/-p spelling, 10 declare a top-level var, and hoisting changes 9 of them. Five (ROT13, case swap, base64 decode) would print accumulated text with no error:

    $ printf 'aB\ncD\n' | with -p 'var s=StringBuilder.new();for c in line.bytes():s.push_char(if is_alpha(c):c^32 else:c);line=s.to_str()'
    Ab
    Cd
    

    Hoisted, that prints Ab and AbCd. The other four read the line in the initializer (a prime check: let n=parse(line);var p=n>1;…) and would stop compiling. Per line and across lines are two meanings, so the programmer spells which one: "a default picks a representation, never a meaning". Nor is it law 11's trade: nothing is refused to protect the programmer, and hoisting changes what working one-liners do. (use already hoists, #2015, but a use means the same wherever it sits.)

    Instead, spell it by position. -e code before the first -n runs once before the loop, and -e code after the last -n runs once after it: awk's BEGIN and END. -e between two -n parts is an error, and leading code runs before nr exists. This changes §18.5b (the one-mode rule, which today refuses the combination with -e, -n, and -p are mutually exclusive; the -n/-p desugarings; the part numbering) and adds battery rows. Explicit -B/-E flags would say the same at the same length, if position reads as too clever.

    with -e 'var m=""' -n 'if line.len()>m.len():m=line' -e 'print(m)'   # longest line: 61
    with -n '' -e 'print(nr)'                                              # wc -l: 20
    with -n 'if last:print(line)'                                          # tail -1: 24
    

    last and code after the loop are different meanings, not two spellings of one: on empty input if last: never fires, so tail -1 prints nothing, while code after the loop still runs, so wc -l prints 0. Against #957 as filed (hoisting plus -E), this costs 5 characters per one-liner that declares state: the -e '' around the declaration.

    I ran each of these, and the hoisted versions, as their desugared programs on today's nightly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions