diff options
| author | 2026-02-22 03:18:01 +0000 | |
|---|---|---|
| committer | 2026-02-22 03:18:01 +0000 | |
| commit | f404d75c6050223a3cbbe9b7775700ca291ff93d (patch) | |
| tree | cbcec3fec884901b11e32def54f539d3a8a6eb3b /examples/lex.c | |
| parent | add lexer implementation (diff) | |
| download | rs274ngc-f404d75c6050223a3cbbe9b7775700ca291ff93d.tar.gz | |
add lex example
Diffstat (limited to 'examples/lex.c')
| -rw-r--r-- | examples/lex.c | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/examples/lex.c b/examples/lex.c new file mode 100644 index 0000000..a0f33e7 --- /dev/null +++ b/examples/lex.c | |||
| @@ -0,0 +1,67 @@ | |||
| 1 | // examples/lex.c | ||
| 2 | |||
| 3 | #include <stddef.h> | ||
| 4 | #include <stdio.h> | ||
| 5 | #include <fcntl.h> | ||
| 6 | #include <unistd.h> | ||
| 7 | |||
| 8 | #define CMMM__RS274NGC__LEXEME__STRIP_VENDOR | ||
| 9 | #define CMMM__RS274NGC__LEXER__STRIP_VENDOR | ||
| 10 | |||
| 11 | #include "utils.h" | ||
| 12 | #include "cmmm/rs274ngc/lexer.h" | ||
| 13 | |||
| 14 | int | ||
| 15 | main (int argc, char *argv[]) | ||
| 16 | { | ||
| 17 | const char *filename; | ||
| 18 | struct cmmm__sv rs274ngc; | ||
| 19 | struct cmmm__arena a = {0}; | ||
| 20 | |||
| 21 | if (argc == 1) { | ||
| 22 | filename = "-"; | ||
| 23 | rs274ngc = read_until_eof (&a, 0); | ||
| 24 | } else if (argc == 2) { | ||
| 25 | filename = argv[1]; | ||
| 26 | int fd = open (filename, O_RDONLY); | ||
| 27 | rs274ngc = mmap_whole (fd); | ||
| 28 | } else { | ||
| 29 | exit (EXIT_FAILURE); // TODO(cmmm): better DIE | ||
| 30 | } | ||
| 31 | |||
| 32 | // printf (SV_FMT, SV_FMTA (rs274ngc)); | ||
| 33 | // return 0; | ||
| 34 | |||
| 35 | struct rs274ngc__lexer lexer = | ||
| 36 | rs274ngc__lexer__from_string_view (rs274ngc, filename); | ||
| 37 | |||
| 38 | int line = 1; | ||
| 39 | const char *bol = lexer.lexeme.sv.begin; | ||
| 40 | for (;; rs274ngc__lexer__next_lexeme (&lexer)) { | ||
| 41 | struct rs274ngc__lexeme lexeme = lexer.lexeme; | ||
| 42 | |||
| 43 | if (lexeme.kind == RS274NGC__LEXEME__KIND__END_OF_FILE) { | ||
| 44 | printf ("%s:%d:%ld: %s\n", | ||
| 45 | lexer.filename, line, lexeme.sv.begin - bol, | ||
| 46 | rs274ngc__lexeme__kind_names[lexeme.kind]); | ||
| 47 | break; | ||
| 48 | }; | ||
| 49 | |||
| 50 | if (lexeme.kind == RS274NGC__LEXEME__KIND__END_OF_LINE) { | ||
| 51 | printf ("%s:%d:%ld: %s\n", | ||
| 52 | lexer.filename, line, lexeme.sv.begin - bol + 1, | ||
| 53 | rs274ngc__lexeme__kind_names[lexeme.kind]); | ||
| 54 | bol = lexeme.sv.end; | ||
| 55 | line += 1; | ||
| 56 | continue; | ||
| 57 | } | ||
| 58 | |||
| 59 | printf ("%s:%d:%ld-%ld: %s: |"SV_FMT"|\n", | ||
| 60 | lexer.filename, line, lexeme.sv.begin - bol + 1, lexeme.sv.end - bol, | ||
| 61 | rs274ngc__lexeme__kind_names[lexeme.kind], SV_FMTA (lexeme.sv)); | ||
| 62 | } | ||
| 63 | |||
| 64 | return EXIT_SUCCESS; | ||
| 65 | } | ||
| 66 | |||
| 67 | // examples/lex.c ends here | ||
