Tokenizing: Text into Words
The first stage of any language: chop the raw stream of characters into meaningful chunks โ numbers, names, operators, strings. It's the simplest part, and a great place to start building.
The first stage of turning source into a running program is tokenizing (also called lexing): scanning the raw stream of characters and grouping them into meaningful tokens - a number here, a name there, an operator, a string. It's like turning a sentence's letters into words before you worry about grammar. It's the simplest stage, which makes it the perfect place to start understanding - and building - a language.
From characters to tokens
Your source is just a string of characters. The lexer walks through it and emits tokens, skipping whitespace and comments, recognising each kind of thing.
# source text:
2 + 3 * 4
# tokens the lexer produces:
NUMBER(2) OP(+) NUMBER(3) OP(*) NUMBER(4) EOF+, emits an operator token; skips spaces and comments. Each token records what it is (its type) and its value. That stream of typed tokens is what the next stage works with - the parser never sees raw characters, only clean tokens. It's a humble but essential first step.Recognising the pieces
A lexer handles a handful of token categories, each with a simple rule for how to scan it.
| Token kind | How the lexer recognises it |
|---|---|
| Number | A run of digits (and maybe a dot) |
| Identifier / keyword | A letter, then letters/digits; is it a keyword? |
| String | Text between quotes |
| Operator / punctuation | + - * ( ) etc. |
The stack's <a href='/stack/larzcalc'>larzcalc</a> and <a href='/stack/larzscript'>larzscript</a> both start exactly here - and larzscript adds a twist that shows the power of a custom lexer: it recognises <code>$1.50</code> as a first-class <i>money</i> token, which is what lets money be native to the language. Whatever special values your language needs, the lexer is where you teach it to see them.
The first buildable stage
- Tokenizing turns the raw character stream into meaningful tokens.
- A lexer is a loop - read a chunk, recognise its kind, emit a token, repeat.
- Categories: numbers, identifiers/keywords, strings, operators - each a simple rule.
- Custom tokens give a language its flavour (larzscript lexes
$1.50as money).
๐งฉ Do it with LarzOS
Turn this lesson into action with the exact free tools and AI workflows for the job:
๐ฏ Key takeaways
- Tokenizing (lexing) is the first stage: scan raw characters and group them into meaningful tokens.
- A lexer is a simple loop - read a chunk, recognise its kind (number, name, operator, string), emit a token, repeat.
- It skips whitespace and comments and hands the parser a clean stream of typed tokens, never raw characters.
- Custom token kinds give a language its flavour - larzscript lexes $1.50 as a first-class money token.
Frequently asked
Why separate lexing from parsing - why not just parse the raw text directly?
You could parse raw characters directly, and some approaches do, but separating lexing from parsing makes each stage dramatically simpler and clearer, which is why it's the standard approach - it's a clean application of separating concerns. The lexer's job is purely about recognising the low-level pieces: is this chunk of characters a number, a name, an operator, a string? It deals with character-level details - skipping whitespace, handling comments, grouping digits into a number, recognising keywords - and produces a tidy stream of typed tokens. The parser's job is about structure: given these tokens, how do they fit together into valid constructs (expressions, statements)? By splitting these, each stage handles one level of concern and stays simple. The parser gets to work with clean, meaningful tokens ('NUMBER, PLUS, NUMBER') instead of wrestling with raw characters and worrying about whitespace and comments while also trying to understand grammar - it can focus purely on structure. And the lexer gets to focus purely on character-level recognition without caring about grammar. Mixing them would mean the parser has to handle both 'is this a number or a name?' and 'do these fit into a valid expression?' at once, tangling two different kinds of logic and making the code much harder to write and understand. It's the same reason you separate any two distinct responsibilities: each part becomes simpler, more focused, and easier to get right and change. There are also practical benefits: the lexer can handle things like ignoring whitespace and comments once, so the parser never has to think about them; error messages can be clearer (a lexing error like 'unexpected character' versus a parsing error like 'unexpected token'); and you can reason about and test each stage independently. This two-stage front-end (lex then parse) is so useful that it's the near-universal pattern in language implementations. That said, the separation isn't an absolute law - some simple parsers do work directly on characters, and there are advanced techniques that combine the stages - but for learning and for most real languages, separating lexing (characters to tokens) from parsing (tokens to tree) keeps both stages simple and is the recommended, standard approach. Think of it as: the lexer reads the letters and forms words; the parser arranges words into sentences - two clean jobs rather than one tangled one. The stack's larzcalc and larzscript both follow this separation precisely, which is part of what makes them readable.
How does the lexer know where one token ends and the next begins?
The lexer figures out token boundaries by recognising the pattern of each token type as it scans, greedily consuming characters that belong to the current token until it hits a character that can't be part of it - a process that's simpler than it sounds because most token types have clear rules. Here's how it works: the lexer reads left to right, and at each point it looks at the current character to decide what kind of token is starting, then keeps consuming characters as long as they fit that token. For a number, it sees a digit and then keeps taking characters as long as they're digits (or a decimal point), stopping when it hits something that isn't part of a number - a space, an operator, a letter - which marks the number's end. For an identifier or keyword, it sees a letter and keeps taking letters and digits until it hits a non-identifier character, which ends the name (then it checks whether that name is a keyword). For a string, it sees an opening quote and takes everything until the closing quote. For operators and punctuation, they're usually one or two characters with fixed patterns. So the boundaries emerge naturally: a token ends when the lexer encounters a character that can't extend the current token. Whitespace helps too - a space clearly separates tokens and is skipped - but tokens can also be adjacent without spaces (like '2+3'), and the lexer handles that because after consuming the '2' as a number, the '+' can't be part of a number, so the number ends and a new operator token begins. The lexer essentially asks, at each character, 'does this continue the current token, or start a new one?' and uses each token type's simple rule to decide. A subtlety is multi-character operators (like '==' versus '='): the lexer typically looks at two characters to check for the longer operator first, so it correctly recognises '==' as one token rather than two '=' tokens - this 'longest match' idea (prefer the longest valid token) handles such cases. And for things like '$1.50' in larzscript, the lexer has a rule: after '$', consume the digits and dot to form a money token, ending when a non-money character appears. So the mechanism is: identify what token is starting from the first character, greedily consume characters that fit that token's pattern (preferring longer matches for multi-character operators), and stop when a character doesn't fit, marking the boundary. Each token type contributes its recognition rule, and the lexer applies them as it scans. This is exactly what you see in the stack's lexers - a loop that dispatches on the current character and consumes the matching run - and it's why lexing is the simplest, most approachable stage to understand and build: it's mostly straightforward character-by-character recognition with clear rules for where each kind of token starts and ends.
Related lessons
What Is a Programming Language, Really?
A language feels like magic โ you type words and the machine obeys. But underneath, it's aโฆ
How Programming Languages WorkParsing: Words into Structure
The heart of a language: take the flat list of tokens and build a *tree* that captures theโฆ