Repository navigation
str.fields(): awk's $N for one-liners (#959) - #2127
Conversation
ehartford
left a comment
There was a problem hiding this comment.
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 ani64becausetotalis 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:
- Update the docs in the same PR.
AGENTS.md/CLAUDE.mdstill mapawk '{print $2}'toline.split(" ")[1], "exact separator only untilstr.fields()lands (#959)".docs/spec/toolchain/improve_oneliners.mdstill listsfields()as missing (line 96) and as future work (751).
- Replace the magic numbers
43,45,48with'+','-','0'. Char literals compare directly against string bytes ('+' == "+"[0]istrue), and the project rule is no magic-number byte chains. - The awk equivalence needs a caveat. The PR presents
line.fields()[1].parse_i64() ?? 0as 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. - Minor:
Some(0 - acc)can beSome(-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().
9390286 to
04b4afc
Compare
|
Thanks. Split as you suggested: this PR is now
While checking 3, I found that one-liners don't panic there today. For |
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.
04b4afc to
3a997c6
Compare
|
Rebased on |
|
Seed-driven battery GREEN on PR head Ran
Final battery status: Total battery runtime: about 41 minutes. No source changes were made during the run. |
ehartford
left a comment
There was a problem hiding this comment.
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.
…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]>
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 onetrimstrips (' ','\t','\n','\r').printf 'beta 20 y\n' | with -n 'print(line.fields()[1])'prints20.It is an
impl strmethod instd.stringbesidetrim_start/trim_end, so there is no compiler change, and-e/-n/-psee it without ause. OwnedVec[str], likelines()andsplit().Docs, in this PR:
AGENTS.md/CLAUDE.md:awk '{print $2}'isline.fields()[1]andNFisline.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 sayfields()has landed and the genericparse()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, andsplit(" ")againstfields()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)::devgreen; the behavior test passes on stage1;cli-selfhost-one-liner-testsgreen;--debug-allocover 200 rounds offields()reports leak count 0. On1f946c14::gategreen exceptc-migrator-basic-tests(a missing evidence line, "contract param 0: non-null") andno-host-toolchain(unknown type 'c_longdouble'intest/host_toolchain/cimport_stdio.w). Both fail the same way on1f946c14without this change. The battery has not been run. Main has since moved to1917e058(offsetof, D109; consumed map keys, #2265); neither touchesstd.stringor 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, andwith -e 'let a = [1, 2]' -e 'print(f"{a[5]}")'prints0; the same code in a file panics with "index out of bounds" (exit 134). It happens on main too, withsplit(" "). That is #2268.