C99
The C target generates portable C99 source with an explicit ownership API. Generated parsers use the standard C library and require no additional runtime.
Minimal working example
Create the following two files in an empty directory. parser.c is generated by pegtool.
identifier.peg
Start = Identifier !. {
return pegtool_value_string_n(c->text, c->text_length);
}
Identifier = [\pL_] [\pL\p{Nd}_]*main.c
#include "parser.c"
int main(void) {
PegtoolResult result = pegtool_parse("name_世界");
if (!result.ok) {
fprintf(stderr, "%s\n", result.error);
pegtool_result_free(&result);
return 1;
}
printf("%s\n", result.value.as.string.data);
pegtool_result_free(&result);
return 0;
}Generate and compile it:
pegtool -t c -o parser.c identifier.peg
gcc -std=c99 -Wall -Wextra -Werror -pedantic-errors main.c -o identifier
.\identifier.exeOutput:
name_世界Public API
| Function | Purpose |
|---|---|
pegtool_parse | Parse a NUL-terminated string |
pegtool_parse_n | Parse an explicit byte length, which may contain NUL |
pegtool_parse_with_options | Use PegtoolParserOptions |
pegtool_parse_with_options_n | Combine options with an explicit length |
pegtool_result_free | Free memory owned by the success value or error result |
Call pegtool_result_free after every parse, whether it succeeds or fails.
Actions and ownership
word = [\p{L}]+ {
return pegtool_value_string_n(c->text, c->text_length);
}Labels are const PegtoolValue *, and actions return an owned PegtoolValue. Call pegtool_value_clone when retaining a label value. Build arrays with pegtool_value_array and pegtool_value_array_push. Failure paths must free temporary values whose ownership they have acquired.
Labels that conflict with internal parameters or C99 keywords are generated as _pegtool_label_<name>. Use -receiver-name to change the default c name of the current-match object.
Options
PegtoolParserOptions supports filename, entrypoint, custom_data, and max_expressions. The C target currently has no memoization switch, and -optimize-parser has no C-specific effect.