You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
in editorRelates to code editing or language featuresis enhancementAn enhancement or improvement that should be listed in release notes but is not a bug fix.
When my parentheses are off while writing Dart code, it's not clear where I should add or remove them. It can be frustrating trying to debug.
(Making things worse, VSCode doesn't add parenthesis when there's already a parenthesis to the right of a cursor. It often happens that I do not notice that a parenthesis that I meant to add wasn't added because of this.)
Please make it easier to find where to put a missing parenthesis.
Reacted by Cedric, Kristen McWilliam, Victor and Felipe Morschel
One way to make it clearer would be to be able to have dartfmt run up until the first error. Right now dartfmt just doesn't run when there are analysis errors, but dartfmt-ing everything up to the first error might help me sort out parenthesis/brace problems through indents?
I'm not sure if we could reliably format up to the first error since truncating there would likely also be invalid code and rejected by dartfmt.
Although I wonder if we could try auto-inserting them at the location where there are "expected )"-style errors, then re-parse (and repeat) to see if we can end up with valid code?
Something similar was discussed for semicolons at dart-lang/sdk#45427, though there were some ambigious cases. If we're able to only do it if it produces valid code, then that might cut out some of the issues (although it may also narrow the number of cases where it works too).
Additional context from #3344 ("Add the ability to automatically insert missing } and )"):
If you change some code the beginning ( and { are easily traceable. But if there is a missing end ) or } it is a nightmare to find which one is the missing pair.
Since you have all the beginning ( and { is it possible to kind of automatically match them and if there is one missing add it automatically.
I did some prototyping to see how fast and reliable automatic bracket/parenthesis recovery could be using the analyzer's token stream and parser. Full code and detailed results are in DanTupBot/dart_bracket_recovery_experiment (tested against ~1,400 single and multi-bracket mutations across 15 Flutter Material files).
Strategies Tested
Strategy 1 (Raw Syntactic Sandbox): Inserts synthetic closers (or deletes unmatched closers) suggested by the scanner/parser and accepts the edit if re-parsing produces 0 syntax errors and 0 synthetic tokens.
Strategy 2 (Guarded Syntactic Sandbox): Excludes {} blocks, also deletes extra ) / ] flagged with Expected ';' mid-expression, and skips ambiguous ( / [ insertions where the unclosed group spans across commas, .property chains, or operators.
Strategy 3 (Hybrid Syntactic + Semantic Hints): Combines Strategy 2 with the analyzer's existing semantic diagnostics (undefined_named_parameter, extra_positional_arguments, undefined_getter) to safely recover nested widget/function calls where an inner unclosed ( swallowed outer arguments, without needing extra resolution passes.
Single-Bracket Results (on () and [])
Strategy
Avg Time
Fixed (Exact)
Broke Code (Shifted*)
Left Unfixed
Precision (When Applied)
1. Raw Syntactic
1.14 ms
71.6% (65.9% missing, 77.6% extra)
8.6% (17.5% missing, 0% extra)
19.8%
89.2%
2. Guarded Syntactic
1.93 ms
63.1% (35.3% missing, 91.0% extra)
0.0% (0% missing, 0% extra)
36.9%
100.0%
3. Hybrid
3.01 ms
67.3% (43.5% missing, 91.0% extra)
0.0% (0% missing, 0% extra)
32.7%
100.0%
*("Broke Code / Shifted" means the result had 0 syntax errors, but the bracket was placed in a different valid location than the original code.)
We also tested pasting code with multiple missing/extra brackets at once (runs of 2, 3, and 4+ adjacent ) / ], swapped ) <-> ], and multiple independent errors in the same file):
Scenario
Total
Fixed (Exact)
Broke Code (Shifted)
Left Unfixed
Precision (When Applied)
Avg Time
Contiguous Missing (2 adjacent )/])
138
48.6% (67)
0.0% (0)
51.4%
100.0%
4.19 ms
Contiguous Missing (3 adjacent )/])
33
30.3% (10)
0.0% (0)
69.7%
100.0%
8.02 ms
Contiguous Missing (4+ adjacent )/])
15
33.3% (5)
0.0% (0)
66.7%
100.0%
8.13 ms
Contiguous Extra (2 adjacent )/])
138
94.9% (131)
0.0% (0)
5.1%
100.0%
10.51 ms
Contiguous Extra (3 adjacent )/])
33
93.9% (31)
0.0% (0)
6.1%
100.0%
31.90 ms
Contiguous Extra (4+ adjacent )/])
15
93.3% (14)
0.0% (0)
6.7%
100.0%
41.42 ms
Mismatched Closer () <-> ])
210
50.5% (106)
0.0% (0)
49.5%
100.0%
6.65 ms
Two Independent Errors in File
130
36.2% (47)
0.0% (0)
63.8%
100.0%
10.37 ms
Total Multi-Bracket
712
57.7% (411)
0.0% (0)
42.3%
100.0%
9.66 ms
Why the Ambiguity Guards Are Needed (Why Strategy 1 Breaks Code 8.6% of the Time)
Without the ambiguity guards in Strategies 2 & 3, simply inserting a missing ) wherever it produces 0 syntax errors (Strategy 1) silently changes the meaning of the code in 17.5% of missing-) cases because an unclosed ( steals the next ) and swallows subsequent arguments or operators:
// 1. Swallowing outer named arguments:// Broken: Container(padding: EdgeInsets.all(8, child: Text('hi'));// Raw fix: Container(padding: EdgeInsets.all(8, child: Text('hi'))); // `child` moved inside `EdgeInsets.all`!// 2. Swallowing a chained `.property` or operator:// Broken: final x = math.cos(angle * _radius!;// Raw fix: final x = math.cos(angle * _radius!); // `* _radius!` moved inside `cos(...)`!
By abstaining whenever an unclosed ( / [ spans across operators or ambiguous nested calls (Strategy 2), and only splitting argument lists when corroborated by an existing semantic diagnostic like undefined_named_parameter (Strategy 3), we get 0 false positives (100% precision) across both single-bracket and multi-bracket paste scenarios.
Here is a plain-English summary of how the best strategy (Strategy 3 Multi-Pass) actually works:
1. What the Dart Scanner & Parser Already Give Us
Whenever a file is parsed, the scanner pairs every opening ( or [ (BeginToken) with a closing token (endGroup):
Missing closers: If an opener has no matching closer, the scanner inserts a synthetic ) or ] at the next statement/block boundary (like ; or }), and the parser moves that synthetic closer earlier when grammar rules force it (e.g., before { in if (a && (b || c) {).
Extra closers: If there is an extra ) or ], either the scanner leaves it unmatched in the token stream (nothing points to it), or it prematurely closes an outer ( mid-expression, causing the parser to report Expected to find ';' right on that extra ) or ].
2. Gathering Candidate Edits (With Safety Guards)
We only look at () and [] (ignoring {} blocks, since moving } across statements is almost always valid syntax that silently changes control flow):
Candidate Deletions (for extra ) / ]):
Propose deleting any unmatched ) / ] token (unless it comes right after a , or binary operator, where the user is likely mid-typing an expression like foo(a, )), or any ) / ] token where the parser reported Expected to find ';'.
If there is a contiguous run of closers around that token (like ))) or )])), also propose deleting 2, 3, or 4 adjacent closers from that run.
Candidate Insertions (for missing ) / ]):
For each opening ( / [ that has a synthetic closer:
Check existing semantic diagnostics first: If an inner ( was left open, it will have "stolen" the outer call's ) and swallowed the outer call's remaining arguments or .property access. If the analyzer already reported undefined_named_parameter, extra_positional_arguments, or undefined_getter inside that unclosed group, propose inserting the missing ) right before that invalid argument or .property access.
Otherwise, use the scanner/parser's synthetic closer position, unless it is ambiguous: We refuse to trust the synthetic closer position if the unclosed group spans across an operator (., ?., !, =, ?, +, &&, etc.) or contains a nested group of the same bracket type that swallowed commas/operators. If multiple unclosed openers all end at the same boundary (e.g. ;), we group their closers in reverse (inner-to-outer) order (e.g. )]))).
3. Verifying in a Fast Re-parse Sandbox
We apply the candidate edit(s) to the text in memory and re-run just the scanner and parser (~1–2 ms):
Clean-parse gate: A result is only accepted if re-parsing produces 0 syntax errors and 0 synthetic tokens (which ensures the parser didn't only "succeed" by hallucinating a fake variable name), and introduces no new argument-list errors.
Multi-error / paste loop: If a single edit doesn't immediately make the whole file clean (because multiple brackets are off), we first try applying all non-overlapping candidate edits at once; otherwise we step through up to 5–8 times, picking the single edit that strictly reduces the total number of synthetic/unmatched brackets (stopping immediately if there's a tie between two different locations).
@bwilkerson I was tidying up the issue tracker and found this and decided to see what Gemini thought about it. It had some ideas and tried them out (code in its repo linked above). With some guards, it claims not to break any code in the tests it ran against some Flutter framework files.
The comment above is an explanation of how it works, the comment above that has the repo and some numbers from different strategies it tried.
Given the increasing use of agents that could use intelligence to fix these kinds of errors, I don't know how worthwhile it is trying to solve algorithmically (if there are ambiguities or a risk of getting it wrong), but I'm interested in your thoughts on the idea/description above.
(I will note that as I write this I realise it only did ] and ) and not } which was mentioned specifically in #3344, although I suspect braces are less comment in widget construction that is likely to be cut/paste?).
Given the increasing use of agents that could use intelligence to fix these kinds of errors ...
@jwren performed this experiment years ago and found that the simple models that we had at the time were already better and fixing these problems. The only reason we didn't ship it was because the implementation support wasn't available at the time.
If the deterministic approach were always correct, then I'd definitely argue for implementing it and making it available to agents. But as that isn't the case, an agent might be the better choice.
So, the question is: how well do agents do today when asked (in simple terms) to correct these kinds of mismatched brackets? If they're not very good at it, we might be able to write a skill that would improve their performance.
So, the question is: how well do agents do today when asked (in simple terms) to correct these kinds of mismatched brackets? If they're not very good at it, we might be able to write a skill that would improve their performance.
I did a quick test by getting Gemini write a sample of the cases from our previous experiment to disk, then spawn subagents using the "flash lite" and "flash" models asking them to fix them. Unfortunately I can't tell which models these map to (they report themselves as Flash Lite = "Gemini 2.5 Pro (Experimental)" and Flash = "Gemini 3.8 Flash", but Antigravity suggested these might not be accurate because it wasn't in their transcripts; however I don't know if it can see read their full system prompts).
It gave the agents them the following prompt:
Fix the missing, extra, or mismatched brackets/parentheses ((), [], {}) in each of the following 30 Dart files in /tmp/bracket_agent_eval/flash/:
/tmp/bracket_agent_eval/flash/case_01.dart through /tmp/bracket_agent_eval/flash/case_30.dart (i.e. case_01.dart, case_02.dart, ..., case_30.dart).
Rules:
Use ONLY read_file and edit_file (or write_file with Overwrite: true) on the 30 files in /tmp/bracket_agent_eval/flash/.
Do NOT use run_command or look at any other directory on disk.
Only fix bracket/paren/brace errors (and commas between closing brackets where appropriate) so each file is valid Dart matching the intended structure.
Process all 30 files and then report completion.
The results look like this (and it confirmed neither of them read any files besides these):
Category
Cases
flash_lite Exact Fix
flash_lite Broke Code
flash_lite Still Broken
flash Exact Fix
flash Broke Code
flash Still Broken
1. Single Missing () / ] / })
7
5/7 (71%)
0/7 (0%)
2/7 (29%)
7/7 (100%)
0/7 (0%)
0/7 (0%)
2. Single Extra () / ] / })
6
5/6 (83%)
0/6 (0%)
1/6 (17%)
6/6 (100%)
0/6 (0%)
0/6 (0%)
3. Mismatched Closer () / ] / })
3
3/3 (100%)
0/3 (0%)
0/3 (0%)
3/3 (100%)
0/3 (0%)
0/3 (0%)
4. Contiguous Missing Run (2–4)
6
4/6 (67%)
0/6 (0%)
2/6 (33%)
6/6 (100%)
0/6 (0%)
0/6 (0%)
5. Contiguous Extra Run (2–4)
4
4/4 (100%)
0/4 (0%)
0/4 (0%)
4/4 (100%)
0/4 (0%)
0/4 (0%)
6. Mixed Multi-Error (3–4 across file)
4
4/4 (100%)
0/4 (0%)
0/4 (0%)
4/4 (100%)
0/4 (0%)
0/4 (0%)
Total
30
25/30 (83.3%)
0/30 (0.0%)
5/30 (16.7%)
30/30 (100.0%)
0/30 (0.0%)
0/30 (0.0%)
So flash scored 100%. flash_lite left some code broken (although never produced parsing-but-incorrect code). flash_lite did fail to make some edits due to incorrect whitespace (and re-read the file and then correctly applied the edit).
This was not a big sample, and the errors I tested with were probably quite simpler compared to copy/pasting a large chunk of code. Still, my feeling is that this is that this is probably a fairly simple task for a modern cloud-based model. It might be interesting to try smaller models (for example local models like Gemma or MAI-Code-1.1-Flash on-device), though I don't have anything like that set up to test right now.
There are still a lot of devs not using AI (or at least not using it for all coding), but I suspect those numbers are only going in one direction and given the number of 👍 's across this and the other linked issues, there might be limited value in this.
That said, I merged two issues together here, and this original comment was about making it easier to debug this rather than auto-fixing them, so I wonder if there are other changes that might help (for example, sometimes I think having the code formatted might make it clearer where to insert things, but right now we don't format at all).
in editorRelates to code editing or language featuresis enhancementAn enhancement or improvement that should be listed in release notes but is not a bug fix.
Activity
eseidel commentedon Jun 8, 2021
One way to make it clearer would be to be able to have dartfmt run up until the first error. Right now dartfmt just doesn't run when there are analysis errors, but dartfmt-ing everything up to the first error might help me sort out parenthesis/brace problems through indents?
eseidel commentedon Jun 8, 2021
#3344 seems related too.
DanTup commentedon Jun 8, 2021
I'm not sure if we could reliably format up to the first error since truncating there would likely also be invalid code and rejected by dartfmt.
Although I wonder if we could try auto-inserting them at the location where there are "expected
)"-style errors, then re-parse (and repeat) to see if we can end up with valid code?Something similar was discussed for semicolons at dart-lang/sdk#45427, though there were some ambigious cases. If we're able to only do it if it produces valid code, then that might cut out some of the issues (although it may also narrow the number of cases where it works too).
FMorschel commentedon Aug 30, 2024
Also related to dart-lang/sdk#46916
DanTupBot commentedon Nov 8, 2026
Additional context from #3344 ("Add the ability to automatically insert missing } and )"):
DanTupBot commentedon Nov 8, 2026
I did some prototyping to see how fast and reliable automatic bracket/parenthesis recovery could be using the analyzer's token stream and parser. Full code and detailed results are in DanTupBot/dart_bracket_recovery_experiment (tested against ~1,400 single and multi-bracket mutations across 15 Flutter Material files).
Strategies Tested
{}blocks, also deletes extra)/]flagged withExpected ';'mid-expression, and skips ambiguous(/[insertions where the unclosed group spans across commas,.propertychains, or operators.undefined_named_parameter,extra_positional_arguments,undefined_getter) to safely recover nested widget/function calls where an inner unclosed(swallowed outer arguments, without needing extra resolution passes.Single-Bracket Results (on
()and[])*("Broke Code / Shifted" means the result had 0 syntax errors, but the bracket was placed in a different valid location than the original code.)
Multi-Bracket / Paste Scenarios (Strategy 3 Multi-Pass)
We also tested pasting code with multiple missing/extra brackets at once (runs of 2, 3, and 4+ adjacent
)/], swapped)<->], and multiple independent errors in the same file):)/]))/]))/]))/]))/]))/]))<->])Why the Ambiguity Guards Are Needed (Why Strategy 1 Breaks Code 8.6% of the Time)
Without the ambiguity guards in Strategies 2 & 3, simply inserting a missing
)wherever it produces 0 syntax errors (Strategy 1) silently changes the meaning of the code in 17.5% of missing-)cases because an unclosed(steals the next)and swallows subsequent arguments or operators:By abstaining whenever an unclosed
(/[spans across operators or ambiguous nested calls (Strategy 2), and only splitting argument lists when corroborated by an existing semantic diagnostic likeundefined_named_parameter(Strategy 3), we get 0 false positives (100% precision) across both single-bracket and multi-bracket paste scenarios.DanTupBot commentedon Nov 9, 2026
Here is a plain-English summary of how the best strategy (Strategy 3 Multi-Pass) actually works:
1. What the Dart Scanner & Parser Already Give Us
Whenever a file is parsed, the scanner pairs every opening
(or[(BeginToken) with a closing token (endGroup):)or]at the next statement/block boundary (like;or}), and the parser moves that synthetic closer earlier when grammar rules force it (e.g., before{inif (a && (b || c) {).)or], either the scanner leaves it unmatched in the token stream (nothing points to it), or it prematurely closes an outer(mid-expression, causing the parser to reportExpected to find ';'right on that extra)or].2. Gathering Candidate Edits (With Safety Guards)
We only look at
()and[](ignoring{}blocks, since moving}across statements is almost always valid syntax that silently changes control flow):)/]):)/]token (unless it comes right after a,or binary operator, where the user is likely mid-typing an expression likefoo(a, )), or any)/]token where the parser reportedExpected to find ';'.)))or)])), also propose deleting 2, 3, or 4 adjacent closers from that run.)/]):(/[that has a synthetic closer:(was left open, it will have "stolen" the outer call's)and swallowed the outer call's remaining arguments or.propertyaccess. If the analyzer already reportedundefined_named_parameter,extra_positional_arguments, orundefined_getterinside that unclosed group, propose inserting the missing)right before that invalid argument or.propertyaccess..,?.,!,=,?,+,&&, etc.) or contains a nested group of the same bracket type that swallowed commas/operators. If multiple unclosed openers all end at the same boundary (e.g.;), we group their closers in reverse (inner-to-outer) order (e.g.)]))).3. Verifying in a Fast Re-parse Sandbox
We apply the candidate edit(s) to the text in memory and re-run just the scanner and parser (~1–2 ms):
DanTup commentedon Nov 9, 2026
@bwilkerson I was tidying up the issue tracker and found this and decided to see what Gemini thought about it. It had some ideas and tried them out (code in its repo linked above). With some guards, it claims not to break any code in the tests it ran against some Flutter framework files.
The comment above is an explanation of how it works, the comment above that has the repo and some numbers from different strategies it tried.
Given the increasing use of agents that could use intelligence to fix these kinds of errors, I don't know how worthwhile it is trying to solve algorithmically (if there are ambiguities or a risk of getting it wrong), but I'm interested in your thoughts on the idea/description above.
(I will note that as I write this I realise it only did
]and)and not}which was mentioned specifically in #3344, although I suspect braces are less comment in widget construction that is likely to be cut/paste?).bwilkerson commentedon Nov 9, 2026
@jwren performed this experiment years ago and found that the simple models that we had at the time were already better and fixing these problems. The only reason we didn't ship it was because the implementation support wasn't available at the time.
If the deterministic approach were always correct, then I'd definitely argue for implementing it and making it available to agents. But as that isn't the case, an agent might be the better choice.
So, the question is: how well do agents do today when asked (in simple terms) to correct these kinds of mismatched brackets? If they're not very good at it, we might be able to write a skill that would improve their performance.
DanTup commentedon Nov 9, 2026
I did a quick test by getting Gemini write a sample of the cases from our previous experiment to disk, then spawn subagents using the "flash lite" and "flash" models asking them to fix them. Unfortunately I can't tell which models these map to (they report themselves as Flash Lite = "Gemini 2.5 Pro (Experimental)" and Flash = "Gemini 3.8 Flash", but Antigravity suggested these might not be accurate because it wasn't in their transcripts; however I don't know if it can see read their full system prompts).
It gave the agents them the following prompt:
The results look like this (and it confirmed neither of them read any files besides these):
flash_liteExact Fixflash_liteBroke Codeflash_liteStill BrokenflashExact FixflashBroke CodeflashStill Broken)/]/}))/]/}))/]/})So flash scored 100%. flash_lite left some code broken (although never produced parsing-but-incorrect code). flash_lite did fail to make some edits due to incorrect whitespace (and re-read the file and then correctly applied the edit).
This was not a big sample, and the errors I tested with were probably quite simpler compared to copy/pasting a large chunk of code. Still, my feeling is that this is that this is probably a fairly simple task for a modern cloud-based model. It might be interesting to try smaller models (for example local models like Gemma or MAI-Code-1.1-Flash on-device), though I don't have anything like that set up to test right now.
There are still a lot of devs not using AI (or at least not using it for all coding), but I suspect those numbers are only going in one direction and given the number of 👍 's across this and the other linked issues, there might be limited value in this.
That said, I merged two issues together here, and this original comment was about making it easier to debug this rather than auto-fixing them, so I wonder if there are other changes that might help (for example, sometimes I think having the code formatted might make it clearer where to insert things, but right now we don't format at all).
bwilkerson commentedon Nov 9, 2026
The formatter doesn't run when there are parse errors because recovery might have caused the parser to mis-parse something.