"2023-*{pdf,txt}" is easier to read and write than
Lit("2023-", Any(Either("pdf", "txt")))
How can we translate the former into the latter?
Group characters into [%g token “tokens” %]
Use tokens to create an [%g abstract_syntax_tree “abstract syntax tree” %]
[% figure slug=“parse-pipeline” img=“pipeline.svg” alt=“Parsing pipeline” caption=“Stages in parsing pipeline.” %]
Characters like { and * can be
processed immediately
But “regular” characters need to be accumulated
Lit("abc") rather than
Lit("a", Lit("b", Lit("c")))
When we encounter a special character or ‘}’, we close the current literal token
The , character closes a literal but doesn’t produce
a token
The result is the final (flat) list of tokens
We could pass around a list and append to it
But we also need to know the characters in each
Literal and the options in each
Either
So create a class rather than a function
[%inc tokenizer.py mark=tok %]
Call self._setup() at the start so that the
tokenizer can be re-used
Don’t call self._add() for regular
characters
Add literals when we see special characters
And after all the input has been parsed
[%inc tokenizer.py mark=add %]
self._add(None) means “add the literal but nothing
else”[% figure slug=“parse-tokenize” img=“tokenize.svg” alt=“Tokenizing” caption=“Steps in tokenizing a string.” %]
[%inc test_tokenizer.py mark=tests %]
[%inc parser.py mark=parse %]
front[0] is the token’s name, front[1:]
is any other data
back is the remaining tokens
Look for a _parse_thing method to handle
each token
while it is running
rather than a long chain of if statements
These are powerful techniques and we use them frequently
[%inc parser.py mark=simple %]
_parse can find themEither is Messy[%inc parser.py mark=either %]
back until it hits
EitherEnd[%inc better_parser.py mark=either %]
[%inc test_parser.py mark=sample %]
Match objectsa == b is “just” a.__eq__(b)Match class does shared work
Lit objects are checking for the
same text[%inc match.py mark=equal %]
[% figure slug=“parse-concept-map” img=“concept_map.svg” alt=“Concept map of parsing” caption=“Concept map.” %]