An Example Program
A short, complete program that uses every layer of Kami: it reads a language from a language file, lexes a text in it, highlights it and builds its model; then it reads a C file, builds its semantic model, and pairs its braces in a brace session. This page lists the program, says how to build it, and shows what it prints.
1. The program
The program takes the path of a C file. First it parses the Tiny language of Language Files from a string in the program, and reads a small Tiny text: it prints the keywords and comments by their styles, and the symbols of the model that Tiny's grammar makes. Then it reads the C file: it lexes it with lexer_run(), builds its model with semantic_build() and prints each symbol, and loads the text into a brace session with brace_match_proven and prints each brace pair that spans lines. Every result is freed with the free function of its type.
/* what_is_in.c - Print what Kami finds in a C file, and in a small text in another language. */
#include "kami.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* The whole file, with a NUL after it; NULL when it cannot be read. */
static char *read_file(const char *path, size_t *length) {
FILE *file = fopen(path, "rb");
if (!file) return NULL;
char *text = NULL;
size_t used = 0, got = 0;
do {
char *grown = realloc(text, used + 65536 + 1);
if (!grown) {
free(text);
fclose(file);
return NULL;
}
text = grown;
got = fread(text + used, 1, 65536, file);
used += got;
} while (got == 65536);
fclose(file);
text[used] = '\0';
*length = used;
return text;
}
/* A token's text, for printing. */
static void print_token(const Lexer *lexer, size_t index) {
char spelled[64];
lexer_spell(lexer, &lexer->tokens[index], spelled, sizeof(spelled));
printf("%s", spelled);
}
/* The symbols of a model: kind, name, line and uses. */
static void print_symbols(const Lexer *lexer, const SemanticModel *model) {
for (size_t index = 0; index < model->symbol_count; index++) {
const SemanticSymbol *symbol = &model->symbols[index];
if (symbol->name == SEMANTIC_NONE) continue;
printf(" %-24s ", semantic_kind_name((SemanticKind)symbol->kind));
print_token(lexer, symbol->name);
printf(" (line %u, used %u times%s)\n", lexer->tokens[symbol->name].line, symbol->use_count,
symbol->comment_count ? ", documented" : "");
}
}
/* A C file: its symbols, then its braces, kept by a session. */
static int read_c_file(const char *path) {
size_t length = 0;
char *text = read_file(path, &length);
if (!text) {
fprintf(stderr, "cannot read %s\n", path);
return 1;
}
Lexer lexer;
if (lexer_run(&lexer, text, length, lexer_options_for_path(path))) {
free(text);
return 1;
}
char directory[4096];
snprintf(directory, sizeof(directory), "%s", path);
char *slash = strrchr(directory, '/');
if (slash) *slash = '\0';
else snprintf(directory, sizeof(directory), ".");
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) {
printf("%s: %zu symbols%s%s\n", path, model.symbol_count, model.valid ? "" : "; ", model.valid ? "" : model.problem);
print_symbols(&lexer, &model);
semantic_free(&model);
}
BraceSession *session = brace_session_create(brace_match_proven);
if (session) {
session->lexer_options = lexer.options;
session->path = path;
if (brace_session_load(session, text, length) == 0) {
static const char *const sure[] = { "certain", "likely", "ambiguous" };
for (size_t index = 0; index < session->answer_count; index++) {
const BraceAnswer *answer = &session->answers[index];
const Token *brace = &session->lexer.tokens[answer->token];
if (brace->kind != TOKEN_LEFT_BRACE && answer->partner >= 0) continue; /* shown with its { */
if (answer->partner >= 0 && session->lexer.tokens[session->answers[answer->partner].token].line == brace->line) continue;
printf(" %c on line %u: ", brace->kind == TOKEN_LEFT_BRACE ? '{' : '}', brace->line);
if (answer->partner >= 0) printf("pairs with line %u", session->lexer.tokens[session->answers[answer->partner].token].line);
else if (answer->partner == BRACE_GHOST) printf("its partner is missing, most likely at byte %u", answer->ghost_offset);
else printf("see the macro use at token %d", answer->partner_token);
printf(", %s\n", sure[answer->confidence]);
}
}
brace_session_destroy(session);
}
lexer_free(&lexer);
free(text);
return 0;
}
/* The Tiny language of the manual, and a file in it. */
static const char tiny_language[] =
"[language]\nname = Tiny\nextensions = tiny\nblocks = keywords\nblock-start = func if while\nblock-end = end\n"
"layout = lines\nlayout-ignore-in = (\n"
"[lexical]\nline-comment = #\nstring = \"\nescape = \\\nnumber-separator = _\n"
"operators = == != <= >= = + - * / < > , ( )\n"
"[words]\nkeyword = func if while end return var\nconstant = true false nil\nbuiltin = print\n"
"[symbols]\nfunction = func NAME\nvariable = var NAME\n"
"[grammar]\n"
"file = @many(statement) END\n"
"statement = function / declaration / if_stmt / while_stmt / return_stmt / expression NEWLINE\n"
"function = \"func\" NAME:function @body(\"(\" parameters? \")\" NEWLINE @many(statement, \"end\") \"end\") NEWLINE\n"
"parameters = NAME:parameter (\",\" NAME:parameter)*\n"
"declaration = \"var\" NAME:variable \"=\" expression NEWLINE\n"
"if_stmt = \"if\" expression NEWLINE @block(@many(statement, \"end\")) \"end\" NEWLINE\n"
"while_stmt = \"while\" expression NEWLINE @block(@many(statement, \"end\")) \"end\" NEWLINE\n"
"return_stmt = \"return\" expression? NEWLINE\n"
"expression = operand (OP operand)*\n"
"operand = NUMBER / STRING / \"true\" / \"false\" / \"nil\" / call / NAME:use / \"(\" expression \")\"\n"
"call = NAME:use \"(\" (expression (\",\" expression)*)? \")\"\n";
static const char tiny_file[] =
"# Count down from a number.\nfunc countdown(n)\n\tvar i = n\n\twhile i > 0\n\t\tprint(i, \"left\")\n"
"\t\ti = i - 1\n\tend\n\treturn nil\nend\n\ncountdown(1_000)\n";
static void read_tiny(void) {
Language language;
if (language_parse(&language, tiny_language, "tiny")) return;
if (language.grammar_problem[0]) printf("the grammar has a fault: %s\n", language.grammar_problem);
printf("example.tiny is %s: %d\n", language.name, language_match(&language, "example.tiny", NULL));
Lexer lexer;
if (language_lex(&language, &lexer, tiny_file, strlen(tiny_file)) == 0) {
for (size_t index = 0; index < lexer.token_count; index++) {
LanguageStyle style = language_token_style(&language, &lexer, index);
if (style == LANGUAGE_STYLE_KEYWORD || style == LANGUAGE_STYLE_COMMENT_LINE) {
printf(" %s: ", language_style_name(style));
print_token(&lexer, index);
printf("\n");
}
}
SemanticModel model;
if (language_symbols_build(&language, &lexer, &model) == 0) {
printf(" %s, %zu symbols, %zu scopes\n", model.valid ? "valid" : model.problem, model.symbol_count, model.scope_count);
print_symbols(&lexer, &model);
semantic_free(&model);
}
lexer_free(&lexer);
}
language_free(&language);
}
int main(int argument_count, char **arguments) {
if (argument_count != 2) {
fprintf(stderr, "usage: what_is_in FILE.c\n");
return 2;
}
read_tiny();
return read_c_file(arguments[1]);
}
2. Building it
Build Kami first (make, see the overview). Then, with the program saved as what_is_in.c beside the kami folder:
cc -std=gnu17 -Wall -Wextra -Ikami/src what_is_in.c kami/libkami.a -o what_is_in
After make install, the headers are in $(PREFIX)/include/kami and the library in $(PREFIX)/lib:
cc -std=gnu17 -I/usr/include/kami what_is_in.c -lkami -o what_is_in
3. What it prints
On demo/sample.c, the small file that comes with Kami, run in the kami folder as ../what_is_in demo/sample.c:
example.tiny is Tiny: 2
comment-line: # Count down from a number.
keyword: func
keyword: var
keyword: while
keyword: end
keyword: return
keyword: end
valid, 3 symbols, 2 scopes
function countdown (line 2, used 1 times, documented)
parameter n (line 2, used 1 times)
variable i (line 3, used 4 times)
demo/sample.c: 13 symbols
member x (line 9, used 2 times)
member y (line 10, used 2 times)
type Point (line 11, used 3 times, documented)
variable points_seen (line 14, used 1 times, documented)
parameter from (line 17, used 2 times)
parameter to (line 17, used 2 times)
function distance_squared (line 17, used 1 times, documented)
variable across (line 18, used 2 times)
variable down (line 18, used 2 times)
function main (line 23, used 0 times, documented)
variable path (line 24, used 2 times)
variable index (line 25, used 5 times)
macro LIMIT (line 5, used 2 times)
{ on line 8: pairs with line 11, certain
{ on line 17: pairs with line 20, certain
{ on line 23: pairs with line 30, certain
{ on line 25: pairs with line 28, certain
Every name of the Tiny text is linked to its definition: i is used four times after its definition. The C file parses, so its brace pairs are proved by the language and certain. On demo/broken.c, the same file with the } of the for loop lost, the Tiny part is the same, and the rest is:
demo/broken.c: 10 symbols; line 29: not C: the file ends too early
member x (line 9, used 2 times)
member y (line 10, used 2 times)
type Point (line 11, used 2 times, documented)
variable points_seen (line 14, used 0 times, documented)
parameter from (line 17, used 2 times)
parameter to (line 17, used 2 times)
function distance_squared (line 17, used 0 times, documented)
variable across (line 18, used 2 times)
variable down (line 18, used 2 times)
macro LIMIT (line 5, used 2 times)
{ on line 8: pairs with line 11, certain
{ on line 17: pairs with line 20, certain
{ on line 23: pairs with line 29, likely
{ on line 25: its partner is missing, most likely at byte 731, likely
The file no longer parses: the model is not valid, and its problem says where the parser stopped. Here that is the end of the file, where the } is missing, so the line is that of the file's last token. The parser skips main, so its names are not in the model, and the braces are paired by layout: the { of the loop has lost its partner, and the missing } most likely goes at byte 731, the start of return 0;. Nothing about the function around it is certain any more.
4. The demo that comes with Kami
make demo builds demo/kami_demo from demo/kami_demo.c, a slightly longer program in the same spirit: it prints a C file's size and tab width, its symbols at file scope with the first line of their documentation, and each brace with its partner, how sure that is and its first reason, in color on a terminal.
make demo
demo/kami_demo demo/sample.c
demo/kami_demo demo/broken.c
Kami API
The whole library
Reading C and C++
Braces
Any language