Braces
Which { goes with which }? In code that compiles, the language decides, and Kami proves the answer. In code being typed, Kami gives its best answer, says how sure it is and why, and says where a missing brace most likely goes. This page explains the matchers, the answer for each brace, the reasons, parentheses and brackets, and other languages. The declarations are in brace.h; The Brace Session keeps the answers up to date while a text is edited.
1. Asking for the answers
A matcher reads a BraceInput and fills in one BraceAnswer for each brace that brace_collect() listed:
BraceInput input = { .tokens = lexer.tokens, .token_count = lexer.token_count, .source = text,
.cplusplus = (lexer.options & LEXER_CPLUSPLUS) != 0, .path = path };
size_t count = brace_collect(&input, NULL); /* count the braces */
BraceAnswer *answers = calloc(count ? count : 1, sizeof(BraceAnswer));
brace_collect(&input, answers); /* each answer's token */
brace_match_proven(&input, answers, count); /* the answers */
brace_collect() lists the braces that pair, in token order: every { and } that is not on a preprocessor directive line (brace_is_pairable()), because a brace in a #define belongs to the macro, not to the code around it. It clears each answer and sets its token.
| BraceInput field | What it says |
|---|---|
tokens, token_count, source |
The file's tokens and text. A brace token may have a length of 0 (one that a program inserted). |
cplusplus |
1 to read C++ rules too (lambdas, Type{...}, the range for), normally from LEXER_CPLUSPLUS. |
path |
The file's path, so that its #include "..." are found beside it; or NULL. |
defines, predefines, include_directories |
What is known of the build, in the same forms as PreprocessorOptions (see The Preprocessor). Each may be NULL. |
2. The matchers
brace_matchers lists the matchers by name, the best first, with a sentence for people about each (brace_matcher_count of them). Each is a function that fills in the answers:
| Name | Function | What it does |
|---|---|---|
proven |
brace_match_proven() |
The best for C and C++. It first takes the answers of brace_match_preprocessor(). Then it preprocesses the file (macros expanded, #if decided) in the configuration the compiler builds and in every other configuration that changes the braces. Where the compiler's configuration preprocesses cleanly, its braces balance, and parse_c() accepts it (for C++, which has no grammar check: its braces, parentheses and brackets all pair and nest with each other), the pairing is the language's own: every brace that the valid configurations pair with one partner gets that partner, certain, with BRACE_REASON_PROVEN. A brace that they pair with two partners is certain too: it keeps the partner of the compiler's configuration, the other goes in other_partner, and BRACE_REASON_CONFIGURATION is added. A brace with more than two partners, or whose second partner is inside a macro, keeps the layout's answer. Another configuration that is not valid is one nobody builds (an #ifdef for another platform) and is left out. Where the proof cannot reach (a broken file, code in #if 0), the layout's answers stay. |
preprocessor |
brace_match_preprocessor() |
brace_match_layout() in every #if configuration that changes the braces, merged by brace_match_configurations(). |
layout |
brace_match_layout() |
Nesting and indentation as two independent kinds of evidence: certain only where they agree. |
depth |
brace_match_depth() |
The baseline that most editors use: plain nesting depth from the start of the file. It marks every answer certain, which it is not. |
How the layout matcher thinks
Counting braces is wrong only on the "spine" of a mistake: the pairs that enclose it. Every other pair it makes is right. A spine pair shows itself in the layout: its } sits at the wrong column, or lines inside the block are not indented deeper than it. So a pair is certain only when counting and indentation agree; in code with no indentation nothing that spans lines is certain, because nothing can be checked. Certain pairs are walls: the partner of an uncertain brace lies inside the nearest certain pair around it, or before the next certain top-level declaration (C has no nested functions). Inside that range, indentation proposes the partner: a } pairs with the open { whose block it lines up with, and a { with no such } gets a ghost where its block's indentation ends. Signs from the code itself narrow it further, such as a case that would land outside every switch, or a variable used after the } of the block that declares it.
Configurations
brace_match_configurations(input, answers, count, match) runs any matcher in each #if configuration that changes the braces and merges the answers: an answer is certain only when it is certain in each, and other_partner names the partner a brace has in another configuration. A group whose every branch balances its own braces cannot change anything outside it, so it is not varied. Groups with the same condition (an #ifdef __cplusplus around extern "C" { and another around its }) choose the same branch. The base configuration is what a compiler sees where the source says so (#if 0 is false, #if 1 true, __cplusplus defined only in C++, and what defines says), and otherwise each varied group's first branch. Up to 64 combinations are tried together; with more, each varied group is tried on its own against the base. brace_match_proven() explores configurations by turning one undecided decision of the base the other way at a time (and decisions nested inside a turned branch), with at most 32 preprocessor runs.
3. The answer for one brace
Ranges and ghosts are token gaps, so they can name the end of the file. Here no } follows, and the indentation suggests that the block of { ends after f;, so its missing } is shown before g.
| Field | What it holds |
|---|---|
token |
The token index of the brace. |
partner |
The partner's index in the same answer array. Or one of: BRACE_GHOST (-1), the partner is missing and the range says where it can be; BRACE_EXTRA (-2), the brace should not be there (only brace_session_verify() says this); BRACE_IN_MACRO (-3), the partner comes from a macro, whose use is at partner_token (only brace_match_proven() says this, for BEGIN_BLOCK ... }). |
confidence |
BRACE_CERTAIN: the language, or the evidence, leaves no other pairing. BRACE_LIKELY: the best answer, with a range the partner is in. BRACE_AMBIGUOUS: the evidence does not choose. |
reasons |
BRACE_REASON_* bits: why the answer is what it is (see below). |
range_low, range_high |
When the answer is not certain: the first and last token gaps where the partner can be. A real partner at token t is in the range when range_low <= t <= range_high. |
ghost_gap |
For a ghost: its most likely gap, the token the missing brace goes before (token_count for the end of the file). |
ghost_offset |
The ghost's byte offset. For a brace, only a session fills it in: the start of the ghost_gap token, or a place kept from an earlier edit. brace_match_delimiters() fills it in for parentheses and brackets. |
may_be_extra |
1 when deleting this brace is also a way to repair the code. It is set on uncertain answers, and on an answer that the compiler check made certain as BRACE_EXTRA. |
other_partner |
The partner in another #if configuration (an answer index), or BRACE_GHOST for none. |
partner_token |
With BRACE_IN_MACRO: the token of the macro use that holds the partner. Otherwise it means nothing. |
A proven pair can still look wrong: when the indentation suggests a different pairing, or cannot confirm the pair (the layout's answer was not certain), BRACE_REASON_LAYOUT_DISAGREES is set on a certain answer as a warning that the code may not do what it looks like it does (a missing brace hidden by another one).
4. The reasons
brace_reason_text(bit) gives each reason as one sentence for people ("" for a value that is not one reason bit). BRACE_REASON_COUNT is 32, the number of bits.
| Bit | Meaning |
|---|---|
BRACE_REASON_AGREE |
Nesting and indentation agree on this pair. |
BRACE_REASON_UNMATCHED |
Counting braces leaves this one without a partner. |
BRACE_REASON_CLOSER_COLUMN |
The } is not at the indentation of the line that opens the block. |
BRACE_REASON_BODY_SHALLOW |
A line inside the block is not indented deeper than the block. |
BRACE_REASON_CLOSER_SHARED |
The block spans lines, but its } shares a line with code. |
BRACE_REASON_ONE_LINE_BODY |
The block opens and closes on one line, yet the next line is indented as its body. |
BRACE_REASON_LAYOUT_PAIR |
Indentation pairs it: the } sits at this block's indentation. |
BRACE_REASON_LAYOUT_GHOST |
The block's indentation ends with no brace there, so one is missing. |
BRACE_REASON_NO_LAYOUT |
Indentation gives no evidence here, so nothing can be checked. |
BRACE_REASON_WALL_PAIR |
The partner must be inside the certain pair around it. |
BRACE_REASON_WALL_TOP |
The partner must be before the next certain top-level declaration. |
BRACE_REASON_LABEL_OUTSIDE |
Paired this way, a case or default label would be outside every switch. |
BRACE_REASON_BREAK_OUTSIDE |
Paired this way, a break or continue would end up outside every loop it needs (a continue needs a loop, a break a loop or a switch). |
BRACE_REASON_ELSE_ALONE |
Paired this way, an else would not follow an if. |
BRACE_REASON_BARE_BLOCK |
A block of its own starts in the middle of a line, right after a statement. |
BRACE_REASON_SHARED_COLUMN |
Its } lines up just as well with an enclosing block whose pairing is in doubt. |
BRACE_REASON_OPEN_SHARED |
Code follows the { on its line, yet the block runs on to later lines. |
BRACE_REASON_SHARED_LINE |
Another brace on the same line is in doubt, and one line has no layout to check. |
BRACE_REASON_BAD_PLACE |
C does not allow this here: a { after a comma outside an initializer, or a ; inside an initializer. |
BRACE_REASON_ODD_ROW |
This table row holds a different number of values than the rows around it. |
BRACE_REASON_CONFIGURATION |
It pairs differently in different #if configurations. |
BRACE_REASON_SCOPE |
A variable declared inside this block is used after its }, so the } closes too early. |
BRACE_REASON_SCOPE_GHOST |
The missing } goes after the last use of the variables this block declares. |
BRACE_REASON_DELIMITER_BALANCED |
Every parenthesis and bracket in its statement balances. |
BRACE_REASON_DELIMITER_UNCLOSED |
Its statement ends while it is still open, so its closer is missing. |
BRACE_REASON_DELIMITER_UNOPENED |
Nothing in its statement opens it. |
BRACE_REASON_DELIMITER_IN_DOUBT |
Another parenthesis or bracket in the same statement does not balance. |
BRACE_REASON_SAME_COLUMN_CLOSERS |
Another } sits at the same column on the line right above or below, so either could close either block. |
BRACE_REASON_LOST_BRACE_SIGNS |
Text nearby only makes sense if a brace was lost: }; ;, struct int, a function body closed by };, or an unclosed namespace or extern "C" whose } this could be. |
BRACE_REASON_COMPILER |
Every repair the compiler accepts gives this pairing (the compiler check). |
BRACE_REASON_PROVEN |
The code is valid, so the language itself pairs these braces (every configuration that matters was checked). Valid means that C's grammar accepts it, or for C++ that its braces, parentheses and brackets all pair. |
BRACE_REASON_LAYOUT_DISAGREES |
A warning on a certain answer: the indentation suggests a different pairing, or cannot confirm this one, so the code may not do what it looks like it does. It is bit 31, a macro rather than part of the enum. |
5. Parentheses and brackets
brace_collect_delimiters() lists every (, ), [ and ], those on directive lines too, and brace_match_delimiters() pairs them with the same kind of answers. A parenthesis or bracket cannot outlive its statement, so mistakes stay local: a pair is certain when every parenthesis and bracket of its statement balances. When a ;, or a block's { or }, ends the statement while one is still open, its closer is missing: it gets a ghost right after the last token before that end, and the other pairs of that statement are only likely. The ; inside for (;;), statement expressions ({ ... }), compound literals (Type){ ... } and blocks passed to a macro are allowed. Each directive line is a statement of its own.
6. Other languages
For a language other than C, read by its language file, use brace_match_language(). Its lexer has already taken strings and comments out, and its statements are not C's (Nim's proc f(a: int; b: string) has a ; inside its brackets), so it works differently:
size_t brace_count = brace_collect(&input, NULL), delimiter_count = brace_collect_delimiters(&input, NULL);
BraceAnswer *braces = calloc(brace_count + 1, sizeof(BraceAnswer));
BraceAnswer *delimiters = calloc(delimiter_count + 1, sizeof(BraceAnswer));
brace_collect(&input, braces);
brace_collect_delimiters(&input, delimiters);
int balanced = brace_match_language(&input, braces, brace_count, delimiters, delimiter_count);
When every bracket of the file pairs by nesting (each closer matching the kind of the last opener), every brace, parenthesis and bracket pairs by nesting, every answer is certain with no reasons, and the call returns 1. Otherwise (usually while someone is typing) brace_match_layout() pairs the braces and brace_match_delimiters() the rest, and the call returns 0. A partner is an index into the answer's own list. The language's blocks key plays no part.
7. Other pairs: quotes, comments, tags, blocks and more
Besides brackets, a language file can declare other pairs with its pairs key (Language files): a string's quotes, a block comment's ends, interpolation (${ }), tags, the < > of generics, keyword blocks, #if chains and Unicode brackets in prose. language_pairs() finds them from the tokens alone, with no parsing, so a program can call it on tokens it already holds:
size_t count = 0;
LanguagePair *pairs = language_pairs(&language, &lexer, &count); // in the order of the text; free() it
for (size_t i = 0; i < count; i++)
if (pairs[i].partner < 0 && pairs[i].ghost_offset != LANGUAGE_PAIR_NOWHERE)
printf("missing %s at byte %u\n", pairs[i].missing, pairs[i].ghost_offset);
Each LanguagePair is one end: its bytes (offset, length), its kind (LanguagePairKind), whether it opens, closes or is in the middle (role), and its partner, an index into the same array. An end with no partner has partner -1, the text of the missing end in missing (", */, </div>, fi, #endif) and, in ghost_offset, where it most likely goes, or LANGUAGE_PAIR_NOWHERE when no place is known (an end tag with no start tag). confidence is a BraceConfidence.
- Quotes: a string token's opening marker (after a prefix such as
foru8; C++'sR"x(, Rust'sr#", Lua's[==[) and its closer. A string that an interpolation or a variable breaks into pieces pairs its first and last pieces' quotes. A string the lexer marks unterminated gets a certain ghost where it stops. - Comments: a block comment's opener and closer (
<!---->in markup); an unterminated one gets a ghost at its end. - Interpolation: an
interpolationopener right after a string piece, to its closer, with braces inside nested. - Tags: tokens of style
tag:<or</and a name, ended by>(/>is no pair); the end is the whole tag, attributes and all. End tags close the nearest open element of their name;void-tagsare never open,optional-end-tagsclose with their parent, and any other element left open gets a likely ghost before its parent's end tag (or at the end of the text).void-tags, or a language that is not case-sensitive, compares names in any case. - Angles: a
<right after a name (or after a keyword, or::) whose contents are type-like (names, numbers,, :: . * & ? : = | ( ) [ ], nested< >) and whose>is followed by what may follow a type.>>and>>>close two and three. A<that fails is no pair and gets no ghost. - Keywords: with
blocks = keywords, the blocks folding pairs (language_keyword_pairs()gives them per token); an opener left open gets a likely ghost of the firstblock-endword at the next line no deeper than its own.keyword-pairwords count where a statement starts (first on a line, or after; && || | ( { then do else in);named-paircommands must name the same{ }. - Conditionals: the directive character first on its line and a
conditional-wordsword (C'sif ifdef ifndef,elif elifdef elifndef,else,endifwhen none are given). Each end's partner is the next of its chain, and the#endif's is the#if. - Text:
text-pairsoutside tokens of stylecode, nested; a closer between two letters is an apostrophe. Ends left open get no place.
Kami API
The whole library
Reading C and C++
Braces
Any language
