/3rd_party/llvm/docs/tutorial/LangImpl2.html

https://code.google.com/p/softart/ · HTML · 1231 lines · 1004 code · 208 blank · 19 comment · 0 complexity · 22a89bd7a53820a7bb9544055abd23b2 MD5 · raw file

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  2. "http://www.w3.org/TR/html4/strict.dtd">
  3. <html>
  4. <head>
  5. <title>Kaleidoscope: Implementing a Parser and AST</title>
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  7. <meta name="author" content="Chris Lattner">
  8. <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
  9. </head>
  10. <body>
  11. <h1>Kaleidoscope: Implementing a Parser and AST</h1>
  12. <ul>
  13. <li><a href="index.html">Up to Tutorial Index</a></li>
  14. <li>Chapter 2
  15. <ol>
  16. <li><a href="#intro">Chapter 2 Introduction</a></li>
  17. <li><a href="#ast">The Abstract Syntax Tree (AST)</a></li>
  18. <li><a href="#parserbasics">Parser Basics</a></li>
  19. <li><a href="#parserprimexprs">Basic Expression Parsing</a></li>
  20. <li><a href="#parserbinops">Binary Expression Parsing</a></li>
  21. <li><a href="#parsertop">Parsing the Rest</a></li>
  22. <li><a href="#driver">The Driver</a></li>
  23. <li><a href="#conclusions">Conclusions</a></li>
  24. <li><a href="#code">Full Code Listing</a></li>
  25. </ol>
  26. </li>
  27. <li><a href="LangImpl3.html">Chapter 3</a>: Code generation to LLVM IR</li>
  28. </ul>
  29. <div class="doc_author">
  30. <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
  31. </div>
  32. <!-- *********************************************************************** -->
  33. <h2><a name="intro">Chapter 2 Introduction</a></h2>
  34. <!-- *********************************************************************** -->
  35. <div>
  36. <p>Welcome to Chapter 2 of the "<a href="index.html">Implementing a language
  37. with LLVM</a>" tutorial. This chapter shows you how to use the lexer, built in
  38. <a href="LangImpl1.html">Chapter 1</a>, to build a full <a
  39. href="http://en.wikipedia.org/wiki/Parsing">parser</a> for
  40. our Kaleidoscope language. Once we have a parser, we'll define and build an <a
  41. href="http://en.wikipedia.org/wiki/Abstract_syntax_tree">Abstract Syntax
  42. Tree</a> (AST).</p>
  43. <p>The parser we will build uses a combination of <a
  44. href="http://en.wikipedia.org/wiki/Recursive_descent_parser">Recursive Descent
  45. Parsing</a> and <a href=
  46. "http://en.wikipedia.org/wiki/Operator-precedence_parser">Operator-Precedence
  47. Parsing</a> to parse the Kaleidoscope language (the latter for
  48. binary expressions and the former for everything else). Before we get to
  49. parsing though, lets talk about the output of the parser: the Abstract Syntax
  50. Tree.</p>
  51. </div>
  52. <!-- *********************************************************************** -->
  53. <h2><a name="ast">The Abstract Syntax Tree (AST)</a></h2>
  54. <!-- *********************************************************************** -->
  55. <div>
  56. <p>The AST for a program captures its behavior in such a way that it is easy for
  57. later stages of the compiler (e.g. code generation) to interpret. We basically
  58. want one object for each construct in the language, and the AST should closely
  59. model the language. In Kaleidoscope, we have expressions, a prototype, and a
  60. function object. We'll start with expressions first:</p>
  61. <div class="doc_code">
  62. <pre>
  63. /// ExprAST - Base class for all expression nodes.
  64. class ExprAST {
  65. public:
  66. virtual ~ExprAST() {}
  67. };
  68. /// NumberExprAST - Expression class for numeric literals like "1.0".
  69. class NumberExprAST : public ExprAST {
  70. double Val;
  71. public:
  72. NumberExprAST(double val) : Val(val) {}
  73. };
  74. </pre>
  75. </div>
  76. <p>The code above shows the definition of the base ExprAST class and one
  77. subclass which we use for numeric literals. The important thing to note about
  78. this code is that the NumberExprAST class captures the numeric value of the
  79. literal as an instance variable. This allows later phases of the compiler to
  80. know what the stored numeric value is.</p>
  81. <p>Right now we only create the AST, so there are no useful accessor methods on
  82. them. It would be very easy to add a virtual method to pretty print the code,
  83. for example. Here are the other expression AST node definitions that we'll use
  84. in the basic form of the Kaleidoscope language:
  85. </p>
  86. <div class="doc_code">
  87. <pre>
  88. /// VariableExprAST - Expression class for referencing a variable, like "a".
  89. class VariableExprAST : public ExprAST {
  90. std::string Name;
  91. public:
  92. VariableExprAST(const std::string &amp;name) : Name(name) {}
  93. };
  94. /// BinaryExprAST - Expression class for a binary operator.
  95. class BinaryExprAST : public ExprAST {
  96. char Op;
  97. ExprAST *LHS, *RHS;
  98. public:
  99. BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
  100. : Op(op), LHS(lhs), RHS(rhs) {}
  101. };
  102. /// CallExprAST - Expression class for function calls.
  103. class CallExprAST : public ExprAST {
  104. std::string Callee;
  105. std::vector&lt;ExprAST*&gt; Args;
  106. public:
  107. CallExprAST(const std::string &amp;callee, std::vector&lt;ExprAST*&gt; &amp;args)
  108. : Callee(callee), Args(args) {}
  109. };
  110. </pre>
  111. </div>
  112. <p>This is all (intentionally) rather straight-forward: variables capture the
  113. variable name, binary operators capture their opcode (e.g. '+'), and calls
  114. capture a function name as well as a list of any argument expressions. One thing
  115. that is nice about our AST is that it captures the language features without
  116. talking about the syntax of the language. Note that there is no discussion about
  117. precedence of binary operators, lexical structure, etc.</p>
  118. <p>For our basic language, these are all of the expression nodes we'll define.
  119. Because it doesn't have conditional control flow, it isn't Turing-complete;
  120. we'll fix that in a later installment. The two things we need next are a way
  121. to talk about the interface to a function, and a way to talk about functions
  122. themselves:</p>
  123. <div class="doc_code">
  124. <pre>
  125. /// PrototypeAST - This class represents the "prototype" for a function,
  126. /// which captures its name, and its argument names (thus implicitly the number
  127. /// of arguments the function takes).
  128. class PrototypeAST {
  129. std::string Name;
  130. std::vector&lt;std::string&gt; Args;
  131. public:
  132. PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args)
  133. : Name(name), Args(args) {}
  134. };
  135. /// FunctionAST - This class represents a function definition itself.
  136. class FunctionAST {
  137. PrototypeAST *Proto;
  138. ExprAST *Body;
  139. public:
  140. FunctionAST(PrototypeAST *proto, ExprAST *body)
  141. : Proto(proto), Body(body) {}
  142. };
  143. </pre>
  144. </div>
  145. <p>In Kaleidoscope, functions are typed with just a count of their arguments.
  146. Since all values are double precision floating point, the type of each argument
  147. doesn't need to be stored anywhere. In a more aggressive and realistic
  148. language, the "ExprAST" class would probably have a type field.</p>
  149. <p>With this scaffolding, we can now talk about parsing expressions and function
  150. bodies in Kaleidoscope.</p>
  151. </div>
  152. <!-- *********************************************************************** -->
  153. <h2><a name="parserbasics">Parser Basics</a></h2>
  154. <!-- *********************************************************************** -->
  155. <div>
  156. <p>Now that we have an AST to build, we need to define the parser code to build
  157. it. The idea here is that we want to parse something like "x+y" (which is
  158. returned as three tokens by the lexer) into an AST that could be generated with
  159. calls like this:</p>
  160. <div class="doc_code">
  161. <pre>
  162. ExprAST *X = new VariableExprAST("x");
  163. ExprAST *Y = new VariableExprAST("y");
  164. ExprAST *Result = new BinaryExprAST('+', X, Y);
  165. </pre>
  166. </div>
  167. <p>In order to do this, we'll start by defining some basic helper routines:</p>
  168. <div class="doc_code">
  169. <pre>
  170. /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
  171. /// token the parser is looking at. getNextToken reads another token from the
  172. /// lexer and updates CurTok with its results.
  173. static int CurTok;
  174. static int getNextToken() {
  175. return CurTok = gettok();
  176. }
  177. </pre>
  178. </div>
  179. <p>
  180. This implements a simple token buffer around the lexer. This allows
  181. us to look one token ahead at what the lexer is returning. Every function in
  182. our parser will assume that CurTok is the current token that needs to be
  183. parsed.</p>
  184. <div class="doc_code">
  185. <pre>
  186. /// Error* - These are little helper functions for error handling.
  187. ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
  188. PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
  189. FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
  190. </pre>
  191. </div>
  192. <p>
  193. The <tt>Error</tt> routines are simple helper routines that our parser will use
  194. to handle errors. The error recovery in our parser will not be the best and
  195. is not particular user-friendly, but it will be enough for our tutorial. These
  196. routines make it easier to handle errors in routines that have various return
  197. types: they always return null.</p>
  198. <p>With these basic helper functions, we can implement the first
  199. piece of our grammar: numeric literals.</p>
  200. </div>
  201. <!-- *********************************************************************** -->
  202. <h2><a name="parserprimexprs">Basic Expression Parsing</a></h2>
  203. <!-- *********************************************************************** -->
  204. <div>
  205. <p>We start with numeric literals, because they are the simplest to process.
  206. For each production in our grammar, we'll define a function which parses that
  207. production. For numeric literals, we have:
  208. </p>
  209. <div class="doc_code">
  210. <pre>
  211. /// numberexpr ::= number
  212. static ExprAST *ParseNumberExpr() {
  213. ExprAST *Result = new NumberExprAST(NumVal);
  214. getNextToken(); // consume the number
  215. return Result;
  216. }
  217. </pre>
  218. </div>
  219. <p>This routine is very simple: it expects to be called when the current token
  220. is a <tt>tok_number</tt> token. It takes the current number value, creates
  221. a <tt>NumberExprAST</tt> node, advances the lexer to the next token, and finally
  222. returns.</p>
  223. <p>There are some interesting aspects to this. The most important one is that
  224. this routine eats all of the tokens that correspond to the production and
  225. returns the lexer buffer with the next token (which is not part of the grammar
  226. production) ready to go. This is a fairly standard way to go for recursive
  227. descent parsers. For a better example, the parenthesis operator is defined like
  228. this:</p>
  229. <div class="doc_code">
  230. <pre>
  231. /// parenexpr ::= '(' expression ')'
  232. static ExprAST *ParseParenExpr() {
  233. getNextToken(); // eat (.
  234. ExprAST *V = ParseExpression();
  235. if (!V) return 0;
  236. if (CurTok != ')')
  237. return Error("expected ')'");
  238. getNextToken(); // eat ).
  239. return V;
  240. }
  241. </pre>
  242. </div>
  243. <p>This function illustrates a number of interesting things about the
  244. parser:</p>
  245. <p>
  246. 1) It shows how we use the Error routines. When called, this function expects
  247. that the current token is a '(' token, but after parsing the subexpression, it
  248. is possible that there is no ')' waiting. For example, if the user types in
  249. "(4 x" instead of "(4)", the parser should emit an error. Because errors can
  250. occur, the parser needs a way to indicate that they happened: in our parser, we
  251. return null on an error.</p>
  252. <p>2) Another interesting aspect of this function is that it uses recursion by
  253. calling <tt>ParseExpression</tt> (we will soon see that <tt>ParseExpression</tt> can call
  254. <tt>ParseParenExpr</tt>). This is powerful because it allows us to handle
  255. recursive grammars, and keeps each production very simple. Note that
  256. parentheses do not cause construction of AST nodes themselves. While we could
  257. do it this way, the most important role of parentheses are to guide the parser
  258. and provide grouping. Once the parser constructs the AST, parentheses are not
  259. needed.</p>
  260. <p>The next simple production is for handling variable references and function
  261. calls:</p>
  262. <div class="doc_code">
  263. <pre>
  264. /// identifierexpr
  265. /// ::= identifier
  266. /// ::= identifier '(' expression* ')'
  267. static ExprAST *ParseIdentifierExpr() {
  268. std::string IdName = IdentifierStr;
  269. getNextToken(); // eat identifier.
  270. if (CurTok != '(') // Simple variable ref.
  271. return new VariableExprAST(IdName);
  272. // Call.
  273. getNextToken(); // eat (
  274. std::vector&lt;ExprAST*&gt; Args;
  275. if (CurTok != ')') {
  276. while (1) {
  277. ExprAST *Arg = ParseExpression();
  278. if (!Arg) return 0;
  279. Args.push_back(Arg);
  280. if (CurTok == ')') break;
  281. if (CurTok != ',')
  282. return Error("Expected ')' or ',' in argument list");
  283. getNextToken();
  284. }
  285. }
  286. // Eat the ')'.
  287. getNextToken();
  288. return new CallExprAST(IdName, Args);
  289. }
  290. </pre>
  291. </div>
  292. <p>This routine follows the same style as the other routines. (It expects to be
  293. called if the current token is a <tt>tok_identifier</tt> token). It also has
  294. recursion and error handling. One interesting aspect of this is that it uses
  295. <em>look-ahead</em> to determine if the current identifier is a stand alone
  296. variable reference or if it is a function call expression. It handles this by
  297. checking to see if the token after the identifier is a '(' token, constructing
  298. either a <tt>VariableExprAST</tt> or <tt>CallExprAST</tt> node as appropriate.
  299. </p>
  300. <p>Now that we have all of our simple expression-parsing logic in place, we can
  301. define a helper function to wrap it together into one entry point. We call this
  302. class of expressions "primary" expressions, for reasons that will become more
  303. clear <a href="LangImpl6.html#unary">later in the tutorial</a>. In order to
  304. parse an arbitrary primary expression, we need to determine what sort of
  305. expression it is:</p>
  306. <div class="doc_code">
  307. <pre>
  308. /// primary
  309. /// ::= identifierexpr
  310. /// ::= numberexpr
  311. /// ::= parenexpr
  312. static ExprAST *ParsePrimary() {
  313. switch (CurTok) {
  314. default: return Error("unknown token when expecting an expression");
  315. case tok_identifier: return ParseIdentifierExpr();
  316. case tok_number: return ParseNumberExpr();
  317. case '(': return ParseParenExpr();
  318. }
  319. }
  320. </pre>
  321. </div>
  322. <p>Now that you see the definition of this function, it is more obvious why we
  323. can assume the state of CurTok in the various functions. This uses look-ahead
  324. to determine which sort of expression is being inspected, and then parses it
  325. with a function call.</p>
  326. <p>Now that basic expressions are handled, we need to handle binary expressions.
  327. They are a bit more complex.</p>
  328. </div>
  329. <!-- *********************************************************************** -->
  330. <h2><a name="parserbinops">Binary Expression Parsing</a></h2>
  331. <!-- *********************************************************************** -->
  332. <div>
  333. <p>Binary expressions are significantly harder to parse because they are often
  334. ambiguous. For example, when given the string "x+y*z", the parser can choose
  335. to parse it as either "(x+y)*z" or "x+(y*z)". With common definitions from
  336. mathematics, we expect the later parse, because "*" (multiplication) has
  337. higher <em>precedence</em> than "+" (addition).</p>
  338. <p>There are many ways to handle this, but an elegant and efficient way is to
  339. use <a href=
  340. "http://en.wikipedia.org/wiki/Operator-precedence_parser">Operator-Precedence
  341. Parsing</a>. This parsing technique uses the precedence of binary operators to
  342. guide recursion. To start with, we need a table of precedences:</p>
  343. <div class="doc_code">
  344. <pre>
  345. /// BinopPrecedence - This holds the precedence for each binary operator that is
  346. /// defined.
  347. static std::map&lt;char, int&gt; BinopPrecedence;
  348. /// GetTokPrecedence - Get the precedence of the pending binary operator token.
  349. static int GetTokPrecedence() {
  350. if (!isascii(CurTok))
  351. return -1;
  352. // Make sure it's a declared binop.
  353. int TokPrec = BinopPrecedence[CurTok];
  354. if (TokPrec &lt;= 0) return -1;
  355. return TokPrec;
  356. }
  357. int main() {
  358. // Install standard binary operators.
  359. // 1 is lowest precedence.
  360. BinopPrecedence['&lt;'] = 10;
  361. BinopPrecedence['+'] = 20;
  362. BinopPrecedence['-'] = 20;
  363. BinopPrecedence['*'] = 40; // highest.
  364. ...
  365. }
  366. </pre>
  367. </div>
  368. <p>For the basic form of Kaleidoscope, we will only support 4 binary operators
  369. (this can obviously be extended by you, our brave and intrepid reader). The
  370. <tt>GetTokPrecedence</tt> function returns the precedence for the current token,
  371. or -1 if the token is not a binary operator. Having a map makes it easy to add
  372. new operators and makes it clear that the algorithm doesn't depend on the
  373. specific operators involved, but it would be easy enough to eliminate the map
  374. and do the comparisons in the <tt>GetTokPrecedence</tt> function. (Or just use
  375. a fixed-size array).</p>
  376. <p>With the helper above defined, we can now start parsing binary expressions.
  377. The basic idea of operator precedence parsing is to break down an expression
  378. with potentially ambiguous binary operators into pieces. Consider ,for example,
  379. the expression "a+b+(c+d)*e*f+g". Operator precedence parsing considers this
  380. as a stream of primary expressions separated by binary operators. As such,
  381. it will first parse the leading primary expression "a", then it will see the
  382. pairs [+, b] [+, (c+d)] [*, e] [*, f] and [+, g]. Note that because parentheses
  383. are primary expressions, the binary expression parser doesn't need to worry
  384. about nested subexpressions like (c+d) at all.
  385. </p>
  386. <p>
  387. To start, an expression is a primary expression potentially followed by a
  388. sequence of [binop,primaryexpr] pairs:</p>
  389. <div class="doc_code">
  390. <pre>
  391. /// expression
  392. /// ::= primary binoprhs
  393. ///
  394. static ExprAST *ParseExpression() {
  395. ExprAST *LHS = ParsePrimary();
  396. if (!LHS) return 0;
  397. return ParseBinOpRHS(0, LHS);
  398. }
  399. </pre>
  400. </div>
  401. <p><tt>ParseBinOpRHS</tt> is the function that parses the sequence of pairs for
  402. us. It takes a precedence and a pointer to an expression for the part that has been
  403. parsed so far. Note that "x" is a perfectly valid expression: As such, "binoprhs" is
  404. allowed to be empty, in which case it returns the expression that is passed into
  405. it. In our example above, the code passes the expression for "a" into
  406. <tt>ParseBinOpRHS</tt> and the current token is "+".</p>
  407. <p>The precedence value passed into <tt>ParseBinOpRHS</tt> indicates the <em>
  408. minimal operator precedence</em> that the function is allowed to eat. For
  409. example, if the current pair stream is [+, x] and <tt>ParseBinOpRHS</tt> is
  410. passed in a precedence of 40, it will not consume any tokens (because the
  411. precedence of '+' is only 20). With this in mind, <tt>ParseBinOpRHS</tt> starts
  412. with:</p>
  413. <div class="doc_code">
  414. <pre>
  415. /// binoprhs
  416. /// ::= ('+' primary)*
  417. static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
  418. // If this is a binop, find its precedence.
  419. while (1) {
  420. int TokPrec = GetTokPrecedence();
  421. // If this is a binop that binds at least as tightly as the current binop,
  422. // consume it, otherwise we are done.
  423. if (TokPrec &lt; ExprPrec)
  424. return LHS;
  425. </pre>
  426. </div>
  427. <p>This code gets the precedence of the current token and checks to see if if is
  428. too low. Because we defined invalid tokens to have a precedence of -1, this
  429. check implicitly knows that the pair-stream ends when the token stream runs out
  430. of binary operators. If this check succeeds, we know that the token is a binary
  431. operator and that it will be included in this expression:</p>
  432. <div class="doc_code">
  433. <pre>
  434. // Okay, we know this is a binop.
  435. int BinOp = CurTok;
  436. getNextToken(); // eat binop
  437. // Parse the primary expression after the binary operator.
  438. ExprAST *RHS = ParsePrimary();
  439. if (!RHS) return 0;
  440. </pre>
  441. </div>
  442. <p>As such, this code eats (and remembers) the binary operator and then parses
  443. the primary expression that follows. This builds up the whole pair, the first of
  444. which is [+, b] for the running example.</p>
  445. <p>Now that we parsed the left-hand side of an expression and one pair of the
  446. RHS sequence, we have to decide which way the expression associates. In
  447. particular, we could have "(a+b) binop unparsed" or "a + (b binop unparsed)".
  448. To determine this, we look ahead at "binop" to determine its precedence and
  449. compare it to BinOp's precedence (which is '+' in this case):</p>
  450. <div class="doc_code">
  451. <pre>
  452. // If BinOp binds less tightly with RHS than the operator after RHS, let
  453. // the pending operator take RHS as its LHS.
  454. int NextPrec = GetTokPrecedence();
  455. if (TokPrec &lt; NextPrec) {
  456. </pre>
  457. </div>
  458. <p>If the precedence of the binop to the right of "RHS" is lower or equal to the
  459. precedence of our current operator, then we know that the parentheses associate
  460. as "(a+b) binop ...". In our example, the current operator is "+" and the next
  461. operator is "+", we know that they have the same precedence. In this case we'll
  462. create the AST node for "a+b", and then continue parsing:</p>
  463. <div class="doc_code">
  464. <pre>
  465. ... if body omitted ...
  466. }
  467. // Merge LHS/RHS.
  468. LHS = new BinaryExprAST(BinOp, LHS, RHS);
  469. } // loop around to the top of the while loop.
  470. }
  471. </pre>
  472. </div>
  473. <p>In our example above, this will turn "a+b+" into "(a+b)" and execute the next
  474. iteration of the loop, with "+" as the current token. The code above will eat,
  475. remember, and parse "(c+d)" as the primary expression, which makes the
  476. current pair equal to [+, (c+d)]. It will then evaluate the 'if' conditional above with
  477. "*" as the binop to the right of the primary. In this case, the precedence of "*" is
  478. higher than the precedence of "+" so the if condition will be entered.</p>
  479. <p>The critical question left here is "how can the if condition parse the right
  480. hand side in full"? In particular, to build the AST correctly for our example,
  481. it needs to get all of "(c+d)*e*f" as the RHS expression variable. The code to
  482. do this is surprisingly simple (code from the above two blocks duplicated for
  483. context):</p>
  484. <div class="doc_code">
  485. <pre>
  486. // If BinOp binds less tightly with RHS than the operator after RHS, let
  487. // the pending operator take RHS as its LHS.
  488. int NextPrec = GetTokPrecedence();
  489. if (TokPrec &lt; NextPrec) {
  490. <b>RHS = ParseBinOpRHS(TokPrec+1, RHS);
  491. if (RHS == 0) return 0;</b>
  492. }
  493. // Merge LHS/RHS.
  494. LHS = new BinaryExprAST(BinOp, LHS, RHS);
  495. } // loop around to the top of the while loop.
  496. }
  497. </pre>
  498. </div>
  499. <p>At this point, we know that the binary operator to the RHS of our primary
  500. has higher precedence than the binop we are currently parsing. As such, we know
  501. that any sequence of pairs whose operators are all higher precedence than "+"
  502. should be parsed together and returned as "RHS". To do this, we recursively
  503. invoke the <tt>ParseBinOpRHS</tt> function specifying "TokPrec+1" as the minimum
  504. precedence required for it to continue. In our example above, this will cause
  505. it to return the AST node for "(c+d)*e*f" as RHS, which is then set as the RHS
  506. of the '+' expression.</p>
  507. <p>Finally, on the next iteration of the while loop, the "+g" piece is parsed
  508. and added to the AST. With this little bit of code (14 non-trivial lines), we
  509. correctly handle fully general binary expression parsing in a very elegant way.
  510. This was a whirlwind tour of this code, and it is somewhat subtle. I recommend
  511. running through it with a few tough examples to see how it works.
  512. </p>
  513. <p>This wraps up handling of expressions. At this point, we can point the
  514. parser at an arbitrary token stream and build an expression from it, stopping
  515. at the first token that is not part of the expression. Next up we need to
  516. handle function definitions, etc.</p>
  517. </div>
  518. <!-- *********************************************************************** -->
  519. <h2><a name="parsertop">Parsing the Rest</a></h2>
  520. <!-- *********************************************************************** -->
  521. <div>
  522. <p>
  523. The next thing missing is handling of function prototypes. In Kaleidoscope,
  524. these are used both for 'extern' function declarations as well as function body
  525. definitions. The code to do this is straight-forward and not very interesting
  526. (once you've survived expressions):
  527. </p>
  528. <div class="doc_code">
  529. <pre>
  530. /// prototype
  531. /// ::= id '(' id* ')'
  532. static PrototypeAST *ParsePrototype() {
  533. if (CurTok != tok_identifier)
  534. return ErrorP("Expected function name in prototype");
  535. std::string FnName = IdentifierStr;
  536. getNextToken();
  537. if (CurTok != '(')
  538. return ErrorP("Expected '(' in prototype");
  539. // Read the list of argument names.
  540. std::vector&lt;std::string&gt; ArgNames;
  541. while (getNextToken() == tok_identifier)
  542. ArgNames.push_back(IdentifierStr);
  543. if (CurTok != ')')
  544. return ErrorP("Expected ')' in prototype");
  545. // success.
  546. getNextToken(); // eat ')'.
  547. return new PrototypeAST(FnName, ArgNames);
  548. }
  549. </pre>
  550. </div>
  551. <p>Given this, a function definition is very simple, just a prototype plus
  552. an expression to implement the body:</p>
  553. <div class="doc_code">
  554. <pre>
  555. /// definition ::= 'def' prototype expression
  556. static FunctionAST *ParseDefinition() {
  557. getNextToken(); // eat def.
  558. PrototypeAST *Proto = ParsePrototype();
  559. if (Proto == 0) return 0;
  560. if (ExprAST *E = ParseExpression())
  561. return new FunctionAST(Proto, E);
  562. return 0;
  563. }
  564. </pre>
  565. </div>
  566. <p>In addition, we support 'extern' to declare functions like 'sin' and 'cos' as
  567. well as to support forward declaration of user functions. These 'extern's are just
  568. prototypes with no body:</p>
  569. <div class="doc_code">
  570. <pre>
  571. /// external ::= 'extern' prototype
  572. static PrototypeAST *ParseExtern() {
  573. getNextToken(); // eat extern.
  574. return ParsePrototype();
  575. }
  576. </pre>
  577. </div>
  578. <p>Finally, we'll also let the user type in arbitrary top-level expressions and
  579. evaluate them on the fly. We will handle this by defining anonymous nullary
  580. (zero argument) functions for them:</p>
  581. <div class="doc_code">
  582. <pre>
  583. /// toplevelexpr ::= expression
  584. static FunctionAST *ParseTopLevelExpr() {
  585. if (ExprAST *E = ParseExpression()) {
  586. // Make an anonymous proto.
  587. PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;std::string&gt;());
  588. return new FunctionAST(Proto, E);
  589. }
  590. return 0;
  591. }
  592. </pre>
  593. </div>
  594. <p>Now that we have all the pieces, let's build a little driver that will let us
  595. actually <em>execute</em> this code we've built!</p>
  596. </div>
  597. <!-- *********************************************************************** -->
  598. <h2><a name="driver">The Driver</a></h2>
  599. <!-- *********************************************************************** -->
  600. <div>
  601. <p>The driver for this simply invokes all of the parsing pieces with a top-level
  602. dispatch loop. There isn't much interesting here, so I'll just include the
  603. top-level loop. See <a href="#code">below</a> for full code in the "Top-Level
  604. Parsing" section.</p>
  605. <div class="doc_code">
  606. <pre>
  607. /// top ::= definition | external | expression | ';'
  608. static void MainLoop() {
  609. while (1) {
  610. fprintf(stderr, "ready&gt; ");
  611. switch (CurTok) {
  612. case tok_eof: return;
  613. case ';': getNextToken(); break; // ignore top-level semicolons.
  614. case tok_def: HandleDefinition(); break;
  615. case tok_extern: HandleExtern(); break;
  616. default: HandleTopLevelExpression(); break;
  617. }
  618. }
  619. }
  620. </pre>
  621. </div>
  622. <p>The most interesting part of this is that we ignore top-level semicolons.
  623. Why is this, you ask? The basic reason is that if you type "4 + 5" at the
  624. command line, the parser doesn't know whether that is the end of what you will type
  625. or not. For example, on the next line you could type "def foo..." in which case
  626. 4+5 is the end of a top-level expression. Alternatively you could type "* 6",
  627. which would continue the expression. Having top-level semicolons allows you to
  628. type "4+5;", and the parser will know you are done.</p>
  629. </div>
  630. <!-- *********************************************************************** -->
  631. <h2><a name="conclusions">Conclusions</a></h2>
  632. <!-- *********************************************************************** -->
  633. <div>
  634. <p>With just under 400 lines of commented code (240 lines of non-comment,
  635. non-blank code), we fully defined our minimal language, including a lexer,
  636. parser, and AST builder. With this done, the executable will validate
  637. Kaleidoscope code and tell us if it is grammatically invalid. For
  638. example, here is a sample interaction:</p>
  639. <div class="doc_code">
  640. <pre>
  641. $ <b>./a.out</b>
  642. ready&gt; <b>def foo(x y) x+foo(y, 4.0);</b>
  643. Parsed a function definition.
  644. ready&gt; <b>def foo(x y) x+y y;</b>
  645. Parsed a function definition.
  646. Parsed a top-level expr
  647. ready&gt; <b>def foo(x y) x+y );</b>
  648. Parsed a function definition.
  649. Error: unknown token when expecting an expression
  650. ready&gt; <b>extern sin(a);</b>
  651. ready&gt; Parsed an extern
  652. ready&gt; <b>^D</b>
  653. $
  654. </pre>
  655. </div>
  656. <p>There is a lot of room for extension here. You can define new AST nodes,
  657. extend the language in many ways, etc. In the <a href="LangImpl3.html">next
  658. installment</a>, we will describe how to generate LLVM Intermediate
  659. Representation (IR) from the AST.</p>
  660. </div>
  661. <!-- *********************************************************************** -->
  662. <h2><a name="code">Full Code Listing</a></h2>
  663. <!-- *********************************************************************** -->
  664. <div>
  665. <p>
  666. Here is the complete code listing for this and the previous chapter.
  667. Note that it is fully self-contained: you don't need LLVM or any external
  668. libraries at all for this. (Besides the C and C++ standard libraries, of
  669. course.) To build this, just compile with:</p>
  670. <div class="doc_code">
  671. <pre>
  672. # Compile
  673. clang++ -g -O3 toy.cpp
  674. # Run
  675. ./a.out
  676. </pre>
  677. </div>
  678. <p>Here is the code:</p>
  679. <div class="doc_code">
  680. <pre>
  681. #include &lt;cstdio&gt;
  682. #include &lt;cstdlib&gt;
  683. #include &lt;string&gt;
  684. #include &lt;map&gt;
  685. #include &lt;vector&gt;
  686. //===----------------------------------------------------------------------===//
  687. // Lexer
  688. //===----------------------------------------------------------------------===//
  689. // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
  690. // of these for known things.
  691. enum Token {
  692. tok_eof = -1,
  693. // commands
  694. tok_def = -2, tok_extern = -3,
  695. // primary
  696. tok_identifier = -4, tok_number = -5
  697. };
  698. static std::string IdentifierStr; // Filled in if tok_identifier
  699. static double NumVal; // Filled in if tok_number
  700. /// gettok - Return the next token from standard input.
  701. static int gettok() {
  702. static int LastChar = ' ';
  703. // Skip any whitespace.
  704. while (isspace(LastChar))
  705. LastChar = getchar();
  706. if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
  707. IdentifierStr = LastChar;
  708. while (isalnum((LastChar = getchar())))
  709. IdentifierStr += LastChar;
  710. if (IdentifierStr == "def") return tok_def;
  711. if (IdentifierStr == "extern") return tok_extern;
  712. return tok_identifier;
  713. }
  714. if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
  715. std::string NumStr;
  716. do {
  717. NumStr += LastChar;
  718. LastChar = getchar();
  719. } while (isdigit(LastChar) || LastChar == '.');
  720. NumVal = strtod(NumStr.c_str(), 0);
  721. return tok_number;
  722. }
  723. if (LastChar == '#') {
  724. // Comment until end of line.
  725. do LastChar = getchar();
  726. while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp;&amp; LastChar != '\r');
  727. if (LastChar != EOF)
  728. return gettok();
  729. }
  730. // Check for end of file. Don't eat the EOF.
  731. if (LastChar == EOF)
  732. return tok_eof;
  733. // Otherwise, just return the character as its ascii value.
  734. int ThisChar = LastChar;
  735. LastChar = getchar();
  736. return ThisChar;
  737. }
  738. //===----------------------------------------------------------------------===//
  739. // Abstract Syntax Tree (aka Parse Tree)
  740. //===----------------------------------------------------------------------===//
  741. /// ExprAST - Base class for all expression nodes.
  742. class ExprAST {
  743. public:
  744. virtual ~ExprAST() {}
  745. };
  746. /// NumberExprAST - Expression class for numeric literals like "1.0".
  747. class NumberExprAST : public ExprAST {
  748. double Val;
  749. public:
  750. NumberExprAST(double val) : Val(val) {}
  751. };
  752. /// VariableExprAST - Expression class for referencing a variable, like "a".
  753. class VariableExprAST : public ExprAST {
  754. std::string Name;
  755. public:
  756. VariableExprAST(const std::string &amp;name) : Name(name) {}
  757. };
  758. /// BinaryExprAST - Expression class for a binary operator.
  759. class BinaryExprAST : public ExprAST {
  760. char Op;
  761. ExprAST *LHS, *RHS;
  762. public:
  763. BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
  764. : Op(op), LHS(lhs), RHS(rhs) {}
  765. };
  766. /// CallExprAST - Expression class for function calls.
  767. class CallExprAST : public ExprAST {
  768. std::string Callee;
  769. std::vector&lt;ExprAST*&gt; Args;
  770. public:
  771. CallExprAST(const std::string &amp;callee, std::vector&lt;ExprAST*&gt; &amp;args)
  772. : Callee(callee), Args(args) {}
  773. };
  774. /// PrototypeAST - This class represents the "prototype" for a function,
  775. /// which captures its name, and its argument names (thus implicitly the number
  776. /// of arguments the function takes).
  777. class PrototypeAST {
  778. std::string Name;
  779. std::vector&lt;std::string&gt; Args;
  780. public:
  781. PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args)
  782. : Name(name), Args(args) {}
  783. };
  784. /// FunctionAST - This class represents a function definition itself.
  785. class FunctionAST {
  786. PrototypeAST *Proto;
  787. ExprAST *Body;
  788. public:
  789. FunctionAST(PrototypeAST *proto, ExprAST *body)
  790. : Proto(proto), Body(body) {}
  791. };
  792. //===----------------------------------------------------------------------===//
  793. // Parser
  794. //===----------------------------------------------------------------------===//
  795. /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
  796. /// token the parser is looking at. getNextToken reads another token from the
  797. /// lexer and updates CurTok with its results.
  798. static int CurTok;
  799. static int getNextToken() {
  800. return CurTok = gettok();
  801. }
  802. /// BinopPrecedence - This holds the precedence for each binary operator that is
  803. /// defined.
  804. static std::map&lt;char, int&gt; BinopPrecedence;
  805. /// GetTokPrecedence - Get the precedence of the pending binary operator token.
  806. static int GetTokPrecedence() {
  807. if (!isascii(CurTok))
  808. return -1;
  809. // Make sure it's a declared binop.
  810. int TokPrec = BinopPrecedence[CurTok];
  811. if (TokPrec &lt;= 0) return -1;
  812. return TokPrec;
  813. }
  814. /// Error* - These are little helper functions for error handling.
  815. ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
  816. PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
  817. FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
  818. static ExprAST *ParseExpression();
  819. /// identifierexpr
  820. /// ::= identifier
  821. /// ::= identifier '(' expression* ')'
  822. static ExprAST *ParseIdentifierExpr() {
  823. std::string IdName = IdentifierStr;
  824. getNextToken(); // eat identifier.
  825. if (CurTok != '(') // Simple variable ref.
  826. return new VariableExprAST(IdName);
  827. // Call.
  828. getNextToken(); // eat (
  829. std::vector&lt;ExprAST*&gt; Args;
  830. if (CurTok != ')') {
  831. while (1) {
  832. ExprAST *Arg = ParseExpression();
  833. if (!Arg) return 0;
  834. Args.push_back(Arg);
  835. if (CurTok == ')') break;
  836. if (CurTok != ',')
  837. return Error("Expected ')' or ',' in argument list");
  838. getNextToken();
  839. }
  840. }
  841. // Eat the ')'.
  842. getNextToken();
  843. return new CallExprAST(IdName, Args);
  844. }
  845. /// numberexpr ::= number
  846. static ExprAST *ParseNumberExpr() {
  847. ExprAST *Result = new NumberExprAST(NumVal);
  848. getNextToken(); // consume the number
  849. return Result;
  850. }
  851. /// parenexpr ::= '(' expression ')'
  852. static ExprAST *ParseParenExpr() {
  853. getNextToken(); // eat (.
  854. ExprAST *V = ParseExpression();
  855. if (!V) return 0;
  856. if (CurTok != ')')
  857. return Error("expected ')'");
  858. getNextToken(); // eat ).
  859. return V;
  860. }
  861. /// primary
  862. /// ::= identifierexpr
  863. /// ::= numberexpr
  864. /// ::= parenexpr
  865. static ExprAST *ParsePrimary() {
  866. switch (CurTok) {
  867. default: return Error("unknown token when expecting an expression");
  868. case tok_identifier: return ParseIdentifierExpr();
  869. case tok_number: return ParseNumberExpr();
  870. case '(': return ParseParenExpr();
  871. }
  872. }
  873. /// binoprhs
  874. /// ::= ('+' primary)*
  875. static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
  876. // If this is a binop, find its precedence.
  877. while (1) {
  878. int TokPrec = GetTokPrecedence();
  879. // If this is a binop that binds at least as tightly as the current binop,
  880. // consume it, otherwise we are done.
  881. if (TokPrec &lt; ExprPrec)
  882. return LHS;
  883. // Okay, we know this is a binop.
  884. int BinOp = CurTok;
  885. getNextToken(); // eat binop
  886. // Parse the primary expression after the binary operator.
  887. ExprAST *RHS = ParsePrimary();
  888. if (!RHS) return 0;
  889. // If BinOp binds less tightly with RHS than the operator after RHS, let
  890. // the pending operator take RHS as its LHS.
  891. int NextPrec = GetTokPrecedence();
  892. if (TokPrec &lt; NextPrec) {
  893. RHS = ParseBinOpRHS(TokPrec+1, RHS);
  894. if (RHS == 0) return 0;
  895. }
  896. // Merge LHS/RHS.
  897. LHS = new BinaryExprAST(BinOp, LHS, RHS);
  898. }
  899. }
  900. /// expression
  901. /// ::= primary binoprhs
  902. ///
  903. static ExprAST *ParseExpression() {
  904. ExprAST *LHS = ParsePrimary();
  905. if (!LHS) return 0;
  906. return ParseBinOpRHS(0, LHS);
  907. }
  908. /// prototype
  909. /// ::= id '(' id* ')'
  910. static PrototypeAST *ParsePrototype() {
  911. if (CurTok != tok_identifier)
  912. return ErrorP("Expected function name in prototype");
  913. std::string FnName = IdentifierStr;
  914. getNextToken();
  915. if (CurTok != '(')
  916. return ErrorP("Expected '(' in prototype");
  917. std::vector&lt;std::string&gt; ArgNames;
  918. while (getNextToken() == tok_identifier)
  919. ArgNames.push_back(IdentifierStr);
  920. if (CurTok != ')')
  921. return ErrorP("Expected ')' in prototype");
  922. // success.
  923. getNextToken(); // eat ')'.
  924. return new PrototypeAST(FnName, ArgNames);
  925. }
  926. /// definition ::= 'def' prototype expression
  927. static FunctionAST *ParseDefinition() {
  928. getNextToken(); // eat def.
  929. PrototypeAST *Proto = ParsePrototype();
  930. if (Proto == 0) return 0;
  931. if (ExprAST *E = ParseExpression())
  932. return new FunctionAST(Proto, E);
  933. return 0;
  934. }
  935. /// toplevelexpr ::= expression
  936. static FunctionAST *ParseTopLevelExpr() {
  937. if (ExprAST *E = ParseExpression()) {
  938. // Make an anonymous proto.
  939. PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;std::string&gt;());
  940. return new FunctionAST(Proto, E);
  941. }
  942. return 0;
  943. }
  944. /// external ::= 'extern' prototype
  945. static PrototypeAST *ParseExtern() {
  946. getNextToken(); // eat extern.
  947. return ParsePrototype();
  948. }
  949. //===----------------------------------------------------------------------===//
  950. // Top-Level parsing
  951. //===----------------------------------------------------------------------===//
  952. static void HandleDefinition() {
  953. if (ParseDefinition()) {
  954. fprintf(stderr, "Parsed a function definition.\n");
  955. } else {
  956. // Skip token for error recovery.
  957. getNextToken();
  958. }
  959. }
  960. static void HandleExtern() {
  961. if (ParseExtern()) {
  962. fprintf(stderr, "Parsed an extern\n");
  963. } else {
  964. // Skip token for error recovery.
  965. getNextToken();
  966. }
  967. }
  968. static void HandleTopLevelExpression() {
  969. // Evaluate a top-level expression into an anonymous function.
  970. if (ParseTopLevelExpr()) {
  971. fprintf(stderr, "Parsed a top-level expr\n");
  972. } else {
  973. // Skip token for error recovery.
  974. getNextToken();
  975. }
  976. }
  977. /// top ::= definition | external | expression | ';'
  978. static void MainLoop() {
  979. while (1) {
  980. fprintf(stderr, "ready&gt; ");
  981. switch (CurTok) {
  982. case tok_eof: return;
  983. case ';': getNextToken(); break; // ignore top-level semicolons.
  984. case tok_def: HandleDefinition(); break;
  985. case tok_extern: HandleExtern(); break;
  986. default: HandleTopLevelExpression(); break;
  987. }
  988. }
  989. }
  990. //===----------------------------------------------------------------------===//
  991. // Main driver code.
  992. //===----------------------------------------------------------------------===//
  993. int main() {
  994. // Install standard binary operators.
  995. // 1 is lowest precedence.
  996. BinopPrecedence['&lt;'] = 10;
  997. BinopPrecedence['+'] = 20;
  998. BinopPrecedence['-'] = 20;
  999. BinopPrecedence['*'] = 40; // highest.
  1000. // Prime the first token.
  1001. fprintf(stderr, "ready&gt; ");
  1002. getNextToken();
  1003. // Run the main "interpreter loop" now.
  1004. MainLoop();
  1005. return 0;
  1006. }
  1007. </pre>
  1008. </div>
  1009. <a href="LangImpl3.html">Next: Implementing Code Generation to LLVM IR</a>
  1010. </div>
  1011. <!-- *********************************************************************** -->
  1012. <hr>
  1013. <address>
  1014. <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
  1015. src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
  1016. <a href="http://validator.w3.org/check/referer"><img
  1017. src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
  1018. <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
  1019. <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
  1020. Last modified: $Date: 2012-05-03 06:46:36 +0800 (周四, 03 五月 2012) $
  1021. </address>
  1022. </body>
  1023. </html>