Adding Variables
Store and recall values.
Beyond Arithmetic
To support x = 5 and later x + 1, the interpreter needs identifiers and a place to store their values. That store is the environment.
We will extend the lexer, parser, and evaluator to handle names and assignment.
Lexing Identifiers
An identifier starts with a letter or underscore and continues with letters, digits, or underscores. We copy the name into the token.
A fixed-size buffer keeps the example simple; real lexers intern names.
#include <ctype.h>
#include <string.h>
typedef struct { TokKind kind; int value; char name[32]; } Token;
static Token lex_ident(void) {
Token t; t.kind = TOK_IDENT; int i = 0;
while (isalnum((unsigned char)peek()) || peek() == '_')
if (i < 31) t.name[i++] = advance(); else advance();
t.name[i] = '\0';
return t;
}All lessons in this course
- Tokenizing Input
- Parsing Expressions
- Evaluating the Tree
- Adding Variables