|
20 | 20 | #include <ctype.h>
|
21 | 21 | #include <stdbool.h>
|
22 | 22 | #include <stdio.h>
|
| 23 | +#include <stdlib.h> |
23 | 24 | #include <strings.h>
|
24 | 25 | #include "parse.h"
|
25 | 26 | #include "utils.h"
|
@@ -110,13 +111,15 @@ static void print_token(struct Token *token) {
|
110 | 111 | }
|
111 | 112 |
|
112 | 113 | void parse(char *code) {
|
113 |
| - while (true) { |
114 |
| - struct Token token = token_get(code, &code); |
115 |
| - if (!code) break; |
116 |
| - if (token.type != TOK_WHITESPACE) print_token(&token); |
117 |
| - if (token.type == TOK_UNKNOWN) die("!!! Unknown token encountered !!!"); |
118 |
| - } |
119 |
| - return; |
| 114 | + struct TokenList token_list = token_get_list(code); |
| 115 | + if (!token_list.length) return; |
| 116 | + struct TokenListNode *token_list_node = token_list.head; |
| 117 | + if (token_list.dirty) fputs("!!! WARNING: Unknown token(s) encountered !!!\n", stderr); |
| 118 | + do { |
| 119 | + struct Token *token = token_list_node->token; |
| 120 | + if (token->type != TOK_WHITESPACE) print_token(token); |
| 121 | + token_list_node = token_list_node->next; |
| 122 | + } while (token_list_node); |
120 | 123 | }
|
121 | 124 |
|
122 | 125 | struct Token token_get(char *code, char **next) {
|
@@ -244,6 +247,35 @@ struct Token token_get(char *code, char **next) {
|
244 | 247 | return token;
|
245 | 248 | }
|
246 | 249 |
|
| 250 | +struct TokenList token_get_list(char *code) { |
| 251 | + struct TokenList list = {.length = 0, .dirty = false}; |
| 252 | + |
| 253 | + while (code) { |
| 254 | + struct Token *token = malloc(sizeof(struct Token)); |
| 255 | + if (!token) goto end; |
| 256 | + |
| 257 | + *token = token_get(code, &code); |
| 258 | + if (token->type == TOK_UNKNOWN) list.dirty = true; |
| 259 | + |
| 260 | + struct TokenListNode *new_node = malloc(sizeof(struct TokenListNode)); |
| 261 | + if (!new_node) goto end; |
| 262 | + if (list.tail) { |
| 263 | + list.tail->next = new_node; |
| 264 | + new_node->prev = list.tail; |
| 265 | + list.tail = new_node; |
| 266 | + } else { |
| 267 | + list.head = new_node; |
| 268 | + list.tail = new_node; |
| 269 | + new_node->prev = NULL; |
| 270 | + } |
| 271 | + new_node->token = token; |
| 272 | + new_node->next = NULL; |
| 273 | + list.length += 1; |
| 274 | + } |
| 275 | + |
| 276 | + end: return list; |
| 277 | +}; |
| 278 | + |
247 | 279 | size_t scan_string(char *str, bool (cmpfunc)(char)) {
|
248 | 280 | size_t len = 0;
|
249 | 281 | while (true) {
|
|
0 commit comments