5 The main task of the lexical scanner is to convert a stream of
6 characters into a stream of tokens. The tokens are then typically
7 used by a parser to extract the syntactic structure.
9 The stream of characters are assumed to be in memory identified by a
10 linked list of blocks, such as provided by the "[mdcode][]" literate
11 program extractor. A single token may never cross a block boundary.
18 The text is assumed to be UTF-8 though some matching assumes the
19 ASCII subset. If the text provided does not conform to UTF-8 an error
20 will be reported and some number of bytes will be skipped.
25 #include <unicode/uchar.h>
27 Tokens are returned by successive calls to the main interface
28 function: `token_next()` which has a `state` structure to keep track
29 of where it is up to. Each token carries not just a numeric
30 identifier but also the code block, the line and character within that
31 block, and the actual start and length using the `struct text` from
37 struct code_node *node;
48 ###### exported functions
49 struct token token_next(struct token_state *state);
52 struct token token_next(struct token_state *state)
63 The `line` and `col` offsets are useful for reporting errors.
64 The `txt` provides the content when that is important.
66 ### Token types and configuration ##
68 The scanner is not completely general, yet not completely specified.
69 There are a fixed set of token types, though particular tokens within
70 those types can be distinguish via configuration.
72 Most token types may be explicitly ignored, as typically comments
73 would be. The exact consequence of ignoring each token type varies
78 int ignored; // bit set of ignored tokens.
79 ## token config parameters
83 struct token_config *conf;
85 ###### token_next init
86 int ignored = state->conf->ignored;
89 The different tokens are numbers, words, marks, strings, comments,
90 newlines, EOF, and indents, each of which is examined in detail below.
92 There are various cases where no token can be found in part of the
93 input. All of these will be reported as an `TK_error` token.
95 It is possible to declare a number of strings which form distinct
96 tokens (rather than being grouped as e.g. 'word'). These are given
97 token numbers from `TK_reserved` upwards.
108 Numbers are the messiest tokens to parse, primarily because they can
109 contain characters that also have meaning outside of number and,
110 particularly, immediately after numbers.
112 The obvious example is the '`-`' sign. It can come inside a number for
113 a negative exponent, or after a number as a subtraction operator. To
114 be sure we have parsed as best as possible we need to only allow the
115 '`-`' inside a number if it is after an exponent character. This can be
116 `e` or `p` (for hex exponents), but `e` can also be a hexadecimal
117 digit, so we don't allow '`-`' after just any `e`.
119 To make matters worse, our language designer has decided to experiment
120 with allowing commas to be used as the decimal indicator, and spaces
121 to be used to separate groups of digits in large numbers. Both of
122 these can reasonably be restricted to appear between two digits, so we
123 have to add that condition to our tests.
125 So we cannot just treat numbers as starting with a digit and being
126 followed by some set of characters. We need more structure than that.
130 - Numbers must start with a digit.
131 - If the first digit is zero, the next character must be a base
132 signifier (one of `xob`) or a decimal marker (`.` or `,`).
133 In the first case the first `p` or `P` may be followed by a sign.
134 - If the number doesn't start with `0` followed by one of `xob`, the
135 first `e` may be followed by a sign.
136 - Any digit or hex digit may be followed by a space or underscore
137 providing that the subsequence character is also a (hex) digit.
138 This rule will require an extra level of 'unget' to be
139 supported when handling characters.
140 - Otherwise any digits or ASCII letters are allowed. We do not at
141 this point check that the digits given are permitted by the base.
142 That will happen when the token is converted to a number.
144 To allow easy configuration, the various non alphanumeric characters
145 are only permitted if they are listed in a configuration parameter.
147 ###### token config parameters
150 Note that numbers may not start with a period, so `.75` is not a
151 number. This is not the norm, but is not unheard of. Excluding these
152 numbers simplifies the rule at very little cost.
157 If TK_number is ignored, digits will result in an error unless they
158 are declared to be a start character for words.
166 if (iswdigit(ch) && !(ignored & (1<<TK_number))) {
167 int prev_special = 0;
169 int decimal_mark = 0;
171 wchar_t ch2 = get_char(state);
172 if (strchr("xobXOB", ch2) != NULL)
188 save_unget_state(state);
189 ch = get_char(state);
194 if (ch == '+' || ch == '-') {
199 if (ch == '.' || ch == ',') {
205 /* Don't allow that special char,
208 restore_unget_state(state);
211 if (strchr(state->conf->number_chars, ch)) {
215 /* non-number char */
218 /* We seem to have a "number" token */
220 close_token(state, &tk);
226 Words start with a "start" character followed by the longest
227 sequence of "continue" characters. The Unicode ID_START and
228 ID_CONTINUE sets are always permitted, but other ASCII characters
229 can be added to these sets.
231 ###### token config parameters
235 ###### internal functions
236 static int is_word_start(wchar_t ch, struct token_config *conf)
238 return iswalpha(ch) ||
239 strchr(conf->word_start, ch) != NULL ||
240 u_hasBinaryProperty(ch, UCHAR_ID_START);
243 static int is_word_continue(wchar_t ch, struct token_config *conf)
245 return iswalnum(ch) ||
246 strchr(conf->word_cont, ch) != NULL ||
247 u_hasBinaryProperty(ch, UCHAR_ID_CONTINUE);
250 Words can be either known or unknown. Known words are referred to as
251 "reserved words" and get a unique token number. Unknown words are
252 "identifiers" and are syntactically a single token.
257 A list of known words must be provided. This list is shared with the
258 "marks" which are described next. The list must be lexically sorted
259 and the length of the list must be given (`known_count`).
260 Tokens matching these known words are reported as the index of the
261 list added to `TK_reserved`.
263 ###### token config parameters
264 const char **words_marks;
269 if (is_word_start(ch, state->conf)) {
271 /* A word: identifier or reserved */
273 ch = get_char(state);
274 while (is_word_continue(ch, state->conf));
276 close_token(state, &tk);
278 if (ignored & (1<<TK_ident))
280 n = find_known(state->conf, tk.txt);
282 tk.num = TK_reserved + n;
288 Marks are generally one or more punctuation marks joined together. It
289 would be nice to use the term "symbol" for these, but that causes
290 confusion in a subsequent discussion of the grammar, which has terminal
291 symbols and non-terminal symbols which are conceptually quite
292 different. So strings of punctuation characters will be marks.
294 A "mark" consists of ASCII characters that are not white space, are not
295 "start" characters for words, and are not digits.
296 These will collectively be called mark characters.
298 ###### internal functions
299 static int is_mark(wchar_t ch, struct token_config *conf)
304 strchr(conf->word_start, ch) == NULL;
307 As with words, there can be known and unknown marks, though the rules
308 are slightly different.
310 Two marks do not need to be separated by a non-mark characters. This
311 is different from words which do need to be separated by at least one
312 non-continue character.
314 The scanner will normally prefer longer sequences of mark characters,
315 but will more strongly prefer known marks over unknown marks. So if
316 it finds a known mark where adding one more character does not result
317 in a known mark, it will return that first known mark.
319 If no known mark is found we will test against strings and comments
320 below before giving up and assuming an unknown mark.
321 If `TK_mark` is ignored, then unknown marks as returned as an error.
326 Known marks are included in the same list as the list of known words.
330 while (is_mark(ch, state->conf)) {
332 close_token(state, &tk);
333 n = find_known(state->conf, tk.txt);
335 tk.num = TK_reserved + n;
336 else if (tk.num != TK_error) {
337 /* found a longest-known-mark */
339 close_token(state, &tk);
342 ch = get_char(state);
345 if (tk.num != TK_error)
350 if (ignored & (1<<TK_mark))
359 Strings start with one of single quote, double quote, or back quote
360 and continue until a matching character on the same line. Any of
361 these characters can be included in the list of known marks and then
362 they will not be used for identifying strings.
364 Immediately following the close quote one or two ASCII letters may
365 appear. These are somewhat like the arbitrary letters allowed in
366 "Numbers" above. They can be used by the language in various ways.
368 If 3 identical quote characters appear in a row and are
369 followed by a newline, then this forms a multi-line string which
370 continues until an identical triple quote appears on a line preceded
371 only by whitespace and followed immediately by 0-2 ASCII letters and a newline.
373 Multi-line strings may not extend beyond the end of the `code_node` in
376 Normal strings and multi-line strings are encoded as two different
383 ###### internal functions
384 static int is_quote(wchar_t ch)
386 return ch == '\'' || ch == '"' || ch == '`';
389 #### Multi-line strings
391 The multi-line string is checked for first. If they are being
392 ignored, we fall through and treat a triple quote as an empty string
393 followed by the start of a new string.
396 if (tk.txt.len == 3 &&
397 !(ignored & (1 << TK_multi_string)) &&
398 is_quote(tk.txt.txt[0]) &&
399 memcmp(tk.txt.txt, tk.txt.txt+1, 2) == 0 &&
400 is_newline(tk.txt.txt[3])) {
402 wchar_t first = tk.txt.txt[0];
405 while (!at_eon(state) && qseen < 3) {
406 ch = get_char(state);
407 if (is_newline(ch)) {
410 } else if (at_sol && ch == first) {
412 } else if (ch != ' ' && ch != '\t') {
418 /* Hit end of node - error.
419 * unget so the newline is seen,
420 * but return rest of string as an error.
423 close_token(state, &tk);
427 /* 2 letters are allowed */
428 ch = get_char(state);
430 ch = get_char(state);
432 ch = get_char(state);
433 /* Now we must have a newline, but we don't return it
436 close_token(state, &tk);
437 tk.num = TK_multi_string;
443 #### Single-line strings
445 The sequence of marks collected may be more than a single-line
446 string, so we reset to the start and collect characters until
447 we find a close quote or a newline.
449 If `TK_string` is ignored, then quote characters will appear as `TK_mark`s.
452 if (tk.txt.len && is_quote(tk.txt.txt[0]) &&
453 !(ignored & (1<<TK_string))) {
454 wchar_t first = tk.txt.txt[0];
455 reset_token(state, &tk);
458 ch = get_char(state);
459 while (ch != first && !is_newline(ch));
461 if (is_newline(ch)) {
465 close_token(state, &tk);
471 Single line comments may start with '`//`' or '`#`' providing that these
472 are not known marks. They continue to the end of the line.
474 Block comments start with '`/*`' if this is not a known mark. They
475 continue to the first occurrence of '`*/`' and may not contain any
476 occurrence of '`/*`'.
478 Block comments can be wholly within one line or can continue over
479 multiple lines. The multi-line version should be followed immediately
480 by a newline. The Linux kernel contains over 285000 multi-line
481 comments are only 34 are followed by characters other than white space
482 (which should be removed) or a backslash (only needed in macros). So
483 it would not suffer from this rule.
485 These two comment types are reported as two separate token types, and
486 consequently can be ignored separately. When ignored a comment is
487 parsed and discarded.
493 ###### internal functions
494 static int is_line_comment(struct text txt)
496 return (txt.len >= 1 && txt.txt[0] == '#') ||
497 (txt.len >= 2 && txt.txt[0] == '/' &&
501 static int is_block_comment(struct text txt)
503 return txt.len >= 2 && txt.txt[0] == '/' &&
507 #### Single line comments
509 A single-line comment continues up to, but not including the newline.
513 if (is_line_comment(tk.txt)) {
514 while (!is_newline(ch))
515 ch = get_char(state);
517 close_token(state, &tk);
518 tk.num = TK_line_comment;
519 if (ignored & (1 << TK_line_comment))
526 The token text collected so far could exceed the comment, so we need
529 If we find an embedded `/*` we reset to just before the '/' and report
530 an error. That way the next thing to be parsed will be the rest of
531 the comment. This requires a double unget, so we need to save/restore
532 the unget state (explained later).
536 if (is_block_comment(tk.txt)) {
539 reset_token(state, &tk);
542 save_unget_state(state);
543 ch = get_char(state);
545 while (!at_eon(state) &&
546 (prev != '/' || ch != '*') &&
547 (prev != '*' || ch != '/')) {
551 save_unget_state(state);
552 ch = get_char(state);
554 close_token(state, &tk);
560 /* embedded. Need to unget twice! */
561 restore_unget_state(state);
566 tk.num = TK_block_comment;
567 if (newlines && !(ignored & (1<<TK_newline))) {
568 /* next char must be newline */
569 ch = get_char(state);
574 if (tk.num == TK_error ||
575 !(ignored & (1 << TK_block_comment)))
580 ### Indents, Newlines, and White Space.
582 Normally white space is ignored. However newlines can be important as
583 can indents, which are either after a newline or at the start of a
584 node (detected by `at_son()`);
586 ###### exported functions
587 static inline int is_newline(wchar_t ch)
589 return ch == '\n' || ch == '\f' || ch == '\v';
593 if (ch <= ' ' && !is_newline(ch)
597 If a line starts with more white-space than the previous non-blank
598 line - or if the first non-blank line in the document starts with any
599 white-space - then an Indent is reported at the start of the line.
601 Before the next non-blank line which starts with less white space, or
602 at the latest at the end of the document, a matching Undent token
603 is reported. There will always be an exact match between Indent and
606 It is possible for Undent to be followed (almost) immediately by an
607 Indent. This happens if, for example, the indent of three consecutive
608 lines are 0, 8, 4 spaces. Before the second line we report an
609 Indent. Before the third line we must report an Undent, as 4 is less
610 than 8, then also an Ident as 4 is greater than 0.
616 For the purpose of measuring the length of white space, a tab adds at
617 least one space, and rounds up to a multiple of 8.
619 ###### exported functions
620 static inline int indent_tab(int indent)
625 We need to track the current levels of indent. This requires some
626 sort of stack as indent levels are pushed on and popped off. In
627 practice this stack is unlikely to often exceed 5 so we will used a
628 fixed stack of 20 indent levels. More than this will be silently
633 int indent_sizes[20];
637 Newlines can optionally be reported. Newlines within a block comment
638 or a multi-line string are not reported separately, but each of these
639 must be followed immediately by a newline so these constructs cannot
640 hide the fact that a newline was present.
642 When Indents are being reported, the Newline which would normally be
643 reported immediately before the Indent is delayed until after the
644 matching undent. This makes an indented section act like a
645 continuation of the previous line to some extent.
647 A blank line would normally be reported simply as two consecutive Newline
648 tokens. However if the subsequent line is indented (and indents are being
649 reported) then the right thing to do is less obvious as Newlines should be
650 delayed - but how many Newlines?
652 The approach we will take is to report the extra Newlines immediately after
653 the Indent token, so the blank line is treated as though it were an indented
659 If we find a newline or white space at the start of a block, we keep
660 collecting spaces, tabs, and newlines until we find some real text.
661 Then depending on the indent we generate some number of tokens. These
662 will be a sequence of "Newline Undent" pairs representing a decrease
663 in indent, then either a Newline or an Indent depending on whether the
664 next line is indented, then zero or more Newlines representing all the
665 blank lines that have been skipped.
667 When a Newline leads to the next block of code there is a question of
668 whether the various Newline and Undent/Indent tokens should appear to
669 pbelong to the earlier or later block. This is addressed by processing
670 the tokens in two stages based on the relative indent levels of the
671 two blocks (each block has a base indent to which the actual indents
674 Any "Newline Undent" pairs needed to reduce the current indent to the
675 maximum of the base indents of the old and new blocks are generated
676 against the old block. Then if the next block does not have an
677 increased indent, one more "Newline" is generated.
679 If further "Newline Undent" pairs are needed to get to the indent
680 level of the 'next' block, they are generated against that block,
681 though the first Newline is suppressed (it having already been
684 Finally the Newline or Indent for the first line of the new block is
685 generated, unless the Newline needs to be suppressed because it
686 appeared at the end of the previous block.
688 This means that a block may start with an Undent or an Indent, but
689 will only start with a Newline if it actually starts with a blank
692 We will need to represent in the `token_state` where in this sequence
693 of delayed tokens we are. As `state.col` records the target indent we
694 don't need to record how many undents or indents are needed. We do
695 need to record the number of blank lines, and which of Newline and
696 Undent is needed next in the initial sequence of pairs.
698 For this we store one more than the number of blank lines as
699 `delayed_lines` and a flag for `undent_next`.
706 Generating these tokens involve two separate pieces of code.
708 Firstly we need to recognise white space and count the indents and
709 newlines. These are recorded in the above state fields.
711 Separately we need, on each call to `token_next`, we need to check if
712 there are some delayed tokens and if so we need to advance the state
713 information and return one token.
716 if (is_newline(ch) || (at_son(state) && ch <= ' ')) {
718 int was_son = at_son(state);
719 if (ignored & (1<<TK_indent)) {
722 if (ignored & (1<<TK_newline))
725 close_token(state, &tk);
728 // Indents are needed, so check all white space.
729 while (ch <= ' ' && !at_eon(state)) {
732 ch = get_char(state);
736 if (state->node->next &&
737 state->node->next->indent > state->node->indent)
738 state->col = state->node->next->indent;
740 state->col = state->node->indent;
743 state->delayed_lines = newlines;
744 state->undent_next = was_son;
745 state->check_indent = 1;
750 ###### delayed tokens
752 if (state->check_indent || state->delayed_lines) {
753 if (state->col < state->indent_sizes[state->indent_level]) {
754 if (!state->undent_next &&
755 !(ignored & (1<<TK_newline))) {
756 state->undent_next = 1;
760 state->indent_level -= 1;
761 state->undent_next = 0;
765 if (state->col > state->indent_sizes[state->indent_level] &&
766 state->indent_level < sizeof(state->indent_sizes)-1) {
767 state->indent_level += 1;
768 state->indent_sizes[state->indent_level] = state->col;
769 state->delayed_lines -= 1;
773 state->check_indent = 0;
774 if (state->delayed_lines && !(ignored & (1<<TK_newline))) {
776 state->delayed_lines -= 1;
779 state->delayed_lines = 0;
785 After the last newline in the file has been processed, a special
786 end-of-file token will be returned. any further attempts to get more
787 tokens will continue to return the same end-of-file token.
799 ### Unknown Marks, or errors.
801 We have now handled all the possible known mark-like tokens.
802 If the token we have is not empty and `TK_mark` is allowed,
803 we have an unknown mark, otherwise this must be an error.
806 /* one unknown character */
807 close_token(state, &tk);
811 ## Tools For The Task
813 You may have noticed that are few gaps we left in the above -
814 functions used without first defining them. Doing so above would have
817 ### Character by character
819 As we walk through the various `code_node`s we need to process whole
820 Unicode codepoints, and keep track of which line and column we are on.
821 We will assume for now that any printing character uses one column,
822 though that is not true in general.
824 As the text in a `code_node` may include an indent that identifies it as
825 being code, we need to be careful to strip that. The `code_node` has
826 a flag that tells us whether or not we need to strip.
832 struct code_node *node;
837 ###### internal functions
839 static void do_strip(struct token_state *state)
841 if (state->node->needs_strip) {
843 while (n && state->node->code.txt[state->offset] == ' ') {
847 while (n == 4 && state->node->code.txt[state->offset] == '\t') {
854 static wint_t get_char(struct token_state *state)
860 if (state->node == NULL)
862 if (state->node->code.len <= state->offset) {
864 state->node = state->node->next;
865 while (state->node && state->node->code.txt == NULL);
867 if (state->node == NULL)
870 state->line = state->node->line_no;
871 state->col = state->node->indent;
876 memset(&mbstate, 0, sizeof(mbstate));
878 n = mbrtowc(&next, state->node->code.txt + state->offset,
879 state->node->code.len - state->offset,
881 if (n == -2 || n == 0) {
882 /* Not enough bytes - not really possible */
884 state->offset = state->node->code.len;
885 } else if (n == -1) {
888 next = 0x7f; // an illegal character
894 } else if (is_newline(next)) {
896 state->col = state->node->indent;
898 } else if (next == '\t') {
899 state->col = indent_tab(state->col);
904 We will sometimes want to "unget" the last character as it needs to be
905 considered again as part of the next token. So we need to store a
906 'previous' version of all metadata.
913 ###### before get_char
914 state->prev_offset = state->offset;
915 state->prev_line = state->line;
916 state->prev_col = state->col;
918 ###### internal functions
920 static void unget_char(struct token_state *state)
923 state->offset = state->prev_offset;
924 state->line = state->prev_line;
925 state->col = state->prev_col;
929 We occasionally need a double-unget, particularly for numbers and
930 block comments. We don't impose this cost on all scanning, but
931 require those code sections that need it to call `save_unget_state`
932 before each `get_char`, and then `restore_unget_state` when a
933 double-unget is needed.
940 ###### internal functions
941 static void save_unget_state(struct token_state *state)
943 state->prev_offset2 = state->prev_offset;
944 state->prev_line2 = state->prev_line;
945 state->prev_col2 = state->prev_col;
948 static void restore_unget_state(struct token_state *state)
950 state->prev_offset = state->prev_offset2;
951 state->prev_line = state->prev_line2;
952 state->prev_col = state->prev_col2;
955 At the start of a token we don't want to be at the end of a code block
956 if we can help it. To avoid this possibility, we 'get' and 'unget' a
957 single character. This will move into the next non-empty code block
958 and leave the current pointer at the start of it.
960 This has to happen _after_ dealing with delayed tokens as some of them
961 must appear in the previous node. When we do this, we need to reset
962 the data in the token.
964 ###### delayed tokens
968 tk.node = state->node;
970 tk.txt.txt = state->node->code.txt + state->offset;
971 tk.line = state->line;
978 The current token is initialized to line up with the first character
979 that we 'get' for each token. When we have, or might have, a full
980 token we can call `close_token` to set the `len` of the token
981 appropriately. This can safely be called multiple times.
983 Finally we occasionally (for single-line strings and block comments)
984 need to reset to the beginning of the current token as we might have
985 parsed too much already. For that there is `reset_token`.
988 tk.node = state->node;
990 tk.txt.txt = state->node->code.txt + state->offset;
991 tk.line = state->line;
995 ###### internal functions
997 static void close_token(struct token_state *state,
1000 tk->txt.len = (state->node->code.txt + state->offset)
1004 static void reset_token(struct token_state *state, struct token *tok)
1006 state->prev_line = tok->line;
1007 state->prev_col = tok->col;
1008 state->prev_offset = tok->txt.txt - state->node->code.txt;
1014 Tokens make not cross into the next `code_node`, and some tokens can
1015 include the newline at the and of a `code_node`, we must be able to
1016 easily check if we have reached the end. Equally we need to know if
1017 we are at the start of a node, as white space is treated a little
1020 ###### internal functions
1022 static int at_son(struct token_state *state)
1024 return state->offset == 0;
1027 static int at_eon(struct token_state *state)
1029 // at end-of-node ??
1030 return state->node == NULL ||
1031 state->offset >= state->node->code.len;
1034 ### Find a known word
1036 As the known-word list is sorted we can use a simple binary search.
1037 Following the pattern established in "mdcode", we will use a `struct
1038 text` with start and length to represent the code fragment we are
1041 ###### internal functions
1042 static int find_known(struct token_config *conf, struct text txt)
1045 int hi = conf->known_count;
1047 while (lo + 1 < hi) {
1048 int mid = (lo + hi) / 2;
1049 int cmp = strncmp(conf->words_marks[mid],
1051 if (cmp == 0 && conf->words_marks[mid][txt.len])
1058 if (strncmp(conf->words_marks[lo],
1059 txt.txt, txt.len) == 0
1060 && conf->words_marks[lo][txt.len] == 0)
1066 ### Bringing it all together
1068 Now we have all the bits there is just one section missing: combining
1069 all the token parsing code into one block.
1071 The handling of delayed tokens (newlines, indents, undents) must come
1072 first before we try getting another character.
1074 Then we parse all the test, making sure that we check for known marks
1075 before strings and comments, but unknown marks after strings and comments.
1077 This block of code will either return a token, or will choose to
1078 ignore one, in which case it will `continue` around to the top of the
1084 ch = get_char(state);
1096 As well as getting tokens, we need to be able to create the
1097 `token_state` to start with, and discard it later.
1102 ###### main functions
1103 struct token_state *token_open(struct code_node *code, struct
1106 struct token_state *state = malloc(sizeof(*state));
1107 memset(state, 0, sizeof(*state));
1109 state->line = code->line_no;
1110 state->col = code->indent;
1115 void token_close(struct token_state *state)
1120 ###### exported functions
1121 struct token_state *token_open(struct code_node *code, struct
1122 token_config *conf);
1123 void token_close(struct token_state *state);
1127 Getting tokens is the main thing but it is also useful to be able to
1128 print out token information, particularly for tracing and testing.
1130 Known tokens are printed verbatim. Other tokens are printed as
1131 `type(content)` where content is truncated to a given number of characters.
1133 The function for printing a truncated string (`text_dump`) is also exported
1134 so that it can be used to tracing processed strings too.
1139 ###### exported functions
1140 void token_trace(FILE *f, struct token tok, int max);
1141 void text_dump(FILE *f, struct text t, int max);
1143 ###### main functions
1145 void text_dump(FILE *f, struct text txt, int max)
1152 for (i = 0; i < max; i++) {
1153 char c = txt.txt[i];
1154 if (c < ' ' || c > '~')
1155 fprintf(f, "\\x%02x", c & 0xff);
1159 fprintf(f, "%c", c);
1165 void token_trace(FILE *f, struct token tok, int max)
1167 static char *types[] = {
1168 [TK_ident] = "ident",
1170 [TK_number] = "number",
1171 [TK_string] = "string",
1172 [TK_multi_string] = "mstring",
1173 [TK_line_comment] = "lcomment",
1174 [TK_block_comment] = "bcomment",
1175 [TK_indent] = "indent",
1176 [TK_undent] = "undent",
1177 [TK_newline] = "newline",
1179 [TK_error] = "ERROR",
1183 default: /* known word or mark */
1184 fprintf(f, "%.*s", tok.txt.len, tok.txt.txt);
1190 /* No token text included */
1191 fprintf(f, "%s()", types[tok.num]);
1197 case TK_multi_string:
1198 case TK_line_comment:
1199 case TK_block_comment:
1201 fprintf(f, "%s(", types[tok.num]);
1202 text_dump(f, tok.txt, max);
1208 ### And there we have it
1210 We now have all the library functions defined for reading and printing
1211 tokens. Now we just need C files to store them, and a mk file to make them.
1213 ###### File: scanner.h
1215 ## exported functions
1217 ###### File: libscanner.c
1219 #include "scanner.h"
1221 ## internal functions
1224 ###### File: scanner.mk
1228 scanner.mk scanner.h libscanner.c : scanner.mdc
1231 libscanner.o : libscanner.c
1232 $(CC) $(CFLAGS) -c libscanner.c
1234 ## Processing numbers
1236 Converting a `TK_number` token to a numerical value is a slightly
1237 higher level task than lexical analysis, and slightly lower than
1238 grammar parsing, so put it here - as an index if you like.
1240 Importantly it will be used by the same testing rig that is used for
1241 testing the token scanner.
1243 The numeric value that we will convert all numbers into is the `mpq_t`
1244 from the GNU high precision number library "libgmp".
1246 ###### number includes
1250 Firstly we need to be able to parse a string of digits in a given base
1251 and possibly with a decimal marker. We store this in an `mpz_t`
1252 integer and report the number of digits after the decimal mark.
1254 On error we return zero and ensure that the 'mpz_t' has been freed, or
1255 had never been initialised.
1257 ###### number functions
1259 static int parse_digits(mpz_t num, struct text tok, int base,
1262 /* Accept digits up to 'base', ignore '_' and
1263 * ' ' if they appear between two legal digits,
1264 * and if `placesp` is not NULL, allow a single
1265 * '.' or ',' and report the number of digits
1267 * Return number of characters processed (p),
1268 * or 0 if something illegal was found.
1271 int decimal = -1; // digits after marker
1272 enum {Digit, Space, Other} prev = Other;
1275 for (p = 0; p < tok.len; p++) {
1277 char c = tok.txt[p];
1279 if (c == '_' || c == ' ') {
1285 if (c == '.' || c == ',') {
1288 if (!placesp || decimal >= 0)
1296 else if (isupper(c))
1298 else if (islower(c))
1309 mpz_mul_ui(num, num, base);
1313 mpz_add_ui(num, num, dig);
1332 ###### number includes
1335 To parse a full number we need to consider the optional base, the
1336 mantissa, and the optional exponent. We will treat these one at a
1339 The base is indicated by a letter after a leading zero, which must be
1340 followed by a base letter or a period. The base also determines the
1341 character which will mark an exponent.
1349 if (tok.txt[0] == '0' && tok.len > 1) {
1351 switch(tok.txt[1]) {
1382 // another digit is not permitted
1386 // must be decimal marker or trailing
1387 // letter, which are OK;
1394 After the base is the mantissa, which may contain a decimal mark, so
1395 we need to record the number of places. We won't impose the number of
1396 places until we have the exponent as well.
1403 ###### parse mantissa
1405 d = parse_digits(mant, tok, base, &places);
1411 mpq_set_z(num, mant);
1414 After the mantissa number may come an exponent which may be positive
1415 or negative. We assume at this point that we have seen the exponent
1423 ###### parse exponent
1425 if (tok.txt[0] == '+') {
1428 } else if (tok.txt[0] == '-') {
1434 d = parse_digits(exp, tok, 10, NULL);
1439 if (!mpz_fits_slong_p(exp)) {
1444 lexp = mpz_get_si(exp) * esign;
1450 Now that we have the mantissa and the exponent we can multiply them
1451 together, also allowing for the number of digits after the decimal
1454 For base 10, we simply subtract the decimal places from the exponent.
1455 For the other bases, as the exponent is alway based on 2, even for
1456 octal and hex, we need a bit more detail.
1457 We then recover the sign from the exponent, as division is quite
1458 different from multiplication.
1460 ###### calc exponent
1479 Imposing the exponent on the number is also very different for base 10
1480 than for the others. For the binary shift `gmp` provides a simple
1481 function. For base 10 we use something like Russian Peasant
1484 ###### calc exponent
1488 mpq_set_ui(tens, 10, 1);
1492 mpq_mul(num, num, tens);
1494 mpq_div(num, num, tens);
1499 mpq_mul(tens, tens, tens);
1504 mpq_mul_2exp(num, num, lexp);
1506 mpq_div_2exp(num, num, lexp);
1509 Now we are ready to parse a number: the base, mantissa, and exponent.
1510 If all goes well we check for the possible trailing letters and
1511 return. Return value is 1 for success and 0 for failure.
1514 ###### number functions
1515 int number_parse(mpq_t num, char tail[3], struct text tok)
1522 if (tok.len > 1 && (tok.txt[0] == expc ||
1523 tok.txt[0] == toupper(expc))) {
1530 for (i = 0; i < 2; i++) {
1533 if (!isalpha(tok.txt[i]))
1535 tail[i] = tok.txt[i];
1545 Number parsing goes in `libnumber.c`
1547 ###### File: libnumber.c
1555 ###### File: number.h
1556 int number_parse(mpq_t num, char tail[3], struct text tok);
1558 ###### File: scanner.mk
1560 libnumber.o : libnumber.c
1561 $(CC) $(CFLAGS) -c libnumber.c
1563 ## Processing strings
1565 Both `TK_string` and `TK_multi_string` require post-processing which
1566 can be one of two types: literal or with escapes processed.
1567 Even literal processing is non-trivial as the file may contain indents
1568 which need to be stripped.
1570 Errors can only occur when processing escapes. Any unrecognised
1571 character following the escape character will cause an error.
1573 Processing escapes and striping indents can only make the string
1574 shorter, not longer, so we allocate a buffer which is the same size as
1575 the string and process into that.
1577 To request escape processing, we pass the character we want to use for
1578 quoting, usually '`\`'. To avoid escape processing we pass a zero.
1581 int string_parse(struct token *tok, char escape,
1582 struct text *str, char tail[3])
1585 struct text t = tok->txt;
1589 if (tok->num == TK_string) {
1594 str->txt = malloc(t.len);
1607 The tail of the string can be 0, 1, or 2 letters
1610 if (i >= 0 && isalpha(t.txt[i-1]))
1612 if (i >= 0 && isalpha(t.txt[i-1]))
1614 strncpy(tail, t.txt+i, t.len-i);
1623 Stripping the quote of a single-line string is trivial.
1624 The only part that is at all interesting is that quote character must
1628 if (t.txt[t.len-1] != quote)
1638 For a multi-line string we have a little more work to do. We need to
1639 remove 3 quotes, not 1, and need to count the indent of the close
1640 quote as it will need to be stripped from all lines.
1644 t.txt[1] != quote || t.txt[2] != quote ||
1645 !is_newline(t.txt[3]))
1650 if (i <= 0 || t.txt[i-1] != quote)
1653 if (i <= 0 || t.txt[i-1] != quote)
1656 if (i <= 0 || t.txt[i-1] != quote)
1660 while (i > 0 && !is_newline(t.txt[i-1]))
1664 if (t.txt[i] == ' ')
1666 if (t.txt[i] == '\t')
1667 indent = indent_tab(indent);
1676 Now we just take one byte at a time. trans-ASCII unicode won't look
1677 like anything we are interested in so it will just be copied byte by
1682 for (i = 0; i < t.len; i++) {
1696 } else if (i+1 >= t.len) {
1697 // escape and end of string
1705 str->len = cp - str->txt;
1713 Every time we find a start of line, we strip spaces and tabs until the
1714 required indent is found.
1717 while (i < t.len && skipped < indent) {
1722 skipped = indent_tab(c);
1731 *cp++ = '\n'; break;
1733 *cp++ = '\r'; break;
1735 *cp++ = '\t'; break;
1737 *cp++ = '\b'; break;
1739 *cp++ = quote; break;
1741 *cp++ = '\f'; break;
1743 *cp++ = '\v'; break;
1745 *cp++ = '\a'; break;
1750 // 3 digit octal number
1753 if (t.txt[i+1] < '0' || t.txt[i+1] > '7' ||
1754 t.txt[i+2] < '0' || t.txt[i+1] > '7')
1756 n = (t.txt[i ]-'0') * 64 +
1757 (t.txt[i+1]-'0') * 8 +
1758 (t.txt[i+2]-'0') * 1;
1764 n = take_hex(2, t.txt+i+1, t.len-i-1);
1772 // 4 or 8 hex digits for unicode
1773 n = take_hex(c == 'u'?4:8, t.txt+i+1, t.len-i-1);
1776 memset(&pstate, 0, sizeof(pstate));
1777 n = wcrtomb(cp, n, &pstate);
1781 i += c == 'u' ? 4 : 8;
1786 else if (is_newline(c))
1796 For `\x` `\u` and `\U` we need to collect a specific number of
1799 ###### string functions
1801 static long take_hex(int digits, char *cp, int l)
1813 else if (isupper(c))
1824 #### File: libstring.c
1826 String parsing goes in `libstring.c`
1835 #include "scanner.h"
1839 ###### File: string.h
1840 int string_parse(struct token *tok, char escape,
1841 struct text *str, char tail[3]);
1843 ###### File: scanner.mk
1845 libstring.o : libstring.c
1846 $(CC) $(CFLAGS) -c libstring.c
1851 As "untested code is buggy code" we need a program to easily test
1852 the scanner library. This will simply parse a given file and report
1853 the tokens one per line.
1855 ###### File: scanner.c
1861 #include <sys/mman.h>
1867 #include "scanner.h"
1872 static void pr_err(char *msg)
1875 fprintf(stderr, "%s\n", msg);
1878 int main(int argc, char *argv[])
1883 struct token_state *state;
1884 const char *known[] = {
1893 struct token_config conf = {
1896 .words_marks = known,
1897 .number_chars = "., _+-",
1898 .known_count = sizeof(known)/sizeof(known[0]),
1899 .ignored = (0 << TK_line_comment)
1900 |(0 << TK_block_comment),
1902 struct section *table, *s, *prev;
1903 setlocale(LC_ALL,"");
1905 fprintf(stderr, "Usage: scanner file\n");
1908 fd = open(argv[1], O_RDONLY);
1910 fprintf(stderr, "scanner: cannot open %s: %s\n",
1911 argv[1], strerror(errno));
1914 len = lseek(fd, 0, 2);
1915 file = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
1916 table = code_extract(file, file+len, pr_err);
1919 (code_free(s->code), prev = s, s = s->next, free(prev))) {
1920 printf("Tokenizing: %.*s\n", s->section.len,
1922 state = token_open(s->code, &conf);
1924 struct token tk = token_next(state);
1925 printf("%d:%d ", tk.line, tk.col);
1926 token_trace(stdout, tk, 20);
1927 if (tk.num == TK_number) {
1930 if (number_parse(num, tail,tk.txt)) {
1931 printf(" %s ", tail);
1932 mpq_out_str(stdout, 10, num);
1935 printf(" BAD NUMBER");
1937 if (tk.num == TK_string ||
1938 tk.num == TK_multi_string) {
1942 if (tk.txt.txt[0] == '`')
1944 if (string_parse(&tk, esc,
1946 printf(" %s ", tail);
1947 text_dump(stdout, str, 20);
1950 printf(" BAD STRING");
1953 if (tk.num == TK_error)
1955 if (tk.num == TK_eof)
1961 ###### File: scanner.mk
1962 scanner.c : scanner.mdc
1965 scanner : scanner.o scanner.h libscanner.o libmdcode.o mdcode.h
1966 $(CC) $(CFLAGS) -o scanner scanner.o libscanner.o \
1967 libmdcode.o libnumber.o libstring.o -licuuc -lgmp
1968 scanner.o : scanner.c
1969 $(CC) $(CFLAGS) -c scanner.c