Skip to content

lexer: skip comment lines wherever newlines are skipped - #209

Open
Harp404 wants to merge 3 commits into
uutils:mainfrom
Harp404:fix-comment-lines
Open

Harp404 wants to merge 3 commits into
uutils:mainfrom
Harp404:fix-comment-lines

Conversation

@Harp404

@Harp404 Harp404 commented Nov 30, 2026

Copy link
Copy Markdown

Fixes #164.

A # comment on a line of its own broke the statement around it when it sat between two statements, after if (...), after {, or inside an argument list:

BEGIN {
    x = 1;
    # set y
    y = 2
}

The lexer skipped the comment text, but the newlines on either side of it came out as separate Newline tokens. The tokens that skip newlines ({, ,, &&, ||, else, do, ...) only skipped the first one. The parser then found a second Newline where it expected a statement and reported "invalid statement start".

The change is in the lexer only:

  • A new comment subpattern (#[^\n]*) is part of ignore_with_nl, so the tokens that skip newlines also skip comment lines.
  • A Newline token takes the blank and comment-only lines that follow it (\n(?:(?&ignore)|\n|(?&comment))* instead of \n+). Runs of newlines separated by spaces now also come out as one token rather than several, which the parser already treats the same way. I updated the expected token lists in lexer_test_newlines_non_posix and lexer_test_collapsible_delimiters for that, and added lexer_test_comment_lines_join_newlines.

# inside strings and regexes is unaffected, since those are lexed as their own tokens.

I compared 24 programs with gawk and they all match. They cover comment lines between statements, at the top of a block, after if (...), for (...) and while (...), before else, inside an argument list, after &&, mixed with blank lines, at the top and bottom of the file, a trailing comment, and # in strings and regexes. A comment after a \ line continuation is still an error, as in gawk. Two things I noticed are left alone here because they fail the same way without comments: do ... while doesn't parse yet, and printf/for (k in a) aren't implemented.

The new test comment_lines_between_statements fails on main and passes with this change. cargo test --workspace passes (275 tests), and cargo fmt and cargo clippy --workspace --all-targets -- -D warnings are clean.

I used Claude Code (Opus 5.5) to help investigate and draft this change; I reproduced the bug and checked the fix myself.

Copilot AI balanced review requested due to automatic review settings November 30, 2026 18:29

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing. Review the Copilot code review billing settings.

@github-actions

Copy link
Copy Markdown

GNU awk testsuite comparison:

Test results comparison:
  Current:   TOTAL: 666 / PASSED: 123 / FAILED: 445 / SKIPPED: 98
  Reference: TOTAL: 666 / PASSED: 121 / FAILED: 447 / SKIPPED: 98

Changes from main branch:
  TOTAL: +0
  PASSED: +2
  FAILED: -2

New test failures (1):
  - getnr2tm

Test improvements (3):
  + fldterm
  + leaddig
  + sortglos

1 similar comment
@github-actions

Copy link
Copy Markdown

GNU awk testsuite comparison:

Test results comparison:
  Current:   TOTAL: 666 / PASSED: 123 / FAILED: 445 / SKIPPED: 98
  Reference: TOTAL: 666 / PASSED: 121 / FAILED: 447 / SKIPPED: 98

Changes from main branch:
  TOTAL: +0
  PASSED: +2
  FAILED: -2

New test failures (1):
  - getnr2tm

Test improvements (3):
  + fldterm
  + leaddig
  + sortglos

Comment thread lexer/src/lib.rs Outdated
Record,
#[regex(r"\n+", accept_expression)]
// Blank and comment-only lines after a newline belong to the same token.
#[regex(r"\n(?:(?&ignore)|\n|(?&comment))*", accept_expression)]

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 upstream comparison shows getnr2tm as a new failure
could you please check whether this change explains it?

@Harp404 Harp404 Dec 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Yes, this change caused it, thanks. Line 52 of getnr2tm.awk is a comment holding a byte that is not UTF-8 (0xC8). The old skip_line callback skipped raw bytes, but the new #[^\n]* subpattern only matches UTF-8 characters. So the newline token that now takes in the following comment lines stopped in the middle of line 52, and the 0xC8 byte became an unexpected token.

Fixed in 9cdcaa1: the subpattern is now #(?-u:[^\n])*, which matches bytes. getnr2tm passes again locally against the gawk 5.3.2 testsuite, and fldterm, leaddig and sortglos still pass. I also added lexer_test_comments_may_hold_non_utf8_bytes, which fails on the previous commit.

Comment thread lexer/src/lib.rs Outdated
#[logos(subpattern identifier = r"[a-zA-Z_][a-zA-Z0-9_]*")]
#[logos(subpattern ignore = r"(?:[ \t\r]|(\\\r?\n))+")]
#[logos(subpattern ignore_with_nl = r"(?:(?&ignore)|\n)*")]
#[logos(subpattern comment = r"#[^\n]*")]

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.

# comments are now described in two places, this subpattern and skip("#", skip_line) above
could they share one?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done in 9cdcaa1. skip_line is gone and the skip is now #[logos(skip(r"(?&comment)", allow_greedy = true))], so the subpattern is the only definition of a comment. logos needs allow_greedy for the [^\n]*, but that only reads to the end of the line, which is the same as what skip_line did with memchr.

Comment thread tests/by-util/test_awk.rs Outdated
}

#[test]
fn comment_lines_between_statements() {

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.

please split this into separate tests (like the ones in the issue), with a loop a failure doesn't say which program broke

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done in 9cdcaa1. There is now one test per program, for example comment_line_after_if_condition, comment_line_between_arguments and hash_in_string_is_not_a_comment.

@sylvestre

Copy link
Copy Markdown
Contributor

thanks for working on this!
The upstream comparison shows getnr2tm as a new failure; please check whether this change causes it (inline comment).

Copilot AI balanced review requested due to automatic review settings December 1, 2026 02:38

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing. Review the Copilot code review billing settings.

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

GNU awk testsuite comparison:

Test results comparison:
  Current:   TOTAL: 666 / PASSED: 124 / FAILED: 444 / SKIPPED: 98
  Reference: TOTAL: 666 / PASSED: 121 / FAILED: 447 / SKIPPED: 98

Changes from main branch:
  TOTAL: +0
  PASSED: +3
  FAILED: -3

Test improvements (3):
  + fldterm
  + leaddig
  + sortglos

@sylvestre

Copy link
Copy Markdown
Contributor

nice:


Test improvements (3):
  + fldterm
  + leaddig
  + sortglos

Comment thread lexer/src/lib.rs Outdated
#[logos(skip(r"(?&ignore)"))]
#[logos(skip("#", skip_line))]
// `[^\n]*` stops at the end of the line, not of the input.
#[logos(skip(r"(?&comment)", allow_greedy = true))]

@Alonely0 Alonely0 Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

allow_greedy hurts perf considerably, since the lexer must go over the whole input to get to an accepting state for each token. The way to do this usually is a callback that performs the lookbehind or greedy checks (like we do with memchr to quickly skip to a delimiter) and bumps the input, so the DFA doesn't scan the (considerably long) strings/comments/etc. This essentially keeps the DFA as a fast path.

What I propose instead is to change skip_line in the original # skip rule to something like this funtion, and then wire through the parser the newline ignoring for all tokens that currently hacked this through ignore_with_nl at the end; i.e., else, do, ||, &&, {, ,, ?, and :. This function only preserves the newlines on lone comments, where they are significant, and we would rely on the parser to ignore newlines instead of those tokens consuming them.

fn skip_comment(lex: &mut Lexer) -> Skip {
    let prev = &lex.source()[..lex.span().start];
    let is_line_comment = prev
        .iter()
        .rfind(|b| !matches!(b, b' ' | b'\t' | b'\r'))
        .is_none_or(|&b| b == b'\n');

    lex.bump(memchr(b'\n', lex.remainder()).unwrap_or(lex.remainder().len()));
    if is_line_comment && let [b'\n', ..] = lex.remainder() {
        lex.bump(1);
    }

    logos::skip(lex)
}

A comment line between two statements, after if (...), or after a , or
{ left an extra Newline token the parser did not expect. Let a Newline
token take the blank and comment-only lines that follow it, and let the
tokens that skip newlines skip comment lines too. Fixes uutils#164.
…es in them

Split the comment tests into one test per program.
Copilot AI balanced review requested due to automatic review settings December 1, 2026 10:34

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing. Review the Copilot code review billing settings.

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

GNU awk testsuite comparison:

Test results comparison:
  Current:   TOTAL: 666 / PASSED: 124 / FAILED: 444 / SKIPPED: 98
  Reference: TOTAL: 666 / PASSED: 121 / FAILED: 447 / SKIPPED: 98

Changes from main branch:
  TOTAL: +0
  PASSED: +3
  FAILED: -3

Test improvements (3):
  + fldterm
  + leaddig
  + sortglos

Comments are skipped by a memchr callback again instead of a greedy
pattern. A comment alone on its line also takes its newline, so comment
lines add no newline token.

else, do, &&, ||, {, ',', ? and : no longer take the newlines after
them; the parser's token stream drops the newlines after them and after
another newline. POSIX mode still refuses a newline after ? and :.
Copilot AI balanced review requested due to automatic review settings December 1, 2026 14:39

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing. Review the Copilot code review billing settings.

@Harp404

Harp404 commented Dec 1, 2026

Copy link
Copy Markdown
Author

@Alonely0 thanks, done in d000c63. I built it on top of @sylvestre's rebase.

  • Comments are skipped by your skip_comment callback again (memchr + bump). allow_greedy and the comment / ignore_with_nl subpatterns are gone, and so are the regex forms of else, do, &&, ||, {, ,, ? and :, which are now plain tokens.
  • The parser ignores the newlines. parser::lex::Lexer drops Newline tokens after any of those eight tokens, and after another Newline. It does this in next/next_if, so none of the call sites needed changing. Merging a run of newlines there means \n+ stays as it is on main, while blank and comment-only lines between two newlines still give a single newline to the parser (e.g. if (1)\n\n # c\n\n print).
  • POSIX still refuses a newline after ? and :. Since those tokens no longer take the newline, parse_ternary_part checks the remainder for a newline or a comment, after blanks and line continuations. The new lexer_test_posix_ternary_parts_end_the_line covers it.
  • The lexer tests now expect the Newline tokens. lexer_test_comment_lines_are_skipped replaces the joined-newline test. There are 2 new end-to-end tests: one with a newline after each of the tokens, and the blank-comment-blank case above.

To check for regressions without the GNU harness (gawk doesn't configure here), I ran all 608 test/*.awk programs from gawk 5.3.2 with main's binary and with this branch, and compared the outputs:

  • No program that matched its .ok on main stops matching.
  • fldterm, leaddig and sortglos now match.
  • 46 others give different output but fail on both. On main they stop at a syntax error inside a comment; with this branch they get past it.

cargo test --workspace, clippy -D warnings and fmt all pass.

On #214: this doesn't cover the do cases. I checked its four tests against this branch, and all four still fail: do i++; while (...) fails with "Expected opening brace", and the braced body with while on the next line fails with "Expected a while statement after a do block". do only takes a braced body, and the newline after the } is not one this change drops. I'll keep #214 for that part.

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

GNU awk testsuite comparison:

Test results comparison:
  Current:   TOTAL: 666 / PASSED: 124 / FAILED: 444 / SKIPPED: 98
  Reference: TOTAL: 666 / PASSED: 121 / FAILED: 447 / SKIPPED: 98

Changes from main branch:
  TOTAL: +0
  PASSED: +3
  FAILED: -3

Test improvements (3):
  + fldterm
  + leaddig
  + sortglos

@Alonely0 Alonely0 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Looks good! Tho notice that both ternary operators ? and : mustn't accept newlines after them in POSIX mode; this is a GNU extension (the lexer had different rules for them depending on mode). Other than that, I don't see any issues, tho will give it a closer look later today.

@Harp404

Harp404 commented Dec 1, 2026

Copy link
Copy Markdown
Author

@Alonely0 thanks! That one should still hold. The lexer refuses it before the parser sees the newline: ? and : are lexed by parse_ternary_part, which in POSIX mode looks past blanks and line continuations, and returns LexingError::non_posix when the next thing is a newline or a comment. Only GNU mode emits the Newline token that the parser then drops.

lexer_test_posix_ternary_parts_end_the_line covers it. With posix_strict, a ?\n b : c, a ? # c\n b : c, a ? b :\n c and a ? b : \t\n c all give an error, while a ? \\n b : c and a ? b : c\n lex cleanly. The existing lexer_test_newlines_posix (should_panic) still passes too.

One caveat, the same as on main: parser::lex::Lexer::new still calls Token::lex(source, false, false) (the TODO there), so --posix doesn't reach the lexer from the CLI yet. The check only applies once that's wired in.

@Alonely0 Alonely0 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice! I mentioned a small clean-up opportunity, but this looks great. Since it came up here, I will be adding some documentation to the lexer to explain the intricacies and footguns in its implementation, so new contributors have an easier time making changes.

Comment thread parser/src/lex.rs
Comment on lines +141 to +149
Token::Newline
| Token::Else
| Token::Do
| Token::BooleanAnd
| Token::BooleanOr
| Token::OpenBrace
| Token::Comma
| Token::QuestionMark
| Token::Colon,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this reads a bit ugly to me. Do you think it'd be cleaner to move it to a method in TokenExt? Like the existing is_*

@Alonely0

Alonely0 commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

@Alonely0 thanks! That one should still hold. The lexer refuses it before the parser sees the newline: ? and : are lexed by parse_ternary_part, which in POSIX mode looks past blanks and line continuations, and returns LexingError::non_posix when the next thing is a newline or a comment. Only GNU mode emits the Newline token that the parser then drops.

lexer_test_posix_ternary_parts_end_the_line covers it. With posix_strict, a ?\n b : c, a ? # c\n b : c, a ? b :\n c and a ? b : \t\n c all give an error, while a ? \\n b : c and a ? b : c\n lex cleanly. The existing lexer_test_newlines_posix (should_panic) still passes too.

One caveat, the same as on main: parser::lex::Lexer::new still calls Token::lex(source, false, false) (the TODO there), so --posix doesn't reach the lexer from the CLI yet. The check only applies once that's wired in.

Oh, you're totally right, I hadn't seen the helper method for it, sorry hahah

(by the way, this reads a bit LLMy. Just FYI, but it is our policy that replies to maintainers should be written by humans, mainly for two reasons: contributors should be able to explain the code without their assistance, and LLM prose is just tiring to read. It is okay if your English is not perfect, mine isn't either :) )

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.

awk: a comment line next to a newline breaks the statement ("invalid statement start")

4 participants