Skip to content

str.fields(): awk's $N for one-liners (#959) - #2127

Merged
ehartford merged 1 commit into
withlang-dev:mainfrom
joshhickson:josh/one-liner-fields
Oct 10, 2026
Merged

ehartford merged 1 commit into
withlang-dev:mainfrom
joshhickson:josh/one-liner-fields

Conversation

@joshhickson

@joshhickson joshhickson commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Part of #959: whitespace fields. The integer parse moves to its own PR, as the generic s.parse() from the review.

  • str.fields() -> Vec[str]: runs of whitespace separate fields, and leading, trailing or repeated blanks make no empty field (split(" ") gives "" between two spaces). The whitespace set is the one trim strips (' ', '\t', '\n', '\r'). printf 'beta 20 y\n' | with -n 'print(line.fields()[1])' prints 20.

It is an impl str method in std.string beside trim_start/trim_end, so there is no compiler change, and -e/-n/-p see it without a use. Owned Vec[str], like lines() and split().

Docs, in this PR:

  • AGENTS.md/CLAUDE.md: awk '{print $2}' is line.fields()[1] and NF is line.fields().len(), with the caveat that a line with too few fields panics (D71) where awk gives an empty field or 0.
  • docs/spec/toolchain/improve_oneliners.md: gap 3, the cheat-sheet note and the close-out list now say fields() has landed and the generic parse() is what remains of str: no parse() typed by use — a field cannot become a number (fields() landed) #959.

Tests:

  • test/behavior/behav_959_str_fields.w: awk input, mixed blanks, an empty, an all-blank and a one-field string, a CRLF line, and split(" ") against fields() on a double space. On main it fails to compile (unknown method 'fields' for type '&str').
  • cli-selfhost-one-liner-tests: awk '{print $2}' and a per-line field count.

Checked on Linux x86_64 (WSL2), seed and SDK from the locks. On 7d729c2c (main): :dev green; the behavior test passes on stage1; cli-selfhost-one-liner-tests green; --debug-alloc over 200 rounds of fields() reports leak count 0. On 1f946c14: :gate green except c-migrator-basic-tests (a missing evidence line, "contract param 0: non-null") and no-host-toolchain (unknown type 'c_longdouble' in test/host_toolchain/cimport_stdio.w). Both fail the same way on 1f946c14 without this change. The battery has not been run. Main has since moved to 1917e058 (offsetof, D109; consumed map keys, #2265); neither touches std.string or the one-liner path, and the branch merges onto it cleanly.

Found while writing the caveat, not changed here: in with -e/-n, indexing past the end does not panic. printf 'one\n' | with -n 'print(line.fields()[1])' prints an empty line with exit 0, and with -e 'let a = [1, 2]' -e 'print(f"{a[5]}")' prints 0; the same code in a file panics with "index out of bounds" (exit 134). It happens on main too, with split(" "). That is #2268.

@ehartford ehartford left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. str.fields() is the right shape; parse_i64 needs to change.

Maintainer ruling: parse_i64 is not Withy. A type spelled into a method name is the programmer writing what the compiler can decide. Make it one generic s.parse() returning Option[T], with T taken from its use, the way numeric and collection literals take their type from use (D88, D89, D93):

  • total = total + (x.parse() ?? 0) parses an i64 because total is one;
  • a typed binding fixes it: let n: i32 = x.parse() ?? 0;
  • s.parse[i64]() spells it when nothing decides.

That needs a parse trait the integer types implement (floats later), plus Sema typing the call from what its use demands. So it's a compiler change, not only a std.string addition. The parsing logic itself is correct: it gave the right answer on every case we tried, including the ones your test doesn't cover (-0, a lone +, a 20-digit overflow, 007), and it carries over as the i64 implementation.

Also, in this PR:

  1. Update the docs in the same PR.
    • AGENTS.md/CLAUDE.md still map awk '{print $2}' to line.split(" ")[1], "exact separator only until str.fields() lands (#959)".
    • docs/spec/toolchain/improve_oneliners.md still lists fields() as missing (line 96) and as future work (751).
  2. Replace the magic numbers 43, 45, 48 with '+', '-', '0'. Char literals compare directly against string bytes ('+' == "+"[0] is true), and the project rule is no magic-number byte chains.
  3. The awk equivalence needs a caveat. The PR presents line.fields()[1].parse_i64() ?? 0 as awk's $2 + 0, but on a line with fewer than two fields [1] panics (D71: indexing past the end panics), while awk gives 0. The cheat sheet should say so.
  4. Minor: Some(0 - acc) can be Some(-acc).

fields() returning owned Vec[str] is right: Vec[&str] is refused today ("ephemeral references cannot be stored in generic containers"), and it matches lines() and split().

@joshhickson
joshhickson force-pushed the josh/one-liner-fields branch from 9390286 to 04b4afc Compare October 8, 2026 19:24
@joshhickson joshhickson changed the title str.fields() and str.parse_i64(): awk's $N and $N + 0 for one-liners (#959) str.fields(): awk's $N for one-liners (#959) Oct 8, 2026
@joshhickson

Copy link
Copy Markdown
Contributor Author

Thanks. Split as you suggested: this PR is now fields() only, rebased on 7d729c2c, and the generic s.parse() will be its own PR. Your fixes:

  1. Docs: the AGENTS.md/CLAUDE.md awk line now uses line.fields()[1], and improve_oneliners.md no longer lists fields() as missing (gap 3, the cheat-sheet note, and item 6 of the close-out list).
  2. and 4. ('+'/'-'/'0', Some(-acc)): these were in parse_i64, so they go into the parse PR.
  3. The cheat sheet now says a line with too few fields panics (D71) where awk gives an empty field or 0.

While checking 3, I found that one-liners don't panic there today. with -n 'print(line.fields()[1])' on a one-field line prints an empty line and exits 0, and with -e 'let a = [1, 2]' -e 'print(f"{a[5]}")' prints 0. In a file, both panic. That is #2268.

For parse(), I looked at what Sema has now. A result-only type parameter is inferred only for a free generic call that is the whole value (bind_unbound_type_params_from_result). A generic method with nothing bound is "cannot infer". ?? gives its left side no expected type, and + gives a non-literal operand none. Also, s.parse[i64]() is the turbofish that #598 rules out (err_generic_fn_turbofish.w). So the PR needs four things: (1) a method's type parameter bound from the expected result, (2) ?? passing Option[E] to its left, (3) total + (x.parse() ?? 0) passing total's type to the right, and (4) an exception to #598 for parse[T](), or should it be let n: i64 = … there instead? Is that the scope you have in mind, and is (4) OK?

fields() splits on runs of whitespace (the ASCII set trim strips), with no
empty field for leading, trailing or repeated blanks: the awk default that
split(" ") is not. Owned Vec[str], like lines() and split(). An impl str
method in std.string, so -e/-n/-p see it with no use.

The AGENTS.md/CLAUDE.md cheat-sheet maps awk '{print $2}' to
line.fields()[1] and NF to line.fields().len(), with the caveat that a line
with too few fields panics (D71) where awk gives an empty field or 0.
improve_oneliners.md no longer lists fields() as missing.

Test: behav_959_str_fields.w (fails to compile before: unknown method
'fields' for type '&str'). cli-selfhost-one-liner-tests gains
awk '{print $2}' and a per-line field count.
@joshhickson
joshhickson force-pushed the josh/one-liner-fields branch from 04b4afc to 3a997c6 Compare October 10, 2026 00:30
@joshhickson

Copy link
Copy Markdown
Contributor Author

Rebased on 7ecc120a for D118: fields() now returns List[str], and the improve_oneliners.md line that conflicted with the rename now says List.sort. Checked on 7ecc120a (Linux, pinned seed): behav_959_str_fields.w passes on stage1 and on the release build, and cli-selfhost-one-liner-tests is green. Main has since moved to 864e43b0; none of those five commits touch these files.

@ehartford

Copy link
Copy Markdown
Contributor

Seed-driven battery GREEN on PR head 3a997c61b95a277d3d94bcfeb66f2b5d7e59e45d, in a clean isolated checkout on macOS arm64.

Ran src/main run tools/battery.w with the seed pinned by seed.lock (nightly-20261009-local-2-1140e66035cc) and the matching SDK pinned by sdk.lock.

  • Gate: PASS, 160 executed targets, 1,111 seconds.
  • UAT: PASS, 11 scenarios passed, 1 Windows-only scenario skipped, 28 seconds. The runner also recorded a manual visual check for the raylib scenario; that visual check was not independently verified.
  • Battery checks: PASS, 84 executed targets, 1,309 seconds.
  • Fixpoint: stage2 == stage3 across all 16 compiler units.
  • Drop/move audits, all 1,737 behavior fixtures (including behav_959_str_fields.w), and cli-selfhost-one-liner-tests: PASS.
  • Current test evidence recorded; last-green evidence archived and published by the battery.

Final battery status:

3a997c61b /Users/eric/with-pr-2127-battery
gate rc=0 wall=1111s
uat rc=0 wall=28s
battery-checks rc=0 wall=1309s
GREEN
BATTERY_DONE

Total battery runtime: about 41 minutes. No source changes were made during the run.

@ehartford
ehartford marked this pull request as ready for review October 10, 2026 02:32

@ehartford ehartford left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The earlier requested changes are addressed: this PR is scoped to fields(), the documentation and short-line caveat are updated, and parsing is deferred to its own PR. Reviewed this head and ran the pinned-seed battery: gate, UAT, fixpoint, audits, behavior tests and CLI one-liner tests all passed. Battery evidence is posted above.

@ehartford
ehartford merged commit d7399d8 into withlang-dev:main Oct 10, 2026
ehartford added a commit that referenced this pull request Oct 27, 2026
…emands (#959, D165) (#2752)

`str` had no parse method: `f[1].parse()` was "unknown method 'parse'
for type '&str'", so a field could not become a number. `parse[T:
Parse]() -> Option[T]` takes its type from its use, as Eric set in the
#2127 review. Two Sema gaps stood in the way (the third, the `??`
carrier hint, landed as #2724):

- check_generic_method_call returned before checking a generic method
  of a builtin owner (`type_decl_nodes` has no `str`), so the call
  reached MIR uninstantiated. A builtin owner now has no type parameters
  of its own.
- a method type parameter no argument mentions was never bound from
  the demand on the result, so `let n: Option[i64] = cell.get()` was
  "cannot infer generic method type parameter". It is now, as for a free
  generic function.

Parsing is strict (None unless the whole text is one in-range value):
the integer types parse sign and digits; f64 validates the text and
reads strtold's correctly rounded double through rt_core. f32 waits for
its own correctly rounded parse.

Landing str.parse broke `text |> parse` pipelines naming a program's
own `fn parse` (behav_pipeline_match, spec_ss09_7_pipeline_match):
check_pipeline committed to a method on existence alone, bound
str.parse[T], and died "cannot infer 'T'". A generic method is now
applicable at a stage only when the stage can instantiate it (§9.6,
D165): every type parameter named by a parameter type, or bound by the
demand on the stage's result (asked speculatively, substitution
restored). Otherwise, when a visible free function shares the name, the
stage is that function. Verified matrix: demand-bound stage takes the
method, undemanded stage takes the program's parse, no free function
keeps the loud cannot-infer error, `parse[i64]()` spells it.

The census rise that parked the branch was its own ceremony: sixteen
`Some(...)` wrappers at Option demands in the new string.w code (now
bare values, D103) and two typed field lets in the new Sema code (now
inferred). Counts return to main's (plain-bits 416, the D144 allowance
ceiling; some-at lib 1, src 7).

Tests: behav_959_str_parse_by_use, behav_959_generic_method_typed_by_result
(both fail pre-fix on the installed compiler); the two pipeline_match
fixtures are the collision regression. Delegated under D98 as D165
(renumbers the unmerged fix-959 branch's D160).

Co-authored-by: Eric Hartford <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants