logo

drewdevault.com

[mirror] blog and personal website of Drew DeVault git clone https://hacktivis.me/git/mirror/drewdevault.com.git

Our-self-hosted-parser-design.gmi (19128B)


  1. One of the things we’re working on in my new programming language is a self-hosting compiler. Having a self-hosted compiler is a critical step in the development of (some) programming languages: it signals that the language is mature enough to be comfortably used to implement itself. While this isn’t right for some languages (e.g. shell scripts), for a systems programming language like ours, this is a crucial step in our bootstrapping plan. Our self-hosted parser design was completed this week, and today I’ll share some details about how it works and how it came to be.
  2. This is the third parser which has been implemented for this language. We wrote a sacrificial compiler prototype upfront to help inform the language design, and that first compiler used yacc for its parser. Using yacc was helpful at first because it makes it reasonably simple to iterate on the parser when the language is still undergoing frequent and far-reaching design changes. Another nice side-effect starting with a yacc parser is that it makes it quite easy to produce a formal grammar when you settle on the design. Here’s a peek at some of our original parser code:
  3. ```
  4. struct_type
  5. : T_STRUCT '{' struct_fields '}' {
  6. $$.flags = 0;
  7. $$.storage = TYPE_STRUCT;
  8. allocfrom((void **)&$$.fields, &$3, sizeof($3));
  9. }
  10. | T_UNION '{' struct_fields '}' {
  11. $$.flags = 0;
  12. $$.storage = TYPE_UNION;
  13. allocfrom((void **)&$$.fields, &$3, sizeof($3));
  14. }
  15. ;
  16. struct_fields
  17. : struct_field
  18. | struct_field ',' { $$ = $1; }
  19. | struct_field ',' struct_fields {
  20. $$ = $1;
  21. allocfrom((void **)&$$.next, &$3, sizeof($3));
  22. }
  23. ;
  24. struct_field
  25. : T_IDENT ':' type {
  26. $$.name = $1;
  27. allocfrom((void**)&$$.type, &$3, sizeof($3));
  28. $$.next = NULL;
  29. }
  30. ;
  31. ```
  32. This approach has you writing code which is already almost a formal grammar in its own right. If we strip out the C code, we get the following:
  33. ```
  34. struct_type
  35. : T_STRUCT '{' struct_fields '}'
  36. | T_UNION '{' struct_fields '}'
  37. ;
  38. struct_fields
  39. : struct_field
  40. | struct_field ','
  41. | struct_field ',' struct_fields
  42. ;
  43. struct_field
  44. : T_IDENT ':' type
  45. ;
  46. ```
  47. This gives us a reasonably clean path to writing a formal grammar (and specification) for the language, which is what we did next.
  48. > 6.1.15: Struct and union types
  49. >
  50. > struct-union-type:
  51. > struct { struct-union-fields }
  52. > union { struct-union-fields }
  53. >
  54. > struct-union-fields:
  55. > struct-union-field ,[opt]
  56. > struct-union-field , struct-union-fields
  57. >
  58. > struct-union-field:
  59. > offset-specifier[opt] name : type
  60. > offset-specifier[opt] struct-union-type
  61. > offset-specifier[opt] identifier
  62. >
  63. > offset-specifier:
  64. > @offset ( expression )
  65. All of these samples describe a struct type. The following example shows what this grammar looks like in real code — starting from the word “struct” and including up to the “}” at the end.
  66. ```
  67. type coordinates = struct {
  68. x: int,
  69. y: int,
  70. z: int,
  71. };
  72. ```
  73. In order to feed our parser tokens to work with, we also need a lexer, or a lexical analyzer. This turns a series of characters like “struct” into a single token, like the T_STRUCT we used in the yacc code. Like the original compiler used yacc as a parser generator, we also used lex as a lexer generator. It’s simply a list of regexes and the names of the tokens that match those regexes, plus a little bit of extra code to do things like turning “1234” into an int with a value of 1234. Our lexer also kept track of line and column numbers as it consumed characters from input files.
  74. ```
  75. "struct" { _lineno(); return T_STRUCT; }
  76. "union" { _lineno(); return T_UNION; }
  77. "{" { _lineno(); return '{'; }
  78. "}" { _lineno(); return '}'; }
  79. [a-zA-Z][a-zA-Z0-9_]* {
  80. _lineno();
  81. yylval.sval = strdup(yytext);
  82. return T_IDENTIFIER;
  83. }
  84. ```
  85. After we settled on the design with our prototype compiler, which was able to compile some simple test programs to give us a feel for our language design, we set it aside and wrote the specification, and, alongside it, a second compiler. This new compiler was written in C — the language was not ready to self-host yet — and uses a hand-written recursive descent parser.
  86. To simplify the parser, we deliberately designed a context-free LL(1) grammar, which means it (a) can parse an input unambiguously without needing additional context, and (b) only requires one token of look-ahead. This makes our parser design a lot simpler, which was a deliberate goal of the language design. Our hand-rolled lexer is slightly more complicated: it requires two characters of lookahead to distinguish between the “.”, “..”, and “…” tokens.
  87. I’ll skip most of the design for this parser, because the hosted parser is pretty similar and more interesting. Let’s start by taking a look at our hosted lexer. The goal of our lexer is to initialize it with an input source (e.g. a file), from which it can read a stream of characters. Then, each time we need a token, we’ll ask it to read the next one out. It will read as many characters as it needs to unambiguously identify the next token, then hand it up to the caller.
  88. Our specification provides some information to guide the lexer design:
  89. > A token is the smallest unit of meaning in the **** grammar. The lexical analysis phase processes a UTF-8 source file to produce a stream of tokens by matching the terminals with the input text.
  90. >
  91. > Tokens may be separated by white-space characters, which are defined as the Unicode code-points U+0009 (horizontal tabulation), U+000A (line feed), and U+0020 (space). Any number of whitespace characters may be inserted between tokens, either to disambiguate from subsequent tokens, or for aesthetic purposes. This whitespace is discarded during the lexical analysis phase.
  92. >
  93. > Within a single token, white-space is meaningful. For example, the string-literal token is defined by two quotation marks " enclosing any number of literal characters. The enclosed characters are considered part of the string-literal token and any whitespace therein is not discarded.
  94. >
  95. > The lexical analysis process consumes Unicode characters from the source file input until it is exhausted, performing the following steps in order. At each step, it shall consume and discard white-space characters until a non-white-space characters is found, then consume the longest sequence of characters which constitutes a token and emit it to the token stream.
  96. There are a few different kinds of tokens our lexer is going to need to handle: operators, like “+” and “-"; keywords, like “struct” and “return”; user-defined identifiers, like variable names; and constants, like string and numeric literals.
  97. In short, given the following source code:
  98. ```
  99. fn add2(x: int, y: int) int = x + y;
  100. ```
  101. We need to return the following sequence of tokens:
  102. ```
  103. fn (keyword)
  104. add2 (identifier)
  105. ( (operator)
  106. x
  107. :
  108. int
  109. ,
  110. y
  111. int
  112. )
  113. int
  114. =
  115. x
  116. +
  117. y
  118. ;
  119. ```
  120. This way, our parser doesn’t have to deal with whitespace, or distinguishing “int” (keyword) from “integer” (identifier), or handling invalid tokens like “$”. To actually implement this behavior, we’ll start with an initialization function which populates a state structure.
  121. ```
  122. // Initializes a new lexer for the given input stream. The path is borrowed.
  123. export fn init(in: *io::stream, path: str, flags: flags...) lexer = {
  124. return lexer {
  125. in = in,
  126. path = path,
  127. loc = (1, 1),
  128. un = void,
  129. rb = [void...],
  130. };
  131. };
  132. export type lexer = struct {
  133. in: *io::stream,
  134. path: str,
  135. loc: (uint, uint),
  136. rb: [2](rune | io::EOF | void),
  137. };
  138. ```
  139. This state structure holds, respectively:
  140. * The input I/O stream
  141. * The path to the current input file
  142. * The current (line, column) number
  143. * A buffer of un-read characters from the input, for lookahead
  144. The main entry point for doing the actual lexing will look like this:
  145. ```
  146. // Returns the next token from the lexer.
  147. export fn lex(lex: *lexer) (token | error);
  148. // A single lexical token, the value it represents, and its location in a file.
  149. export type token = (ltok, value, location);
  150. // A token value, used for tokens such as '1337' (an integer).
  151. export type value = (str | rune | i64 | u64 | f64 | void);
  152. // A location in a source file.
  153. export type location = struct {
  154. path: str,
  155. line: uint,
  156. col: uint
  157. };
  158. // A lexical token class.
  159. export type ltok = enum uint {
  160. UNDERSCORE,
  161. ABORT,
  162. ALLOC,
  163. APPEND,
  164. AS,
  165. // ... continued ...
  166. EOF,
  167. };
  168. ```
  169. The idea is that when the caller needs another token, they will call lex, and receive either a token or an error. The purpose of our lex function is to read out the next character and decide what kind of tokens it might be the start of, and dispatch to more specific lexing functions to handle each case.
  170. ```
  171. export fn lex(lex: *lexer) (token | error) = {
  172. let loc = location { ... };
  173. let rn: rune = match (nextw(lex)?) {
  174. _: io::EOF => return (ltok::EOF, void, mkloc(lex)),
  175. rl: (rune, location) => {
  176. loc = rl.1;
  177. rl.0;
  178. },
  179. };
  180. if (is_name(rn, false)) {
  181. unget(lex, rn);
  182. return lex_name(lex, loc, true);
  183. };
  184. if (ascii::isdigit(rn)) {
  185. unget(lex, rn);
  186. return lex_literal(lex, loc);
  187. };
  188. let tok: ltok = switch (rn) {
  189. * => return syntaxerr(loc, "invalid character"),
  190. '"', '\'' => {
  191. unget(lex, rn);
  192. return lex_rn_str(lex, loc);
  193. },
  194. '.', '<', '>' => return lex3(lex, loc, rn),
  195. '^', '*', '%', '/', '+', '-', ':', '!', '&', '|', '=' => {
  196. return lex2(lex, loc, rn);
  197. },
  198. '~' => ltok::BNOT,
  199. ',' => ltok::COMMA,
  200. '{' => ltok::LBRACE,
  201. '[' => ltok::LBRACKET,
  202. '(' => ltok::LPAREN,
  203. '}' => ltok::RBRACE,
  204. ']' => ltok::RBRACKET,
  205. ')' => ltok::RPAREN,
  206. ';' => ltok::SEMICOLON,
  207. '?' => ltok::QUESTION,
  208. };
  209. return (tok, void, loc);
  210. };
  211. ```
  212. Aside from the EOF case, and simple single-character operators like “;”, both of which this function handles itself, its role is to dispatch work to various sub-lexers.
  213. Each sub-lexer handles a more specific case. The lex_name function handles things which look like identifiers, including keywords; the lex_literal function handles things which look like literals (e.g. “1234”); lex_rn_str handles rune and string literals (e.g. “hello world” and ‘\n’); and lex2 and lex3 respectively handle two- and three-character operators like “&&” and “>>=”. The rest of this switch statement handles single-character operators like “;” directly.
  214. lex_name is the most complicated of these. Because the only thing which distinguishes a keyword from an identifier is that the former matches a specific list of strings, we start by reading a “name” into a buffer, then binary searching against a list of known keywords to see if it matches something there. To facilitate this, “bmap” is a pre-sorted array of keyword names.
  215. ```
  216. const bmap: [_]str = [
  217. // Keep me alpha-sorted and consistent with the ltok enum.
  218. "_",
  219. "abort",
  220. "alloc",
  221. "append",
  222. "as",
  223. "assert",
  224. "bool",
  225. // ...
  226. ];
  227. fn lex_name(lex: *lexer, loc: location, keyword: bool) (token | error) = {
  228. let buf = strio::dynamic();
  229. match (next(lex)) {
  230. r: rune => {
  231. assert(is_name(r, false));
  232. strio::appendrune(buf, r);
  233. },
  234. _: (io::EOF | io::error) => abort(), // Invariant
  235. };
  236. for (true) match (next(lex)?) {
  237. _: io::EOF => break,
  238. r: rune => {
  239. if (!is_name(r, true)) {
  240. unget(lex, r);
  241. break;
  242. };
  243. strio::appendrune(buf, r);
  244. },
  245. };
  246. let name = strio::finish(buf);
  247. if (!keyword) {
  248. return (ltok::NAME, name, loc);
  249. };
  250. return match (sort::search(bmap[..ltok::LAST_KEYWORD+1],
  251. size(str), &name, &namecmp)) {
  252. null => (ltok::NAME, name, loc),
  253. v: *void => {
  254. defer free(name);
  255. let tok = v: uintptr - &bmap[0]: uintptr;
  256. tok /= size(str): uintptr;
  257. (tok: ltok, void, loc);
  258. },
  259. };
  260. };
  261. ```
  262. The rest of the code is more of the same, but I’ve put it up here if you want to read it:
  263. => https://paste.sr.ht/~sircmpwn/25871787b0d41db2b0af573ba1c93e1b6438b942 lex.ha
  264. Let’s move on to parsing: we need to turn this one dimensional stream of tokens into an structured form: the Abstract Syntax Tree. Consider the following sample code:
  265. ```
  266. let x: int = add2(40, 2);
  267. ```
  268. Our token stream looks like this:
  269. ```
  270. let x : int = add2 ( 40 , 2 ) ;
  271. ```
  272. But what we need is something more structured, like this:
  273. ```
  274. binding
  275. name="x"
  276. type="int"
  277. initializer=call-expression
  278. => func="add2"
  279. parameters
  280. constant value="40"
  281. constant value="2"
  282. ```
  283. We know at each step what kinds of tokens are valid in each situation. After we see “let”, we know that we’re parsing a binding, so we look for a name (“x”) then a colon token, a type for the variable, an equals sign, and an expression which initializes it. To parse the initializer, we see an identifier, “add2”, then an open parenthesis, so we know we’re in a call expression, and we can start parsing arguments.
  284. To make our parser code expressive, and to handle errors neatly, we’re going to implement a few helper function that lets us describe these states in terms of what the parser wants from the lexer. We have a few functions to accomplish this:
  285. ```
  286. // Requires the next token to have a matching ltok. Returns that token, or an error.
  287. fn want(lexer: *lex::lexer, want: lex::ltok...) (lex::token | error) = {
  288. let tok = lex::lex(lexer)?;
  289. if (len(want) == 0) {
  290. return tok;
  291. };
  292. for (let i = 0z; i < len(want); i += 1) {
  293. if (tok.0 == want[i]) {
  294. return tok;
  295. };
  296. };
  297. let buf = strio::dynamic();
  298. defer io::close(buf);
  299. for (let i = 0z; i < len(want); i += 1) {
  300. fmt::fprintf(buf, "'{}'", lex::tokstr((want[i], void, mkloc(lexer))));
  301. if (i + 1 < len(want)) {
  302. fmt::fprint(buf, ", ");
  303. };
  304. };
  305. return syntaxerr(mkloc(lexer), "Unexpected '{}', was expecting {}",
  306. lex::tokstr(tok), strio::string(buf));
  307. };
  308. // Looks for a matching ltok from the lexer, and if not present, unlexes the
  309. // token and returns void. If found, the token is consumed from the lexer and is
  310. // returned.
  311. fn try(
  312. lexer: *lex::lexer,
  313. want: lex::ltok...
  314. ) (lex::token | error | void) = {
  315. let tok = lex::lex(lexer)?;
  316. assert(len(want) > 0);
  317. for (let i = 0z; i < len(want); i += 1) {
  318. if (tok.0 == want[i]) {
  319. return tok;
  320. };
  321. };
  322. lex::unlex(lexer, tok);
  323. };
  324. // Looks for a matching ltok from the lexer, unlexes the token, and returns
  325. // it; or void if it was not a ltok.
  326. fn peek(
  327. lexer: *lex::lexer,
  328. want: lex::ltok...
  329. ) (lex::token | error | void) = {
  330. let tok = lex::lex(lexer)?;
  331. lex::unlex(lexer, tok);
  332. if (len(want) == 0) {
  333. return tok;
  334. };
  335. for (let i = 0z; i < len(want); i += 1) {
  336. if (tok.0 == want[i]) {
  337. return tok;
  338. };
  339. };
  340. };
  341. ```
  342. Let’s say we’re looking for a binding like our sample code to show up next. The grammar from the spec is as follows:
  343. > 6.6.44: Variable binding
  344. >
  345. > binding-list:
  346. > static[opt] let bindings
  347. > static[opt] const bindings
  348. >
  349. > bidings:
  350. > binding ,[opt]
  351. > binding , bindings
  352. >
  353. > binding:
  354. > name = expression
  355. > name : type = expression
  356. And here’s the code that parses that:
  357. ```
  358. fn binding(lexer: *lex::lexer) (ast::expr | error) = {
  359. const is_static: bool = try(lexer, ltok::STATIC)? is lex::token;
  360. const is_const = switch (want(lexer, ltok::LET, ltok::CONST)?.0) {
  361. ltok::LET => false,
  362. ltok::CONST => true,
  363. };
  364. let bindings: []ast::binding = [];
  365. for (true) {
  366. const name = want(lexer, ltok::NAME)?.1 as str;
  367. const btype: nullable *ast::_type =
  368. if (try(lexer, ltok::COLON)? is lex::token) {
  369. alloc(_type(lexer)?);
  370. } else null;
  371. want(lexer, ltok::EQUAL)?;
  372. const init = alloc(expression(lexer)?);
  373. append(bindings, ast::binding {
  374. name = name,
  375. _type = btype,
  376. init = init,
  377. });
  378. match (try(lexer, ltok::COMMA)?) {
  379. _: void => break,
  380. _: lex::token => void,
  381. };
  382. };
  383. return ast::binding_expr {
  384. is_static = is_static,
  385. is_const = is_const,
  386. bindings = bindings,
  387. };
  388. };
  389. ```
  390. Hopefully the flow of this code is fairly apparent. The goal is to fill in the following AST structure:
  391. ```
  392. // A single variable biding. For example:
  393. //
  394. // foo: int = bar
  395. export type binding = struct {
  396. name: str,
  397. _type: nullable *_type,
  398. init: *expr,
  399. };
  400. // A variable binding expression. For example:
  401. //
  402. // let foo: int = bar, ...
  403. export type binding_expr = struct {
  404. is_static: bool,
  405. is_const: bool,
  406. bindings: []binding,
  407. };
  408. ```
  409. The rest of the code is pretty similar, though some corners of the grammar are a bit hairier than others. One example is how we parse infix operators for binary arithmetic expressions (such as “2 + 2”):
  410. ```
  411. fn binarithm(
  412. lexer: *lex::lexer,
  413. lvalue: (ast::expr | void),
  414. i: int,
  415. ) (ast::expr | error) = {
  416. // Precedence climbing parser
  417. // https://en.wikipedia.org/wiki/Operator-precedence_parser
  418. let lvalue = match (lvalue) {
  419. _: void => cast(lexer, void)?,
  420. expr: ast::expr => expr,
  421. };
  422. let tok = lex::lex(lexer)?;
  423. for (let j = precedence(tok); j >= i; j = precedence(tok)) {
  424. const op = binop_for_tok(tok);
  425. let rvalue = cast(lexer, void)?;
  426. tok = lex::lex(lexer)?;
  427. for (let k = precedence(tok); k > j; k = precedence(tok)) {
  428. lex::unlex(lexer, tok);
  429. rvalue = binarithm(lexer, rvalue, k)?;
  430. tok = lex::lex(lexer)?;
  431. };
  432. let expr = ast::binarithm_expr {
  433. op = op,
  434. lvalue = alloc(lvalue),
  435. rvalue = alloc(rvalue),
  436. };
  437. lvalue = expr;
  438. };
  439. lex::unlex(lexer, tok);
  440. return lvalue;
  441. };
  442. fn precedence(tok: lex::token) int = switch (tok.0) {
  443. ltok::LOR => 0,
  444. ltok::LXOR => 1,
  445. ltok::LAND => 2,
  446. ltok::LEQUAL, ltok::NEQUAL => 3,
  447. ltok::LESS, ltok::LESSEQ, ltok::GREATER, ltok::GREATEREQ => 4,
  448. ltok::BOR => 5,
  449. ltok::BXOR => 6,
  450. ltok::BAND => 7,
  451. ltok::LSHIFT, ltok::RSHIFT => 8,
  452. ltok::PLUS, ltok::MINUS => 9,
  453. ltok::TIMES, ltok::DIV, ltok::MODULO => 10,
  454. * => -1,
  455. };
  456. ```
  457. I don’t really grok this algorithm, to be honest, but hey, it works. Whenever I write a precedence climbing parser, I’ll stare at the Wikipedia page for 15 minutes, quickly write a parser, and then immediately forget how it works. Maybe I’ll write a blog post about it someday.
  458. Anyway, ultimately, this code lives in our standard library and is used for several things, including the our (early in development) self-hosted compiler. Here’s an example of its usage, taken from our documentation generator:
  459. ```
  460. fn scan(path: str) (ast::subunit | error) = {
  461. const input = match (os::open(path)) {
  462. s: *io::stream => s,
  463. err: fs::error => fmt::fatal("Error reading {}: {}",
  464. path, fs::strerror(err)),
  465. };
  466. defer io::close(input);
  467. const lexer = lex::init(input, path, lex::flags::COMMENTS);
  468. return parse::subunit(&lexer)?;
  469. };
  470. ```
  471. Where the “ast::subunit” type is:
  472. ```
  473. // A sub-unit, typically representing a single source file.
  474. export type subunit = struct {
  475. imports: []import,
  476. decls: []decl,
  477. };
  478. ```
  479. Pretty straightforward! Having this as part of the standard library should make it much easier for users to build language-aware tooling with the language itself. We also plan on having our type checker in the stdlib as well. This is something that I drew inspiration for from Golang — having a lot of their toolchain components in the standard library makes it really easy to write Go-aware tools.
  480. So, there you have it: the next stage in the development of our language. I hope you’re looking forward to it!