Skip to content

Read #delimit cr after a Mata end, keep continued mata: lines as written under #delimit ;, end string input at a row with extra fields, and read Unicode program names - #430

Merged
jbearak merged 8 commits into
mainfrom
t3/lexer-parser-formatter-fixes
Nov 19, 2026

Conversation

@jbearak

@jbearak jbearak commented Nov 19, 2026 •

Copy link
Copy Markdown
Owner

A cold review of #428 found eight more lexer, parser and formatter bugs, all reproducible on main. The worst ones:

  • #delimit cr right after a Mata block's end was ignored, so the rest of the file became one statement.
  • Format Document moved a // comment line inside a continued mata: statement to column one, where Stata reads it as code.
  • An input of string variables without end swallowed the code after it.

This PR fixes them. I checked each language question in StataMP 18 before writing the rule.

Fixed

  • S2: #delimit after a Mata end. Under #delimit ;, a Mata block's bare end ends the statement, so #delimit cr (or #d cr) on the next line is a directive. I checked every token that can end a statement. A Python block's end, a program's end, input's end and a } each need their ;, so Stata reads on past them. Sight already did this and still does. One lenient case: a bare mata line under ; (not an opener in Stata, which reads one statement to the next ;) is still read as a block opener, so #delimit cr after its end is now a directive.

  • S1: formatting a continued mata: statement. Under #delimit ; the source-preserving formatter now leaves the later lines of a one-line mata: statement as written. A // line inside the statement is a comment when indented and code at column 0, and this holds after a /// join too. Under #delimit cr, after a /// join, the line is a comment at either indent, and a /// inside a string does not join ("mismatched quotes"). So the lines still move with their first line there, as since Move the lines continuing a one-line mata: statement with it once, not one level further on every format #400. Python one-liners already stayed as written, and * lines stay as written too.

  • S3: string input without end. A row that doesn't fit the declared variables now ends the data only when the block's end is accounted for some other way. A row doesn't fit when it has more fields than variables, or text where a numeric variable needs a number (round 2's rule). At such a row the lexer looks ahead to the next row whose first word is end:

    • If a row before that end (this row included) opens a block that needs its own end, that end belongs to the block. The blocks are: a program definition (checked by the shared program-header recognizer), a mata or python block, or another input.
    • If no end follows at all, nothing closes the data.

    In either case the data ended before the row, which is code. Otherwise the end closes this data and the row is data, which is how Stata reads it.

    • stringobs and input-no-end.do: the data ends after Paris (or 10), and the local, the program and the rest are code.
    • input x / 1 2 / end, input str20 name / Mary-Ann Smith / Los-Angeles / end, and input x / 1 / abc / 2 / end: 0 issues, and both formatter modes leave the text unchanged on two passes. On main the third block reported a false Unexpected "end" under round 2's numeric rule; on this PR's first push the first two did too.
    • Fields are counted the way Stata's input counts them: a run of non-blanks, a quoted value, or , or / on its own. Treating / as a field is new; round 2 read it as a blank.
    • The lookahead runs once per data block: later rows reuse a "data" answer. The first word is read without crossing blank lines. With 80,000 blank lines after an over-wide row, lexing takes 4.6 ms (877.9 ms with a regex that crossed them).
    • src/utils/input-data.ts and docs/cli.md describe the rule.
    • Still ambiguous: a row that fits is always data, so a short command under an input without end that declares enough string variables is read as data. And a row that doesn't fit is data whenever an end follows that no block Sight recognizes claims, even if that end closes something opened behind a prefix (quietly program define).
  • S4 and S14: quoted input fields. Under #delimit ; a quoted field may span lines, and the record ends at the ; after its closing quote. A ; inside a compound quote still ends the record, as in Stata. A quote that nothing closes ends at the end of its line. The scanner reads each character once, plus at most one scan to the end of the file per kind of quote.

  • S6: Unicode program names. Stata names may start with any Unicode letter or _ and continue with letters, digits, numbers, combining marks or _. src/utils/stata-name.ts holds that definition. The lexer's word scanner and the program-header recognizer now both use it. Before, café was lexed as caf + é.

  • S12: plugin. It declares a plugin only as an option of its own after the comma, not inside another option's parentheses.

  • S9 (AST mode): subscripts in assert. assert takes an expression, so x[`weight'] stays a subscript. In a varlist, a bracket is still a weight. display already read its arguments as expressions: AST mode keeps display x[`weight'] as written.

  • S15: strings under #delimit ;. The compound fixture is not valid Stata. A ; inside a compound quote ends the statement under #delimit ;, and Stata says "invalid syntax". Sight now matches that: a compound string spans lines (which used to be an error) and stops at a ;. A simple string still protects ;.

    • Recovery rule for badquote: a simple string that no later " closes ends at the end of its line, or at a ; that is the last code on that line. The error is still reported. Stata reads such a string to the end of the file. Sight's choice changes only files that are already broken, and it keeps the later statements. In such a file the formatter may reindent lines that Stata would read as part of the open string.
    • Inside Mata and Python blocks, strings keep their old reading. Stata reads a Mata block under #delimit ; line by line, where ; in a string is text.

Not fixed (outside this PR's files)

  • src/providers/symbols.ts:678 matches program names with \b…\b, which fails for names that start with a Unicode letter.
  • src/console/automation/mode-tracker.ts:30 and the TextMate grammar still use ASCII-only names.

Stata 18 log lines

. #delimit ; / mata; / x = 1 / end / #delimit cr      -> delimiter now cr; T1 42 (also #d cr)
. program r3lp_p2; ... 2. end / > #delimit cr          -> joined to the next ; (program end needs ;)
. input v; 1; 2; 3. end / > #delimit cr ...           -> unexpected end of file
. python; >>> end / >>> > #delimit cr                 -> end statement missing
. if 1 {; ... } / > #delimit cr                        -> code follows on the same line as close brace
. mata: u = 1 / > // c / > + 2;  (indented)            -> u = 3
. mata: t = 1 / > // c / > + 2;  (column 0)            -> invalid expression r(3000)
. mata: w = 1 /// / > // c / > + 2;  (column 0)        -> invalid expression r(3000)
. mata: x = 1 /// / > // a comment  (cr, column 0)    -> x = 1
. mata: s = "a ///   (cr)                              -> mismatched quotes
. input str10 a str10 b: x, y | x/y z | Paris France Extra -> a=x b=, | a=x b=/ | Paris France
. input x y: 3/4 ; 5 / 6                               -> '/' cannot be read as a number
. input x / 1 / abc / 2 / end                          -> 'abc' cannot be read as a number; x = 1, 2
. input x / 1 2 / end                                  -> x = 1
. input str20 name / Mary-Ann Smith / Los-Angeles / end -> Mary-Ann, Los-Angeles
. set obs 1 / input str5 city / Paris / local n = _N   -> n is 1
. input str20 note double amount; "Long / label" 42;   -> note "Long label", amount 42
. input str20 s; `"a; / 3. b"';                        -> two records
. program π / café2 / _é / x½                          -> defined and run;  program ½x -> invalid name
. program define r3lp_pp, properties(plugin) ... end   -> body ran
. assert x[`weight'] == 2                              -> passes; assert x == 2 [`weight'] -> weights not allowed
. local txt `"one;                                     -> invalid syntax
. local b `"p / > q"';  display                        -> B[p q]
. mata; s = "a;b" / t = `"c;d"' / u = "e               -> a;b, c;d, mismatched quotes (on its own line)

Fixture probes (main → this branch)

fixture main this branch
mataend result' is not defined; one command #delimit cr…` 0 issues; directive, macro, display
fm_mata_cmt SP output moves // to column 0; check warns slashes_mid_statement // add the correction kept; 0 issues
stringobs n' is not defined; input runs through end` data Paris; local, program, display; 0 issues
input x / 1 / abc / 2 / end Unexpected "end" one input through end; 0 issues
dataquote2 Unexpected "end" one input with data "Long\nlabel" 42; 0 issues
prpi Unexpected "end" one program node; 0 issues
wtassert AST assert x == 1 [weight']` AST assert x[weight'] == 1`
compound 1 error (unclosed compound string) the same, and Stata agrees ("invalid syntax")
badquote 1 error, 2 undefined-macro warnings; the string swallows the rest 1 error; four separate statements

Corpus (3,780 base ados)

$ bun cdiff.ts chk-final2.json chk-r3lp.json 40
chk-final2.json 30133 chk-r3lp.json 30133
added {}
removed {}
$ SIGHT_TEST_LOG=0 bun fmt.ts <worktree> r3lp
r3lp source-preserving loss 0 nonidem 0 err 0 slow 0
r3lp ast loss 2366 nonidem 16 err 0 slow 0

On the first push, a file-by-file comparison with main found 0 differences in parse shape, source-preserving output and AST output. After the refinement, the corpus check and formatter run above give the same numbers.

Proof

  • tests/unit/lexer-parser-review-round3.test.ts has 38 tests, with a second formatting pass in both formatter modes. On main (with imports missing on main stubbed), 20 fail and 18 pass, so each fixed item has at least one test that fails there. The 18 that pass are guards. On this PR's first push, the refined input tests "is data when nothing else claims the end" and its AST-mode formatting test fail, as does round 2's restored quietly input x / 1 2 / end test. The scaling tests count source reads, indexOf included: 4× the input gives under 5× the reads.

  • Send to Stata: bun test tests/unit/send-to-stata tests/property/send-statement-step-through.prop.test.ts gives 252 pass.

  • Each gate run on its own, all pass:

    • check:line-endings
    • typecheck
    • bun test ./tests: 10291 pass, 0 fail
    • lint
    • test:ci: 10303 + 2 pass

    On the first push, one test:ci run failed macro-completion-context.prop.test.ts "cursor inside block comment" with the counterexample ["*/","_",7]. The generator can put */` inside the comment, and main returns the same result for that input. The rerun passed.

…delimit ; as written, and end input data at a row with more fields than variables
…d end a string that nothing closes at its line
@coderabbitai

coderabbitai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

Next included review available in 29 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available. Your 86 included PR review attempts over the past 7 days set your current allowance at 1 review per hour.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Team
  • Run ID: 6c8ad1ce-4a30-47fc-aa68-9c0ba91d0e7e
Commits

Reviewing files that changed from the base of the PR and between 9d28182 and a219818.

Files selected for processing: 8

  • docs/cli.md
  • src/lexer/index.ts
  • src/parser/index.ts
  • src/providers/formatter.ts
  • src/utils/input-data.ts
  • src/utils/program-definition.ts
  • src/utils/stata-name.ts
  • tests/unit/lexer-parser-review-round3.test.ts
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment thread src/lexer/index.ts Fixed
…sions

CodeQL flagged the two first-word patterns and the mata/python tail
pattern as polynomial on uncontrolled input. One bounded pass from the
row's start to its end reads the same things.
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