Skip to content

Commit b99bc52

Browse files
make this O(1)
1 parent 5143f97 commit b99bc52

File tree

2 files changed

+15
-20
lines changed

2 files changed

+15
-20
lines changed

include/basic/tokenizer.h

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -179,21 +179,18 @@ typedef void (*keyword_handler_t)(struct basic_ctx*);
179179

180180
GENERATE_ENUM_LIST(TOKEN, token_t)
181181

182-
/* Pair of token id and its dispatcher (can be NULL) */
183-
struct keyword_dispatch_t {
184-
enum token_t token;
185-
keyword_handler_t handler;
186-
};
182+
/* Uniform handler type */
183+
typedef void (*keyword_handler_t)(struct basic_ctx *);
187184

188-
/* Expand one TOKEN() entry into a { token, handler } initializer */
189-
#define GENERATE_DISPATCH_ENTRY(NAME, FLAG, DISPATCHER) { NAME, (keyword_handler_t)(DISPATCHER) },
185+
/* Build a flat handler table indexed by token id */
186+
#define GENERATE_HANDLER_ENTRY(NAME, FLAG, DISPATCHER) (keyword_handler_t)(DISPATCHER),
190187

191-
/* Emit a const array named ARRAY_NAME with one element per TOKEN() entry */
192-
#define GENERATE_DISPATCH_TABLE(ARRAY_NAME) \
193-
const struct keyword_dispatch_t ARRAY_NAME[] = { \
194-
TOKEN(GENERATE_DISPATCH_ENTRY) \
188+
#define GENERATE_HANDLER_TABLE(ARRAY_NAME) \
189+
static const keyword_handler_t ARRAY_NAME[] = { \
190+
TOKEN(GENERATE_HANDLER_ENTRY) \
195191
};
196192

193+
/* Size helper */
197194
#define DISPATCH_TABLE_COUNT(ARRAY_NAME) (sizeof(ARRAY_NAME) / sizeof((ARRAY_NAME)[0]))
198195

199196
/**

src/basic/statement.c

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,17 @@ void statement(struct basic_ctx* ctx)
88

99
basic_debug("line %ld statement(%d)\n", ctx->current_linenum, token);
1010

11-
GENERATE_DISPATCH_TABLE(keyword_dispatch);
12-
for (size_t t = 0; t < DISPATCH_TABLE_COUNT(keyword_dispatch); ++t) {
13-
if (token == keyword_dispatch[t].token) {
14-
if (keyword_dispatch[t].handler != NULL) {
15-
keyword_dispatch[t].handler(ctx);
16-
return;
17-
}
11+
GENERATE_HANDLER_TABLE(dispatch_by_token)
12+
if (token < DISPATCH_TABLE_COUNT(dispatch_by_token)) {
13+
if (dispatch_by_token[token] != NULL) {
14+
dispatch_by_token[token](ctx);
15+
return;
1816
}
1917
}
2018

21-
/* If we got here, token wasn’t found in the table at all */
2219
dprintf("Unknown keyword: %d\n", token);
23-
return tokenizer_error_print(ctx, "Unknown keyword");
20+
tokenizer_error_print(ctx, "Unknown keyword");
21+
2422
}
2523

2624
void line_statement(struct basic_ctx* ctx)

0 commit comments

Comments
 (0)