The Lexer and Highlighting
The lexer cuts a text into tokens. Every other layer of Kami works on its tokens, and every token has a style, which is all a program needs for highlighting. One lexer reads every language: C and C++ by Kami's built-in language files, every other language by its own file. This page explains the tokens, how to lex C, C++ and any other language, how lines, columns and the tab width are worked out, how to get a token's style, and how to find the blocks that fold. The declarations are in lexer.h and language.h.
1. Tokens
A Token says where a piece of the text is and what it is:
| Field | What it holds |
|---|---|
offset |
The byte offset of the token's first character. A line splice in front of the token is skipped. |
length |
Its length in bytes, any line splice inside it included. So the token's text is always source + offset for length bytes; lexer_spell() gives it without its splices. |
line |
The line it starts on, counted from 1. |
column |
The visual column where it starts, counted from 0 (see Lines, columns and the tab width). |
kind |
A TokenKind. |
flags |
TOKEN_FLAG_* bits. |
style |
A LanguageStyle: what the token is for highlighting. |
The kinds are few, and the same for every language; the style says more (a name's kind is TOKEN_IDENTIFIER, and its style says whether it is a keyword, a type or a plain name):
| Kind | The token is |
|---|---|
TOKEN_LEFT_BRACE, TOKEN_RIGHT_BRACE |
{ and }, also when written as the digraphs <% and %>. |
TOKEN_LEFT_PARENTHESIS, TOKEN_RIGHT_PARENTHESIS |
( and ). |
TOKEN_LEFT_BRACKET, TOKEN_RIGHT_BRACKET |
[ and ], also as <: and :>. |
TOKEN_SEMICOLON |
;. |
TOKEN_HASH |
The # (or %:) that starts a directive line. |
TOKEN_IDENTIFIER |
A name or a keyword. |
TOKEN_NUMBER |
A number; in C, a preprocessing number. |
TOKEN_STRING, TOKEN_CHARACTER |
A string or character literal, with its prefix. |
TOKEN_HEADER_NAME |
The <...> after #include, #include_next, #import or #embed (in another language: after a header-words word). |
TOKEN_COMMENT |
A comment of any form. |
TOKEN_PUNCTUATOR |
Any other punctuator or operator. |
TOKEN_OTHER |
A byte that starts no token of the language, such as @ in C. |
| Flag | Set when |
|---|---|
TOKEN_FLAG_DIRECTIVE |
The token is on a preprocessor directive line (its # included). |
TOKEN_FLAG_LINE_START |
The token starts its line: no token before it ends on that line. A token after a comment that ends on its line is not a line start. |
TOKEN_FLAG_UNTERMINATED |
A comment or literal has no end. Lexing goes on after it. |
TOKEN_FLAG_SPLICED |
The token's text holds a line end: a line splice, or a string that runs over lines. It is never set on a comment. |
TOKEN_FLAG_DIGRAPH |
The token is written as a digraph. |
TOKEN_FLAG_TRIGRAPH |
The token holds a trigraph (only when trigraphs are read). |
TOKEN_FLAG_HEREDOC |
The token is part of a heredoc's body or its end word: data, not code. |
A Lexer holds the text and its tokens: source and size (the text, which stays the caller's), tokens and token_count, line_start and line_count (where each line starts; line_start[0] is 0, and there is one more line than there are line ends), options (the LEXER_* options it was read with) and tab_width. Free it with lexer_free(), which leaves the text alone.
2. Lexing C and C++
Lexer lexer;
if (lexer_run(&lexer, text, length, lexer_options_for_path(path)) == 0) {
for (size_t index = 0; index < lexer.token_count; index++) {
const Token *token = &lexer.tokens[index];
/* token->offset, token->length, token->line, token->kind ... */
}
lexer_free(&lexer);
}
lexer_run() reads the text as the C standard's translation phases 1 to 3 do. A line splice (a backslash, optional spaces or tabs, and a line end) vanishes anywhere, even inside a token. Digraphs are the tokens they stand for. Comments, and string and character literals with their prefixes, are single tokens. Every token of a directive line is marked with TOKEN_FLAG_DIRECTIVE, and the <...> of an #include is a header name. The options are:
| Option | Effect |
|---|---|
LEXER_CPLUSPLUS |
Lex with the built-in C++ language: raw strings R"tag(...)tag" (and their u8R, LR, uR, UR forms), and <:: as < and :: unless : or > follows. Without it, the built-in C language is used. |
LEXER_TRIGRAPHS |
Read trigraphs: ??= is #, ??< is {, ??/ and a line end is a splice, and so on. |
lexer_options_for_path(path) gives LEXER_CPLUSPLUS for the endings .cc .cpp .cxx .c++ .C .hh .hpp .hxx .h++ .H .ipp .tpp .tcc .inl, and for .h, which may be either: reading C as C++ only changes a string right after an R prefix, and <::, which C code does not have. Any other path, and NULL, gives 0.
3. Lexing any other language
For a language read from its language file (see Language Files), call language_lex():
Language language;
language_parse(&language, file_text, "python");
Lexer lexer;
if (language_lex(&language, &lexer, text, length) == 0) {
/* the tokens, each with its style */
lexer_free(&lexer);
}
language_free(&language);
| Call | What it does |
|---|---|
language_lex(language, lexer, text, size) |
Lexes the text by the language's rules. |
language_lex_options(language, lexer, text, size, options) |
The same, with lexer options: LEXER_TRIGRAPHS reads trigraphs, as the language's trigraphs key does. LEXER_CPLUSPLUS changes nothing in the lexing and is only kept in lexer.options; a language whose engine is c++ sets it there anyway. lexer_run() is this call with a built-in language. |
language_lex_set(set, lexer, text, size, options) |
Lexes the text in the first language of a set, with the set's other languages for what the text embeds: the JavaScript in an HTML page, the code fences of a Markdown file (see Embedded languages). |
Each returns 0, or -1 when out of memory, when an argument is missing (a NULL text is allowed only with a size of 0), or for an empty set. A UTF-8 byte order mark at the start of the text is skipped. The kinds are those of C: every comment is a TOKEN_COMMENT, a line that a [lines] rule takes is one TOKEN_STRING, a name is a TOKEN_IDENTIFIER, and brackets and ; have their own kinds in every language, which is what brace pairing reads. The style tells the rest apart (a heading, a tag, a variable, a regex).
4. Lines, columns and the tab width
After lexing, each token's line and column are worked out, and so is the file's tab width. A column is a visual column: a tab moves to the next multiple of the tab width, a UTF-8 continuation byte takes no column, and every other byte takes one. The layers above (above all, brace matching by layout) read indentation from these columns and never from the text, so two lines look aligned only when they are aligned once tabs are expanded.
Line 3 of a file starts with a tab, so with a tab width of 8 the word after it is at column 8, although it is the second byte of the line. line_start[2] is 40.
The tab width is LEXER_TAB_WIDTH (8) unless the file shows that 4 or 2 is meant. Kami looks at each pair of braces (by nesting, outside directives) whose } starts a line below its {, where the two lines are indented with different characters (tabs on one, spaces or no indentation on the other), or both with a mix of tabs and spaces: the } should sit at the indentation of the line its { is on. It counts, for widths 8, 4 and 2, how many such pairs line up, and takes 4 or 2 only when it is clearly better than the others. The width chosen is lexer.tab_width.
A program that made its tokens in another way can call lexer_layout(): given source, size, tokens, token_count and options, and with line_start NULL (or an array from an earlier layout, which it frees), it fills in line_start, line_count and tab_width, and each token's line, column, TOKEN_FLAG_LINE_START, TOKEN_FLAG_SPLICED and (with LEXER_TRIGRAPHS) TOKEN_FLAG_TRIGRAPH, as the lexer does.
lexer_spell(lexer, token, buffer, capacity) copies a token's spelling with its line splices removed and, when trigraphs are read, its trigraphs replaced. The copy is cut to fit and ends with a NUL (when the capacity is not 0); the return value is the whole length of the spelling, so a program can tell that it was cut.
5. Highlighting
The lexer sets every token's style. language_token_style(language, lexer, index) returns it, and for a token that has none (a token a program made itself) works one out from its kind: a comment is comment; a string or header name string; a character character; a token on a directive line preprocessor; a number number; a bracket brace; a name the class of its word in [words] (language_word_style()), or identifier; a stray byte default; anything else operator. An index past the end gives LANGUAGE_STYLE_DEFAULT.
for (size_t index = 0; index < lexer.token_count; index++) {
LanguageStyle style = language_token_style(&language, &lexer, index);
const char *name = language_style_name(style); /* "keyword", "comment-line" ... */
/* draw lexer.tokens[index] in the color the program gives that style */
}
For C and C++ lexed with lexer_run(), pass language_builtin("c") or language_builtin("cpp") as the language. The style is the style of the token's text. A program that also has a semantic model can do better for names: a name the model links to a symbol can be colored by the symbol's kind (function, type, parameter and so on) instead of identifier, as Unryu does. The styles and their names are listed on Language Files.
6. Folds
A fold is a block whose lines a program can hide, with the first line still in sight: a LanguageFold with first_line and last_line, counted from 0. Where folds come from depends on the language:
| The language | Its folds |
|---|---|
| Has a grammar | The scopes of its semantic model (SemanticModel.scopes: bodies, scopes and blocks alike), from language_symbols_build(). |
blocks = indent |
language_indent_folds(lexer, folds, capacity): a statement (the first token of a line outside every bracket, comments aside) followed by deeper statements opens a block that runs to the last line of the last of them. Blank lines inside belong to it, and lines inside an open bracket continue the line above. |
blocks = keywords |
language_keyword_folds(language, lexer, folds, capacity): each opening word to the closing word that matches it, when the two are on different lines (see Keyword blocks). |
| C, C++ and other brace languages | The brace pairs that span lines, from Braces; a program should fold only the certain ones. |
Both fold calls take NULL for folds to only count, and return how many blocks there are, which may be more than capacity; call once to count, allocate, and call again. They return 0 when out of memory.
7. Characters that are not what they look like
language_unusual_characters() (in language.h) reads a text, not its tokens, and lists the characters a reader cannot tell from others: bidirectional controls (U+202E and the others, which can make code show in another order than it is read: "Trojan Source"), characters that show nothing (a zero-width space, the joiners, a soft hyphen, a byte order mark past the first byte) and, when asked, spaces that look like a plain one (a no-break space, the wide spaces). Each LanguageUnusual has its bytes, its code point, its kind and a short label (RLO, ZWSP, NBSP) for an editor to show it by.
size_t count = 0;
LanguageUnusual *found = language_unusual_characters(text, size, 1, &count);
for (size_t i = 0; i < count; i++) printf("%s at byte %u\n", found[i].label, found[i].offset);
free(found);
8. The text a spelling checker reads
language_spelling_ranges() reads a text's tokens and gives the runs of it that hold words to check, by the language file's spelling key (see Language files): in code, its comments and the strings that have a space in them; in prose, all of it but code spans, links, tags, entities, commands, numbers and operators; in markup, comments, strings with a space and the text between the tags; nothing for none. Touching runs are joined. An editor checks the words of those runs against its dictionary.
size_t count = 0;
LanguageRange *runs = language_spelling_ranges(language, &lexer, &count);
for (size_t i = 0; i < count; i++) check_words(text + runs[i].start, runs[i].end - runs[i].start);
free(runs);
9. A gettext catalog's messages
language_po_messages() reads a .po or .pot file, line by line as gettext writes it, and gives each message: where it starts and ends, its flags line, its msgid, msgid_plural and each msgstr or msgstr[n] (from the first quote to after the last, over continuation lines), and whether it is the header, fuzzy, untranslated or obsolete (#~), and whether it says c-format (or python-format) or no-c-format.
language_po_directives_match() checks a translation's format directives against the original's: %s, %5.2f, %ld, %1$s, %*d (and %%, which is none). Numbered directives are compared by their numbers, so a translation may put them in another order; the others in order. A plural form may leave out the first directive (the number: "one file"). It returns 1 when they match, and when there is nothing to check (an empty translation, a no-c-format message, a % that starts no directive it knows), and 0 when they do not.
size_t count = 0;
LanguagePoMessage *messages = language_po_messages(text, size, &count);
for (size_t i = 0; i < count; i++)
for (int form = 0; form < messages[i].msgstr_count; form++)
if (!language_po_directives_match(text, size, &messages[i], form)) printf("line of byte %u: %%s and %%d differ\n", messages[i].msgstr_start[form]);
free(messages);
Kami API
The whole library
Reading C and C++
Braces
Any language
