OCamlLangImpl2.rst 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. ===========================================
  2. Kaleidoscope: Implementing a Parser and AST
  3. ===========================================
  4. .. contents::
  5. :local:
  6. Chapter 2 Introduction
  7. ======================
  8. Welcome to Chapter 2 of the "`Implementing a language with LLVM in
  9. Objective Caml <index.html>`_" tutorial. This chapter shows you how to
  10. use the lexer, built in `Chapter 1 <OCamlLangImpl1.html>`_, to build a
  11. full `parser <http://en.wikipedia.org/wiki/Parsing>`_ for our
  12. Kaleidoscope language. Once we have a parser, we'll define and build an
  13. `Abstract Syntax
  14. Tree <http://en.wikipedia.org/wiki/Abstract_syntax_tree>`_ (AST).
  15. The parser we will build uses a combination of `Recursive Descent
  16. Parsing <http://en.wikipedia.org/wiki/Recursive_descent_parser>`_ and
  17. `Operator-Precedence
  18. Parsing <http://en.wikipedia.org/wiki/Operator-precedence_parser>`_ to
  19. parse the Kaleidoscope language (the latter for binary expressions and
  20. the former for everything else). Before we get to parsing though, lets
  21. talk about the output of the parser: the Abstract Syntax Tree.
  22. The Abstract Syntax Tree (AST)
  23. ==============================
  24. The AST for a program captures its behavior in such a way that it is
  25. easy for later stages of the compiler (e.g. code generation) to
  26. interpret. We basically want one object for each construct in the
  27. language, and the AST should closely model the language. In
  28. Kaleidoscope, we have expressions, a prototype, and a function object.
  29. We'll start with expressions first:
  30. .. code-block:: ocaml
  31. (* expr - Base type for all expression nodes. *)
  32. type expr =
  33. (* variant for numeric literals like "1.0". *)
  34. | Number of float
  35. The code above shows the definition of the base ExprAST class and one
  36. subclass which we use for numeric literals. The important thing to note
  37. about this code is that the Number variant captures the numeric value of
  38. the literal as an instance variable. This allows later phases of the
  39. compiler to know what the stored numeric value is.
  40. Right now we only create the AST, so there are no useful functions on
  41. them. It would be very easy to add a function to pretty print the code,
  42. for example. Here are the other expression AST node definitions that
  43. we'll use in the basic form of the Kaleidoscope language:
  44. .. code-block:: ocaml
  45. (* variant for referencing a variable, like "a". *)
  46. | Variable of string
  47. (* variant for a binary operator. *)
  48. | Binary of char * expr * expr
  49. (* variant for function calls. *)
  50. | Call of string * expr array
  51. This is all (intentionally) rather straight-forward: variables capture
  52. the variable name, binary operators capture their opcode (e.g. '+'), and
  53. calls capture a function name as well as a list of any argument
  54. expressions. One thing that is nice about our AST is that it captures
  55. the language features without talking about the syntax of the language.
  56. Note that there is no discussion about precedence of binary operators,
  57. lexical structure, etc.
  58. For our basic language, these are all of the expression nodes we'll
  59. define. Because it doesn't have conditional control flow, it isn't
  60. Turing-complete; we'll fix that in a later installment. The two things
  61. we need next are a way to talk about the interface to a function, and a
  62. way to talk about functions themselves:
  63. .. code-block:: ocaml
  64. (* proto - This type represents the "prototype" for a function, which captures
  65. * its name, and its argument names (thus implicitly the number of arguments the
  66. * function takes). *)
  67. type proto = Prototype of string * string array
  68. (* func - This type represents a function definition itself. *)
  69. type func = Function of proto * expr
  70. In Kaleidoscope, functions are typed with just a count of their
  71. arguments. Since all values are double precision floating point, the
  72. type of each argument doesn't need to be stored anywhere. In a more
  73. aggressive and realistic language, the "expr" variants would probably
  74. have a type field.
  75. With this scaffolding, we can now talk about parsing expressions and
  76. function bodies in Kaleidoscope.
  77. Parser Basics
  78. =============
  79. Now that we have an AST to build, we need to define the parser code to
  80. build it. The idea here is that we want to parse something like "x+y"
  81. (which is returned as three tokens by the lexer) into an AST that could
  82. be generated with calls like this:
  83. .. code-block:: ocaml
  84. let x = Variable "x" in
  85. let y = Variable "y" in
  86. let result = Binary ('+', x, y) in
  87. ...
  88. The error handling routines make use of the builtin ``Stream.Failure``
  89. and ``Stream.Error``s. ``Stream.Failure`` is raised when the parser is
  90. unable to find any matching token in the first position of a pattern.
  91. ``Stream.Error`` is raised when the first token matches, but the rest do
  92. not. The error recovery in our parser will not be the best and is not
  93. particular user-friendly, but it will be enough for our tutorial. These
  94. exceptions make it easier to handle errors in routines that have various
  95. return types.
  96. With these basic types and exceptions, we can implement the first piece
  97. of our grammar: numeric literals.
  98. Basic Expression Parsing
  99. ========================
  100. We start with numeric literals, because they are the simplest to
  101. process. For each production in our grammar, we'll define a function
  102. which parses that production. We call this class of expressions
  103. "primary" expressions, for reasons that will become more clear `later in
  104. the tutorial <OCamlLangImpl6.html#user-defined-unary-operators>`_. In order to parse an
  105. arbitrary primary expression, we need to determine what sort of
  106. expression it is. For numeric literals, we have:
  107. .. code-block:: ocaml
  108. (* primary
  109. * ::= identifier
  110. * ::= numberexpr
  111. * ::= parenexpr *)
  112. parse_primary = parser
  113. (* numberexpr ::= number *)
  114. | [< 'Token.Number n >] -> Ast.Number n
  115. This routine is very simple: it expects to be called when the current
  116. token is a ``Token.Number`` token. It takes the current number value,
  117. creates a ``Ast.Number`` node, advances the lexer to the next token, and
  118. finally returns.
  119. There are some interesting aspects to this. The most important one is
  120. that this routine eats all of the tokens that correspond to the
  121. production and returns the lexer buffer with the next token (which is
  122. not part of the grammar production) ready to go. This is a fairly
  123. standard way to go for recursive descent parsers. For a better example,
  124. the parenthesis operator is defined like this:
  125. .. code-block:: ocaml
  126. (* parenexpr ::= '(' expression ')' *)
  127. | [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
  128. This function illustrates a number of interesting things about the
  129. parser:
  130. 1) It shows how we use the ``Stream.Error`` exception. When called, this
  131. function expects that the current token is a '(' token, but after
  132. parsing the subexpression, it is possible that there is no ')' waiting.
  133. For example, if the user types in "(4 x" instead of "(4)", the parser
  134. should emit an error. Because errors can occur, the parser needs a way
  135. to indicate that they happened. In our parser, we use the camlp4
  136. shortcut syntax ``token ?? "parse error"``, where if the token before
  137. the ``??`` does not match, then ``Stream.Error "parse error"`` will be
  138. raised.
  139. 2) Another interesting aspect of this function is that it uses recursion
  140. by calling ``Parser.parse_primary`` (we will soon see that
  141. ``Parser.parse_primary`` can call ``Parser.parse_primary``). This is
  142. powerful because it allows us to handle recursive grammars, and keeps
  143. each production very simple. Note that parentheses do not cause
  144. construction of AST nodes themselves. While we could do it this way, the
  145. most important role of parentheses are to guide the parser and provide
  146. grouping. Once the parser constructs the AST, parentheses are not
  147. needed.
  148. The next simple production is for handling variable references and
  149. function calls:
  150. .. code-block:: ocaml
  151. (* identifierexpr
  152. * ::= identifier
  153. * ::= identifier '(' argumentexpr ')' *)
  154. | [< 'Token.Ident id; stream >] ->
  155. let rec parse_args accumulator = parser
  156. | [< e=parse_expr; stream >] ->
  157. begin parser
  158. | [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
  159. | [< >] -> e :: accumulator
  160. end stream
  161. | [< >] -> accumulator
  162. in
  163. let rec parse_ident id = parser
  164. (* Call. *)
  165. | [< 'Token.Kwd '(';
  166. args=parse_args [];
  167. 'Token.Kwd ')' ?? "expected ')'">] ->
  168. Ast.Call (id, Array.of_list (List.rev args))
  169. (* Simple variable ref. *)
  170. | [< >] -> Ast.Variable id
  171. in
  172. parse_ident id stream
  173. This routine follows the same style as the other routines. (It expects
  174. to be called if the current token is a ``Token.Ident`` token). It also
  175. has recursion and error handling. One interesting aspect of this is that
  176. it uses *look-ahead* to determine if the current identifier is a stand
  177. alone variable reference or if it is a function call expression. It
  178. handles this by checking to see if the token after the identifier is a
  179. '(' token, constructing either a ``Ast.Variable`` or ``Ast.Call`` node
  180. as appropriate.
  181. We finish up by raising an exception if we received a token we didn't
  182. expect:
  183. .. code-block:: ocaml
  184. | [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
  185. Now that basic expressions are handled, we need to handle binary
  186. expressions. They are a bit more complex.
  187. Binary Expression Parsing
  188. =========================
  189. Binary expressions are significantly harder to parse because they are
  190. often ambiguous. For example, when given the string "x+y\*z", the parser
  191. can choose to parse it as either "(x+y)\*z" or "x+(y\*z)". With common
  192. definitions from mathematics, we expect the later parse, because "\*"
  193. (multiplication) has higher *precedence* than "+" (addition).
  194. There are many ways to handle this, but an elegant and efficient way is
  195. to use `Operator-Precedence
  196. Parsing <http://en.wikipedia.org/wiki/Operator-precedence_parser>`_.
  197. This parsing technique uses the precedence of binary operators to guide
  198. recursion. To start with, we need a table of precedences:
  199. .. code-block:: ocaml
  200. (* binop_precedence - This holds the precedence for each binary operator that is
  201. * defined *)
  202. let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
  203. (* precedence - Get the precedence of the pending binary operator token. *)
  204. let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
  205. ...
  206. let main () =
  207. (* Install standard binary operators.
  208. * 1 is the lowest precedence. *)
  209. Hashtbl.add Parser.binop_precedence '<' 10;
  210. Hashtbl.add Parser.binop_precedence '+' 20;
  211. Hashtbl.add Parser.binop_precedence '-' 20;
  212. Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
  213. ...
  214. For the basic form of Kaleidoscope, we will only support 4 binary
  215. operators (this can obviously be extended by you, our brave and intrepid
  216. reader). The ``Parser.precedence`` function returns the precedence for
  217. the current token, or -1 if the token is not a binary operator. Having a
  218. ``Hashtbl.t`` makes it easy to add new operators and makes it clear that
  219. the algorithm doesn't depend on the specific operators involved, but it
  220. would be easy enough to eliminate the ``Hashtbl.t`` and do the
  221. comparisons in the ``Parser.precedence`` function. (Or just use a
  222. fixed-size array).
  223. With the helper above defined, we can now start parsing binary
  224. expressions. The basic idea of operator precedence parsing is to break
  225. down an expression with potentially ambiguous binary operators into
  226. pieces. Consider, for example, the expression "a+b+(c+d)\*e\*f+g".
  227. Operator precedence parsing considers this as a stream of primary
  228. expressions separated by binary operators. As such, it will first parse
  229. the leading primary expression "a", then it will see the pairs [+, b]
  230. [+, (c+d)] [\*, e] [\*, f] and [+, g]. Note that because parentheses are
  231. primary expressions, the binary expression parser doesn't need to worry
  232. about nested subexpressions like (c+d) at all.
  233. To start, an expression is a primary expression potentially followed by
  234. a sequence of [binop,primaryexpr] pairs:
  235. .. code-block:: ocaml
  236. (* expression
  237. * ::= primary binoprhs *)
  238. and parse_expr = parser
  239. | [< lhs=parse_primary; stream >] -> parse_bin_rhs 0 lhs stream
  240. ``Parser.parse_bin_rhs`` is the function that parses the sequence of
  241. pairs for us. It takes a precedence and a pointer to an expression for
  242. the part that has been parsed so far. Note that "x" is a perfectly valid
  243. expression: As such, "binoprhs" is allowed to be empty, in which case it
  244. returns the expression that is passed into it. In our example above, the
  245. code passes the expression for "a" into ``Parser.parse_bin_rhs`` and the
  246. current token is "+".
  247. The precedence value passed into ``Parser.parse_bin_rhs`` indicates the
  248. *minimal operator precedence* that the function is allowed to eat. For
  249. example, if the current pair stream is [+, x] and
  250. ``Parser.parse_bin_rhs`` is passed in a precedence of 40, it will not
  251. consume any tokens (because the precedence of '+' is only 20). With this
  252. in mind, ``Parser.parse_bin_rhs`` starts with:
  253. .. code-block:: ocaml
  254. (* binoprhs
  255. * ::= ('+' primary)* *)
  256. and parse_bin_rhs expr_prec lhs stream =
  257. match Stream.peek stream with
  258. (* If this is a binop, find its precedence. *)
  259. | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
  260. let token_prec = precedence c in
  261. (* If this is a binop that binds at least as tightly as the current binop,
  262. * consume it, otherwise we are done. *)
  263. if token_prec < expr_prec then lhs else begin
  264. This code gets the precedence of the current token and checks to see if
  265. if is too low. Because we defined invalid tokens to have a precedence of
  266. -1, this check implicitly knows that the pair-stream ends when the token
  267. stream runs out of binary operators. If this check succeeds, we know
  268. that the token is a binary operator and that it will be included in this
  269. expression:
  270. .. code-block:: ocaml
  271. (* Eat the binop. *)
  272. Stream.junk stream;
  273. (* Parse the primary expression after the binary operator *)
  274. let rhs = parse_primary stream in
  275. (* Okay, we know this is a binop. *)
  276. let rhs =
  277. match Stream.peek stream with
  278. | Some (Token.Kwd c2) ->
  279. As such, this code eats (and remembers) the binary operator and then
  280. parses the primary expression that follows. This builds up the whole
  281. pair, the first of which is [+, b] for the running example.
  282. Now that we parsed the left-hand side of an expression and one pair of
  283. the RHS sequence, we have to decide which way the expression associates.
  284. In particular, we could have "(a+b) binop unparsed" or "a + (b binop
  285. unparsed)". To determine this, we look ahead at "binop" to determine its
  286. precedence and compare it to BinOp's precedence (which is '+' in this
  287. case):
  288. .. code-block:: ocaml
  289. (* If BinOp binds less tightly with rhs than the operator after
  290. * rhs, let the pending operator take rhs as its lhs. *)
  291. let next_prec = precedence c2 in
  292. if token_prec < next_prec
  293. If the precedence of the binop to the right of "RHS" is lower or equal
  294. to the precedence of our current operator, then we know that the
  295. parentheses associate as "(a+b) binop ...". In our example, the current
  296. operator is "+" and the next operator is "+", we know that they have the
  297. same precedence. In this case we'll create the AST node for "a+b", and
  298. then continue parsing:
  299. .. code-block:: ocaml
  300. ... if body omitted ...
  301. in
  302. (* Merge lhs/rhs. *)
  303. let lhs = Ast.Binary (c, lhs, rhs) in
  304. parse_bin_rhs expr_prec lhs stream
  305. end
  306. In our example above, this will turn "a+b+" into "(a+b)" and execute the
  307. next iteration of the loop, with "+" as the current token. The code
  308. above will eat, remember, and parse "(c+d)" as the primary expression,
  309. which makes the current pair equal to [+, (c+d)]. It will then evaluate
  310. the 'if' conditional above with "\*" as the binop to the right of the
  311. primary. In this case, the precedence of "\*" is higher than the
  312. precedence of "+" so the if condition will be entered.
  313. The critical question left here is "how can the if condition parse the
  314. right hand side in full"? In particular, to build the AST correctly for
  315. our example, it needs to get all of "(c+d)\*e\*f" as the RHS expression
  316. variable. The code to do this is surprisingly simple (code from the
  317. above two blocks duplicated for context):
  318. .. code-block:: ocaml
  319. match Stream.peek stream with
  320. | Some (Token.Kwd c2) ->
  321. (* If BinOp binds less tightly with rhs than the operator after
  322. * rhs, let the pending operator take rhs as its lhs. *)
  323. if token_prec < precedence c2
  324. then parse_bin_rhs (token_prec + 1) rhs stream
  325. else rhs
  326. | _ -> rhs
  327. in
  328. (* Merge lhs/rhs. *)
  329. let lhs = Ast.Binary (c, lhs, rhs) in
  330. parse_bin_rhs expr_prec lhs stream
  331. end
  332. At this point, we know that the binary operator to the RHS of our
  333. primary has higher precedence than the binop we are currently parsing.
  334. As such, we know that any sequence of pairs whose operators are all
  335. higher precedence than "+" should be parsed together and returned as
  336. "RHS". To do this, we recursively invoke the ``Parser.parse_bin_rhs``
  337. function specifying "token\_prec+1" as the minimum precedence required
  338. for it to continue. In our example above, this will cause it to return
  339. the AST node for "(c+d)\*e\*f" as RHS, which is then set as the RHS of
  340. the '+' expression.
  341. Finally, on the next iteration of the while loop, the "+g" piece is
  342. parsed and added to the AST. With this little bit of code (14
  343. non-trivial lines), we correctly handle fully general binary expression
  344. parsing in a very elegant way. This was a whirlwind tour of this code,
  345. and it is somewhat subtle. I recommend running through it with a few
  346. tough examples to see how it works.
  347. This wraps up handling of expressions. At this point, we can point the
  348. parser at an arbitrary token stream and build an expression from it,
  349. stopping at the first token that is not part of the expression. Next up
  350. we need to handle function definitions, etc.
  351. Parsing the Rest
  352. ================
  353. The next thing missing is handling of function prototypes. In
  354. Kaleidoscope, these are used both for 'extern' function declarations as
  355. well as function body definitions. The code to do this is
  356. straight-forward and not very interesting (once you've survived
  357. expressions):
  358. .. code-block:: ocaml
  359. (* prototype
  360. * ::= id '(' id* ')' *)
  361. let parse_prototype =
  362. let rec parse_args accumulator = parser
  363. | [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
  364. | [< >] -> accumulator
  365. in
  366. parser
  367. | [< 'Token.Ident id;
  368. 'Token.Kwd '(' ?? "expected '(' in prototype";
  369. args=parse_args [];
  370. 'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
  371. (* success. *)
  372. Ast.Prototype (id, Array.of_list (List.rev args))
  373. | [< >] ->
  374. raise (Stream.Error "expected function name in prototype")
  375. Given this, a function definition is very simple, just a prototype plus
  376. an expression to implement the body:
  377. .. code-block:: ocaml
  378. (* definition ::= 'def' prototype expression *)
  379. let parse_definition = parser
  380. | [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
  381. Ast.Function (p, e)
  382. In addition, we support 'extern' to declare functions like 'sin' and
  383. 'cos' as well as to support forward declaration of user functions. These
  384. 'extern's are just prototypes with no body:
  385. .. code-block:: ocaml
  386. (* external ::= 'extern' prototype *)
  387. let parse_extern = parser
  388. | [< 'Token.Extern; e=parse_prototype >] -> e
  389. Finally, we'll also let the user type in arbitrary top-level expressions
  390. and evaluate them on the fly. We will handle this by defining anonymous
  391. nullary (zero argument) functions for them:
  392. .. code-block:: ocaml
  393. (* toplevelexpr ::= expression *)
  394. let parse_toplevel = parser
  395. | [< e=parse_expr >] ->
  396. (* Make an anonymous proto. *)
  397. Ast.Function (Ast.Prototype ("", [||]), e)
  398. Now that we have all the pieces, let's build a little driver that will
  399. let us actually *execute* this code we've built!
  400. The Driver
  401. ==========
  402. The driver for this simply invokes all of the parsing pieces with a
  403. top-level dispatch loop. There isn't much interesting here, so I'll just
  404. include the top-level loop. See `below <#full-code-listing>`_ for full code in the
  405. "Top-Level Parsing" section.
  406. .. code-block:: ocaml
  407. (* top ::= definition | external | expression | ';' *)
  408. let rec main_loop stream =
  409. match Stream.peek stream with
  410. | None -> ()
  411. (* ignore top-level semicolons. *)
  412. | Some (Token.Kwd ';') ->
  413. Stream.junk stream;
  414. main_loop stream
  415. | Some token ->
  416. begin
  417. try match token with
  418. | Token.Def ->
  419. ignore(Parser.parse_definition stream);
  420. print_endline "parsed a function definition.";
  421. | Token.Extern ->
  422. ignore(Parser.parse_extern stream);
  423. print_endline "parsed an extern.";
  424. | _ ->
  425. (* Evaluate a top-level expression into an anonymous function. *)
  426. ignore(Parser.parse_toplevel stream);
  427. print_endline "parsed a top-level expr";
  428. with Stream.Error s ->
  429. (* Skip token for error recovery. *)
  430. Stream.junk stream;
  431. print_endline s;
  432. end;
  433. print_string "ready> "; flush stdout;
  434. main_loop stream
  435. The most interesting part of this is that we ignore top-level
  436. semicolons. Why is this, you ask? The basic reason is that if you type
  437. "4 + 5" at the command line, the parser doesn't know whether that is the
  438. end of what you will type or not. For example, on the next line you
  439. could type "def foo..." in which case 4+5 is the end of a top-level
  440. expression. Alternatively you could type "\* 6", which would continue
  441. the expression. Having top-level semicolons allows you to type "4+5;",
  442. and the parser will know you are done.
  443. Conclusions
  444. ===========
  445. With just under 300 lines of commented code (240 lines of non-comment,
  446. non-blank code), we fully defined our minimal language, including a
  447. lexer, parser, and AST builder. With this done, the executable will
  448. validate Kaleidoscope code and tell us if it is grammatically invalid.
  449. For example, here is a sample interaction:
  450. .. code-block:: bash
  451. $ ./toy.byte
  452. ready> def foo(x y) x+foo(y, 4.0);
  453. Parsed a function definition.
  454. ready> def foo(x y) x+y y;
  455. Parsed a function definition.
  456. Parsed a top-level expr
  457. ready> def foo(x y) x+y );
  458. Parsed a function definition.
  459. Error: unknown token when expecting an expression
  460. ready> extern sin(a);
  461. ready> Parsed an extern
  462. ready> ^D
  463. $
  464. There is a lot of room for extension here. You can define new AST nodes,
  465. extend the language in many ways, etc. In the `next
  466. installment <OCamlLangImpl3.html>`_, we will describe how to generate
  467. LLVM Intermediate Representation (IR) from the AST.
  468. Full Code Listing
  469. =================
  470. Here is the complete code listing for this and the previous chapter.
  471. Note that it is fully self-contained: you don't need LLVM or any
  472. external libraries at all for this. (Besides the ocaml standard
  473. libraries, of course.) To build this, just compile with:
  474. .. code-block:: bash
  475. # Compile
  476. ocamlbuild toy.byte
  477. # Run
  478. ./toy.byte
  479. Here is the code:
  480. \_tags:
  481. ::
  482. <{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
  483. token.ml:
  484. .. code-block:: ocaml
  485. (*===----------------------------------------------------------------------===
  486. * Lexer Tokens
  487. *===----------------------------------------------------------------------===*)
  488. (* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
  489. * these others for known things. *)
  490. type token =
  491. (* commands *)
  492. | Def | Extern
  493. (* primary *)
  494. | Ident of string | Number of float
  495. (* unknown *)
  496. | Kwd of char
  497. lexer.ml:
  498. .. code-block:: ocaml
  499. (*===----------------------------------------------------------------------===
  500. * Lexer
  501. *===----------------------------------------------------------------------===*)
  502. let rec lex = parser
  503. (* Skip any whitespace. *)
  504. | [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
  505. (* identifier: [a-zA-Z][a-zA-Z0-9] *)
  506. | [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
  507. let buffer = Buffer.create 1 in
  508. Buffer.add_char buffer c;
  509. lex_ident buffer stream
  510. (* number: [0-9.]+ *)
  511. | [< ' ('0' .. '9' as c); stream >] ->
  512. let buffer = Buffer.create 1 in
  513. Buffer.add_char buffer c;
  514. lex_number buffer stream
  515. (* Comment until end of line. *)
  516. | [< ' ('#'); stream >] ->
  517. lex_comment stream
  518. (* Otherwise, just return the character as its ascii value. *)
  519. | [< 'c; stream >] ->
  520. [< 'Token.Kwd c; lex stream >]
  521. (* end of stream. *)
  522. | [< >] -> [< >]
  523. and lex_number buffer = parser
  524. | [< ' ('0' .. '9' | '.' as c); stream >] ->
  525. Buffer.add_char buffer c;
  526. lex_number buffer stream
  527. | [< stream=lex >] ->
  528. [< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
  529. and lex_ident buffer = parser
  530. | [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
  531. Buffer.add_char buffer c;
  532. lex_ident buffer stream
  533. | [< stream=lex >] ->
  534. match Buffer.contents buffer with
  535. | "def" -> [< 'Token.Def; stream >]
  536. | "extern" -> [< 'Token.Extern; stream >]
  537. | id -> [< 'Token.Ident id; stream >]
  538. and lex_comment = parser
  539. | [< ' ('\n'); stream=lex >] -> stream
  540. | [< 'c; e=lex_comment >] -> e
  541. | [< >] -> [< >]
  542. ast.ml:
  543. .. code-block:: ocaml
  544. (*===----------------------------------------------------------------------===
  545. * Abstract Syntax Tree (aka Parse Tree)
  546. *===----------------------------------------------------------------------===*)
  547. (* expr - Base type for all expression nodes. *)
  548. type expr =
  549. (* variant for numeric literals like "1.0". *)
  550. | Number of float
  551. (* variant for referencing a variable, like "a". *)
  552. | Variable of string
  553. (* variant for a binary operator. *)
  554. | Binary of char * expr * expr
  555. (* variant for function calls. *)
  556. | Call of string * expr array
  557. (* proto - This type represents the "prototype" for a function, which captures
  558. * its name, and its argument names (thus implicitly the number of arguments the
  559. * function takes). *)
  560. type proto = Prototype of string * string array
  561. (* func - This type represents a function definition itself. *)
  562. type func = Function of proto * expr
  563. parser.ml:
  564. .. code-block:: ocaml
  565. (*===---------------------------------------------------------------------===
  566. * Parser
  567. *===---------------------------------------------------------------------===*)
  568. (* binop_precedence - This holds the precedence for each binary operator that is
  569. * defined *)
  570. let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
  571. (* precedence - Get the precedence of the pending binary operator token. *)
  572. let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
  573. (* primary
  574. * ::= identifier
  575. * ::= numberexpr
  576. * ::= parenexpr *)
  577. let rec parse_primary = parser
  578. (* numberexpr ::= number *)
  579. | [< 'Token.Number n >] -> Ast.Number n
  580. (* parenexpr ::= '(' expression ')' *)
  581. | [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
  582. (* identifierexpr
  583. * ::= identifier
  584. * ::= identifier '(' argumentexpr ')' *)
  585. | [< 'Token.Ident id; stream >] ->
  586. let rec parse_args accumulator = parser
  587. | [< e=parse_expr; stream >] ->
  588. begin parser
  589. | [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
  590. | [< >] -> e :: accumulator
  591. end stream
  592. | [< >] -> accumulator
  593. in
  594. let rec parse_ident id = parser
  595. (* Call. *)
  596. | [< 'Token.Kwd '(';
  597. args=parse_args [];
  598. 'Token.Kwd ')' ?? "expected ')'">] ->
  599. Ast.Call (id, Array.of_list (List.rev args))
  600. (* Simple variable ref. *)
  601. | [< >] -> Ast.Variable id
  602. in
  603. parse_ident id stream
  604. | [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
  605. (* binoprhs
  606. * ::= ('+' primary)* *)
  607. and parse_bin_rhs expr_prec lhs stream =
  608. match Stream.peek stream with
  609. (* If this is a binop, find its precedence. *)
  610. | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
  611. let token_prec = precedence c in
  612. (* If this is a binop that binds at least as tightly as the current binop,
  613. * consume it, otherwise we are done. *)
  614. if token_prec < expr_prec then lhs else begin
  615. (* Eat the binop. *)
  616. Stream.junk stream;
  617. (* Parse the primary expression after the binary operator. *)
  618. let rhs = parse_primary stream in
  619. (* Okay, we know this is a binop. *)
  620. let rhs =
  621. match Stream.peek stream with
  622. | Some (Token.Kwd c2) ->
  623. (* If BinOp binds less tightly with rhs than the operator after
  624. * rhs, let the pending operator take rhs as its lhs. *)
  625. let next_prec = precedence c2 in
  626. if token_prec < next_prec
  627. then parse_bin_rhs (token_prec + 1) rhs stream
  628. else rhs
  629. | _ -> rhs
  630. in
  631. (* Merge lhs/rhs. *)
  632. let lhs = Ast.Binary (c, lhs, rhs) in
  633. parse_bin_rhs expr_prec lhs stream
  634. end
  635. | _ -> lhs
  636. (* expression
  637. * ::= primary binoprhs *)
  638. and parse_expr = parser
  639. | [< lhs=parse_primary; stream >] -> parse_bin_rhs 0 lhs stream
  640. (* prototype
  641. * ::= id '(' id* ')' *)
  642. let parse_prototype =
  643. let rec parse_args accumulator = parser
  644. | [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
  645. | [< >] -> accumulator
  646. in
  647. parser
  648. | [< 'Token.Ident id;
  649. 'Token.Kwd '(' ?? "expected '(' in prototype";
  650. args=parse_args [];
  651. 'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
  652. (* success. *)
  653. Ast.Prototype (id, Array.of_list (List.rev args))
  654. | [< >] ->
  655. raise (Stream.Error "expected function name in prototype")
  656. (* definition ::= 'def' prototype expression *)
  657. let parse_definition = parser
  658. | [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
  659. Ast.Function (p, e)
  660. (* toplevelexpr ::= expression *)
  661. let parse_toplevel = parser
  662. | [< e=parse_expr >] ->
  663. (* Make an anonymous proto. *)
  664. Ast.Function (Ast.Prototype ("", [||]), e)
  665. (* external ::= 'extern' prototype *)
  666. let parse_extern = parser
  667. | [< 'Token.Extern; e=parse_prototype >] -> e
  668. toplevel.ml:
  669. .. code-block:: ocaml
  670. (*===----------------------------------------------------------------------===
  671. * Top-Level parsing and JIT Driver
  672. *===----------------------------------------------------------------------===*)
  673. (* top ::= definition | external | expression | ';' *)
  674. let rec main_loop stream =
  675. match Stream.peek stream with
  676. | None -> ()
  677. (* ignore top-level semicolons. *)
  678. | Some (Token.Kwd ';') ->
  679. Stream.junk stream;
  680. main_loop stream
  681. | Some token ->
  682. begin
  683. try match token with
  684. | Token.Def ->
  685. ignore(Parser.parse_definition stream);
  686. print_endline "parsed a function definition.";
  687. | Token.Extern ->
  688. ignore(Parser.parse_extern stream);
  689. print_endline "parsed an extern.";
  690. | _ ->
  691. (* Evaluate a top-level expression into an anonymous function. *)
  692. ignore(Parser.parse_toplevel stream);
  693. print_endline "parsed a top-level expr";
  694. with Stream.Error s ->
  695. (* Skip token for error recovery. *)
  696. Stream.junk stream;
  697. print_endline s;
  698. end;
  699. print_string "ready> "; flush stdout;
  700. main_loop stream
  701. toy.ml:
  702. .. code-block:: ocaml
  703. (*===----------------------------------------------------------------------===
  704. * Main driver code.
  705. *===----------------------------------------------------------------------===*)
  706. let main () =
  707. (* Install standard binary operators.
  708. * 1 is the lowest precedence. *)
  709. Hashtbl.add Parser.binop_precedence '<' 10;
  710. Hashtbl.add Parser.binop_precedence '+' 20;
  711. Hashtbl.add Parser.binop_precedence '-' 20;
  712. Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
  713. (* Prime the first token. *)
  714. print_string "ready> "; flush stdout;
  715. let stream = Lexer.lex (Stream.of_channel stdin) in
  716. (* Run the main "interpreter loop" now. *)
  717. Toplevel.main_loop stream;
  718. ;;
  719. main ()
  720. `Next: Implementing Code Generation to LLVM IR <OCamlLangImpl3.html>`_