← back to lessons
lesson 02 — beginner

Token types and values

Understand the full TokenType enum, how token values are stored, and what memory ownership means in practice.

~10 min · lexer.h

A Token in first is a simple struct with two fields:

typedef struct {
  char *value;      // heap-allocated string
  TokenType type;   // one of the TT_* enum values
} Token;

The value is always a string, even for numbers. The lexer does no type conversion — that is the interpreter's responsibility.

Every token type

The full TokenType enum is defined in include/lexer.h. Each variant has a specific character pattern it matches:

exercise

Write a small C program that creates a lexer for the string "(10 + 3) * 2 >= 20" and prints every non-whitespace token's type and value until TT_EOI. Feed the string via a FILE* using fmemopen(). Notice how >= comes back as a single TT_GREATERTHAN_EQUAL token rather than two.

A note on TT_EOI

When fgetc() returns EOF, lex_next_token() creates a token of type TT_EOI. The parser and any other consumer should treat this as the termination signal and stop calling lex_next_token(). Calling it again after EOI is undefined behaviour — the FILE* is exhausted.