The Parser and the Semantic Model
The semantic model is the answer to "what does each name in this file mean?". For every token of the file it says which symbol the token names, and for every symbol where it is declared, what kind of thing it is, how often it is used and what its documentation comment says. This page explains the parser that the model is built from, the model itself (symbols, scopes, how names and members are resolved), and the model of a language that is not C. The declarations are in parser.h, semantic.h and language.h.
1. From tokens to a model
For C and C++, semantic_build() does all the steps: it preprocesses the file, has the parser read the result into a record, and maps the record back onto the file's own tokens.
The parser works on the preprocessed tokens, so its record counts those. The model counts the file's own tokens, so a program can put every answer back on the text.
2. The parser
parse_c(tokens, count, &result) checks whether preprocessed tokens form a valid C translation unit: C23 with the GNU extensions (statement expressions, nested functions, case ranges, computed goto, __attribute__, asm, typeof, __builtin_va_arg and the like, and K&R definitions). It is a recursive descent parser that backtracks where C is ambiguous without knowing every type: a name that nothing declared may be a type or an object, and the text is accepted if either reading parses. The typedefs it meets are kept by scope, so a known name is never ambiguous. Beyond the grammar it reports these faults: break, continue, case and default outside a loop or switch, an object declared twice in one block (not a typedef, an extern or a function), a function declared static in a block, a call with the wrong number of arguments to a function the file declares with a prototype that is not variadic, and a name used where it is not declared because the file declares it only inside blocks.
The ParseResult says whether the tokens are valid (valid), where reading stopped (stopped_at, a preprocessed token index; the token count when it is valid) and why, for people (message, such as not C at "else", not C: the file ends too early or break outside a loop or switch). The call returns 0, or -1 when out of memory. parse_c() stops at the first declaration that does not parse.
parse_c_record(tokens, count, &result, &record) does the same and keeps what it read. After a declaration that does not parse, it skips to the end of that declaration (its ;, or the } of its body) and goes on, so one broken function hides only itself; result still names the first fault. Free the record with parse_record_free(). Every index in the record is an index into the preprocessed tokens.
| Array | Each entry |
|---|---|
declarations |
A ParseDeclaration: the token of its name, its extent [first, end) from its specifiers to the end of its declarator, its kind (PARSE_VARIABLE, PARSE_FUNCTION, PARSE_PARAMETER, PARSE_TYPEDEF, PARSE_TAG, PARSE_MEMBER, PARSE_ENUMERATOR, PARSE_LABEL), is_definition (1 for a function or tag with its body, and for every parameter, member, enumerator and label; a variable's is worked out by the model), and the scope it belongs to. owner and body are for C++ and are -1 and PARSE_NONE in C. |
uses |
A ParseUse: the name's token, how it is used (PARSE_USE_NAME for an object, function, typedef or enumerator; PARSE_USE_TAG after struct, union or enum; PARSE_USE_MEMBER after . or ->; PARSE_USE_LABEL after goto or &&), and the declaration it resolves to, or -1. The parser resolves a plain name through the scopes it is in; it leaves every member and label at -1 for the model, and in C every tag too. |
scopes |
A ParseScope: a block or a parameter list, with its parent and its first and last tokens where the parser opened and closed it: for a block, the token after its { and its }; for a parameter list, the token after its ( and its ); for a function's body, its { and the token after its }. Scope 0 is the file's own scope, whose parent is -1. |
The C++ reader
parse_cpp_record() fills the same record for C++. It checks no grammar, because C++ cannot be parsed without knowing every type and an editor needs the names of code that does not compile yet. It pairs the brackets first, then reads each statement by its form, so a statement it cannot read costs only that statement; valid says only whether the brackets pair. It reads namespaces (also namespace A::B, and a namespace opened again), classes, structs and unions with their bases, enums scoped or not, members and methods with the class that owns them (owner, and the class's { as body), constructors, destructors and operators, functions defined outside their class (void A::B::f()), typedefs, using aliases, namespace aliases, concepts and template type parameters (as PARSE_TYPEDEF; a template parameter that is a value is a PARSE_PARAMETER), enumerators, variables, parameters of functions and lambdas, and labels. A < after a name in a type is skipped to its closing > (>> closes two). Every other name is a use, resolved through the blocks around it, a method's class and the classes it derives from, namespaces opened by using namespace, and qualified names (A::b). A member after . or ->, and a label, are left to the model.
3. Building the model
PreprocessorOptions options = { .file_directory = directory, .cplusplus = (lexer.options & LEXER_CPLUSPLUS) != 0 };
SemanticModel model;
if (semantic_build(lexer.tokens, lexer.token_count, text, &options, &model) == 0) {
if (!model.valid) { /* model.problem: "line 12: not C at ..." */ }
/* model.symbols, model.symbol_of_token ... */
semantic_free(&model);
}
semantic_build() preprocesses the file with the options (see The Preprocessor), reads it with parse_c_record(), or parse_cpp_record() when options->cplusplus is set, and builds the model. It returns 0, or -1 when out of memory; on -1 the model is left empty. The options may be NULL: then nothing is known of the build, and the file is read as C. A file that does not parse still gets a model: valid is 0 and problem says what stopped it, as "line N: " and the parser's message, or the preprocessor's failure (#error, a missing header). When the parser stopped at the end of the file, the line is that of the file's last token, and the message is not C: the file ends too early. When the preprocessor stopped at one of its limits, the model has no symbols and problem names the limit ("preprocessing stopped: ..."). Free the model with semantic_free().
4. Symbols
model.symbols holds every symbol the file declares. The parser's declarations come first, in the file's order, and the macros follow, one for each #define line of the file (in every branch, taken or not). Each SemanticSymbol has these fields; every token index is an index into the file's own tokens:
| Field | What it holds |
|---|---|
kind |
A SemanticKind: SEMANTIC_VARIABLE, SEMANTIC_FUNCTION, SEMANTIC_PARAMETER, SEMANTIC_TYPEDEF, SEMANTIC_TAG (a struct, union or enum name; in C++ also a class or namespace), SEMANTIC_MEMBER, SEMANTIC_ENUMERATOR, SEMANTIC_LABEL or SEMANTIC_MACRO. semantic_kind_name() gives a name for people: "variable", "function", "parameter", "type", "struct, union or enum", "member", "enumerator", "label" or "macro". |
is_definition |
1 for a function with its body, a tag with its body, a macro, a variable that is not extern, and every parameter, member, enumerator and label (and a C++ namespace). |
at_file_scope |
1 when it is declared outside every function and block. A macro always has 1, even when its #define is inside a function. In C++, a name inside a namespace or a class has 0, and so has a member defined outside its class, void A::f() { }, which belongs to its class. |
name |
The token of its name. When a macro made the name, it is the name's token in the macro's #define line when the macro is defined in the file, and SEMANTIC_NONE when the macro comes from a header or the predefines, or when the name was made by ##. |
first, last |
The first and last tokens of its whole declaration; for a macro, the # and the last token of its #define line. |
scope |
The scope it is declared in, an index into model.scopes. In C, scope 0 is the file's own scope; a macro has -1. |
comment_first, comment_count |
Its documentation: the comment tokens from comment_first, comment_count of them (0 for none). See Documentation. |
use_count |
How many tokens of the file name it, its own declaration's name not counted. |
type_token |
The token that names its type (struct x a;: x; Foo *a;: Foo), or SEMANTIC_NONE. |
body |
The { of the struct, union or enum it declares (in C++ also of the class or namespace), or has as its type written in place (struct { int x; } point;), or SEMANTIC_NONE. |
owner_body |
For a member: the { of the struct that holds it, past any anonymous struct in between. For a C++ declaration with an owner: the owner's {. |
For every token, model.symbol_of_token[token] is the symbol it names, or -1, and model.declares[token] is 1 where the token is the name in a symbol's declaration. These arrays, and member_base, have model.token_count entries, one for each token of the file.
model.scopes holds the scopes, with the same indexes as the parser's: each SemanticScope has its parent (-1 for none) and the file's tokens first and last where it begins and ends, as the parser recorded them (see the record's scopes above). A scope opened by a macro begins at the macro's { in its #define line when the macro is defined in the file, else at the macro's use; SEMANTIC_NONE only when no token of the file can stand for it. block_only is always 0 for C.
5. How names are resolved
A name is resolved as the compiler resolves it, on the tokens the compiler reads, and the answer is written where the name is written in the file. So a name written in a macro's argument is found where it is written, a name written in the body of a macro defined in the file is found in its #define line, and a name that a header's macro makes, or that ## makes, names nothing in the file.
| A name used as | Resolves to |
|---|---|
| A variable, function, typedef or enumerator | The declaration the parser found through the scopes around the use. |
A tag, after struct, union or enum |
The tag of that name in the innermost scope that encloses the use. |
A label, after goto or && |
The label of that name in the same function. |
A member, after . or -> |
The member of that name in the struct that the thing before it has as its type (see below). |
| Any other name spelled as a macro | The macro: every token of the file not already resolved (in code, in #if lines and after #ifdef) whose spelling is a macro's name names that macro, the latest definition before the token, or the earliest one when none comes before. |
Members by type. For a->b.c, the model finds the type of a (the name its declaration's type comes down to: pointers do not matter, typedefs are followed as far as the file declares them, and a type name that the file declares only as a tag, such as struct Foo behind a typedef in a header, is found by its name), looks for b among that struct's members, takes b's type, and looks for c there. So two structs can have members of the same name. model.member_base[token] is, for a member's name, the token its type comes from (in a->b, the a), else -1. Only when no type can be told at all does the model fall back on a name that exactly one member of the file has, which is a guess. When the type is known to come from somewhere else (a header), the member is left unresolved: a program that has the models of other files can go on from type_token and member_base.
6. Documentation
A symbol's documentation is the comments right above its declaration, with no blank line between them and the declaration, as long as each of them starts its own line (a comment at the end of a line of code belongs to that code). When there are none, it is a comment at the end of the declaration's last line, after nothing but ;, punctuation or } (as int count; /* how many */). The comment tokens are left as they are, with their /*, // and *: a program strips what it does not want to show.
7. What a macro use becomes
For a program that shows the expansion of a macro, the model keeps what each outermost use of a macro in the file becomes (a use inside another's argument, and a use that becomes no tokens, have no entry), in full (the macros inside it expanded too), as text with a space where the tokens had one. expansion_tokens lists the file's tokens that are such uses, in ascending order; expansion_offsets gives where each one's text starts in expansion_text, and each text ends with a NUL. A text longer than SEMANTIC_EXPANSION_BYTES (16 KB) is cut and ends with "...", and once the texts of a file reach SEMANTIC_EXPANSIONS_BYTES (2 MB) the later uses have none.
for (size_t index = 0; index < model.expansion_count; index++)
printf("line %u: %s\n", lexer.tokens[model.expansion_tokens[index]].line,
model.expansion_text + model.expansion_offsets[index]);
8. The model of other languages
language_symbols_build(language, lexer, &model) gives a file in any other language a model of the same form, which semantic_free() frees. It returns 0, or -1 when out of memory or an argument is missing. When the grammar fails on a file, out of memory or out of steps, the patterns make the model instead and the call still returns 0.
- With a grammar (see Grammars), the model is what the grammar's annotations say: whether the file is valid and
problemwhen it is not, each definition with its scope and itsbody, each use resolved through the scopes around it, members found through the type of what they are taken from (member_base), and scopes for every@scope,@bodyand@block(the last withblock_onlyset). The comment lines right above a definition's line are its documentation, but only for the first name that line defines: a function's comment is not its parameters'.language_grammar_build()does this part on its own. - Without a usable grammar, or when the grammar gives up on the file, the
[symbols]patterns make the model (see [symbols]). There is a symbol for each place a pattern matches, and in a document language for each heading (asSEMANTIC_LABEL). Each symbol's block comes from the language'sblocks(a heading's block runs to the next heading of its level or above), and a symbol is in the innermost block that holds its name: a method in its class. A symbol in no block is at file scope with scope -1. The comment lines right above a definition, each starting its line, are its documentation. Every other name spelled like a declared name is a use of its first declaration. Such a model is always valid.
The engine key decides which call a program makes: semantic_build() for a language whose engine is c or c++, language_symbols_build() for the others.
Kami API
The whole library
Reading C and C++
Braces
Any language
