Add mention of Glasgow Haskell Compiler.
[oota-llvm.git] / docs / tutorial / LangImpl2.html
index 2a0d4870e01cda4bba54534c92b0a8959f294c6a..292dd4e516cd68eaacfb8226ae62bb2e832026a4 100644 (file)
@@ -6,28 +6,46 @@
   <title>Kaleidoscope: Implementing a Parser and AST</title>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <meta name="author" content="Chris Lattner">
-  <link rel="stylesheet" href="../llvm.css" type="text/css">
+  <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
 </head>
 
 <body>
 
-<div class="doc_title">Kaleidoscope: Implementing a Parser and AST</div>
+<h1>Kaleidoscope: Implementing a Parser and AST</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 2
+  <ol>
+    <li><a href="#intro">Chapter 2 Introduction</a></li>
+    <li><a href="#ast">The Abstract Syntax Tree (AST)</a></li>
+    <li><a href="#parserbasics">Parser Basics</a></li>
+    <li><a href="#parserprimexprs">Basic Expression Parsing</a></li>
+    <li><a href="#parserbinops">Binary Expression Parsing</a></li>
+    <li><a href="#parsertop">Parsing the Rest</a></li>
+    <li><a href="#driver">The Driver</a></li>
+    <li><a href="#conclusions">Conclusions</a></li>
+    <li><a href="#code">Full Code Listing</a></li>
+  </ol>
+</li>
+<li><a href="LangImpl3.html">Chapter 3</a>: Code generation to LLVM IR</li>
+</ul>
 
 <div class="doc_author">
   <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="intro">Part 2 Introduction</a></div>
+<h2><a name="intro">Chapter 2 Introduction</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
-<p>Welcome to part 2 of the "<a href="index.html">Implementing a language with
-LLVM</a>" tutorial.  This chapter shows you how to use the <a 
-href="LangImpl1.html">Lexer built in Chapter 1</a> to build a full <a
+<p>Welcome to Chapter 2 of the "<a href="index.html">Implementing a language
+with LLVM</a>" tutorial.  This chapter shows you how to use the lexer, built in 
+<a href="LangImpl1.html">Chapter 1</a>, to build a full <a
 href="http://en.wikipedia.org/wiki/Parsing">parser</a> for
-our Kaleidoscope language and build an <a 
+our Kaleidoscope language.  Once we have a parser, we'll define and build an <a 
 href="http://en.wikipedia.org/wiki/Abstract_syntax_tree">Abstract Syntax 
 Tree</a> (AST).</p>
 
@@ -35,19 +53,20 @@ Tree</a> (AST).</p>
 href="http://en.wikipedia.org/wiki/Recursive_descent_parser">Recursive Descent
 Parsing</a> and <a href=
 "http://en.wikipedia.org/wiki/Operator-precedence_parser">Operator-Precedence 
-Parsing</a> to parse the Kaleidoscope language (the later for binary expression
-and the former for everything else).  Before we get to parsing though, lets talk
-about the output of the parser: the Abstract Syntax Tree.</p>
+Parsing</a> to parse the Kaleidoscope language (the latter for 
+binary expressions and the former for everything else).  Before we get to
+parsing though, lets talk about the output of the parser: the Abstract Syntax
+Tree.</p>
 
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="ast">The Abstract Syntax Tree (AST)</a></div>
+<h2><a name="ast">The Abstract Syntax Tree (AST)</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
-<p>The AST for a program captures its behavior in a way that it is easy for
+<p>The AST for a program captures its behavior in such a way that it is easy for
 later stages of the compiler (e.g. code generation) to interpret.  We basically
 want one object for each construct in the language, and the AST should closely
 model the language.  In Kaleidoscope, we have expressions, a prototype, and a
@@ -65,20 +84,21 @@ public:
 class NumberExprAST : public ExprAST {
   double Val;
 public:
-  explicit NumberExprAST(double val) : Val(val) {}
+  NumberExprAST(double val) : Val(val) {}
 };
 </pre>
 </div>
 
 <p>The code above shows the definition of the base ExprAST class and one
-subclass which we use for numeric literals.  The important thing about this is
-that the NumberExprAST class captures the numeric value of the literal in the
-class, so that later phases of the compiler can know what it is.</p>
+subclass which we use for numeric literals.  The important thing to note about
+this code is that the NumberExprAST class captures the numeric value of the
+literal as an instance variable. This allows later phases of the compiler to
+know what the stored numeric value is.</p>
 
 <p>Right now we only create the AST,  so there are no useful accessor methods on
 them.  It would be very easy to add a virtual method to pretty print the code,
 for example.  Here are the other expression AST node definitions that we'll use
-in the basic form of the Kaleidoscope language.
+in the basic form of the Kaleidoscope language:
 </p>
 
 <div class="doc_code">
@@ -87,7 +107,7 @@ in the basic form of the Kaleidoscope language.
 class VariableExprAST : public ExprAST {
   std::string Name;
 public:
-  explicit VariableExprAST(const std::string &amp;name) : Name(name) {}
+  VariableExprAST(const std::string &amp;name) : Name(name) {}
 };
 
 /// BinaryExprAST - Expression class for a binary operator.
@@ -110,12 +130,12 @@ public:
 </pre>
 </div>
 
-<p>This is all (intentially) rather straight-forward: variables capture the
+<p>This is all (intentionally) rather straight-forward: variables capture the
 variable name, binary operators capture their opcode (e.g. '+'), and calls
-capture a function name and list of argument expressions.  One thing that is 
-nice about our AST is that it captures the language features without talking
-about the syntax of the language.  Note that there is no discussion about 
-precedence of binary operators, lexical structure etc.</p>
+capture a function name as well as a list of any argument expressions.  One thing 
+that is nice about our AST is that it captures the language features without 
+talking about the syntax of the language.  Note that there is no discussion about 
+precedence of binary operators, lexical structure, etc.</p>
 
 <p>For our basic language, these are all of the expression nodes we'll define.
 Because it doesn't have conditional control flow, it isn't Turing-complete;
@@ -126,7 +146,8 @@ themselves:</p>
 <div class="doc_code">
 <pre>
 /// PrototypeAST - This class represents the "prototype" for a function,
-/// which captures its argument names as well as if it is an operator.
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes).
 class PrototypeAST {
   std::string Name;
   std::vector&lt;std::string&gt; Args;
@@ -147,9 +168,9 @@ public:
 </div>
 
 <p>In Kaleidoscope, functions are typed with just a count of their arguments.
-Since all values are double precision floating point, this fact doesn't need to
-be captured anywhere.  In a more aggressive and realistic language, the
-"ExprAST" class would probably have a type field.</p>
+Since all values are double precision floating point, the type of each argument
+doesn't need to be stored anywhere.  In a more aggressive and realistic
+language, the "ExprAST" class would probably have a type field.</p>
 
 <p>With this scaffolding, we can now talk about parsing expressions and function
 bodies in Kaleidoscope.</p>
@@ -157,10 +178,10 @@ bodies in Kaleidoscope.</p>
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="parserbasics">Parser Basics</a></div>
+<h2><a name="parserbasics">Parser Basics</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <p>Now that we have an AST to build, we need to define the parser code to build
 it.  The idea here is that we want to parse something like "x+y" (which is
@@ -180,7 +201,7 @@ calls like this:</p>
 <div class="doc_code">
 <pre>
 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
-/// token the parser it looking at.  getNextToken reads another token from the
+/// token the parser is looking at.  getNextToken reads another token from the
 /// lexer and updates CurTok with its results.
 static int CurTok;
 static int getNextToken() {
@@ -195,10 +216,6 @@ us to look one token ahead at what the lexer is returning.  Every function in
 our parser will assume that CurTok is the current token that needs to be
 parsed.</p>
 
-<p>Again, we define these with global variables; it would be better design to 
-wrap the entire parser in a class and use instance variables for these.
-</p>
-
 <div class="doc_code">
 <pre>
 
@@ -216,17 +233,16 @@ is not particular user-friendly, but it will be enough for our tutorial.  These
 routines make it easier to handle errors in routines that have various return
 types: they always return null.</p>
 
-<p>With these basic helper functions implemented, we can implement the first
-piece of our grammar: we'll start with numeric literals.</p>
+<p>With these basic helper functions, we can implement the first
+piece of our grammar: numeric literals.</p>
 
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="parserprimexprs">Basic Expression
- Parsing</a></div>
+<h2><a name="parserprimexprs">Basic Expression Parsing</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <p>We start with numeric literals, because they are the simplest to process.
 For each production in our grammar, we'll define a function which parses that
@@ -246,11 +262,11 @@ static ExprAST *ParseNumberExpr() {
 
 <p>This routine is very simple: it expects to be called when the current token
 is a <tt>tok_number</tt> token.  It takes the current number value, creates 
-a <tt>NumberExprAST</tt> node, advances the lexer to the next token, then
+a <tt>NumberExprAST</tt> node, advances the lexer to the next token, and finally
 returns.</p>
 
-<p>There are some interesting aspects of this.  The most important one is that
-this routine eats all of the tokens that correspond to the production, and
+<p>There are some interesting aspects to this.  The most important one is that
+this routine eats all of the tokens that correspond to the production and
 returns the lexer buffer with the next token (which is not part of the grammar
 production) ready to go.  This is a fairly standard way to go for recursive
 descent parsers.  For a better example, the parenthesis operator is defined like
@@ -272,21 +288,25 @@ static ExprAST *ParseParenExpr() {
 </pre>
 </div>
 
-<p>This function illustrates a number of interesting things about the parser:
-1) it shows how we use the Error routines.  When called, this function expects
+<p>This function illustrates a number of interesting things about the 
+parser:</p>
+
+<p>
+1) It shows how we use the Error routines.  When called, this function expects
 that the current token is a '(' token, but after parsing the subexpression, it
-is possible that there is not a ')' waiting.  For example, if the user types in
+is possible that there is no ')' waiting.  For example, if the user types in
 "(4 x" instead of "(4)", the parser should emit an error.  Because errors can
 occur, the parser needs a way to indicate that they happened: in our parser, we
 return null on an error.</p>
 
-<p>Another interesting aspect of this function is that it uses recursion by
+<p>2) Another interesting aspect of this function is that it uses recursion by
 calling <tt>ParseExpression</tt> (we will soon see that <tt>ParseExpression</tt> can call
 <tt>ParseParenExpr</tt>).  This is powerful because it allows us to handle 
 recursive grammars, and keeps each production very simple.  Note that
 parentheses do not cause construction of AST nodes themselves.  While we could
-do this, the most important role of parens are to guide the parser and provide
-grouping.  Once the parser constructs the AST, parens are not needed.</p>
+do it this way, the most important role of parentheses are to guide the parser
+and provide grouping.  Once the parser constructs the AST, parentheses are not
+needed.</p>
 
 <p>The next simple production is for handling variable references and function
 calls:</p>
@@ -294,12 +314,12 @@ calls:</p>
 <div class="doc_code">
 <pre>
 /// identifierexpr
-///   ::= identifer
-///   ::= identifer '(' expression* ')'
+///   ::= identifier
+///   ::= identifier '(' expression* ')'
 static ExprAST *ParseIdentifierExpr() {
   std::string IdName = IdentifierStr;
   
-  getNextToken();  // eat identifer.
+  getNextToken();  // eat identifier.
   
   if (CurTok != '(') // Simple variable ref.
     return new VariableExprAST(IdName);
@@ -307,16 +327,18 @@ static ExprAST *ParseIdentifierExpr() {
   // Call.
   getNextToken();  // eat (
   std::vector&lt;ExprAST*&gt; Args;
-  while (1) {
-    ExprAST *Arg = ParseExpression();
-    if (!Arg) return 0;
-    Args.push_back(Arg);
-    
-    if (CurTok == ')') break;
-    
-    if (CurTok != ',')
-      return Error("Expected ')'");
-    getNextToken();
+  if (CurTok != ')') {
+    while (1) {
+      ExprAST *Arg = ParseExpression();
+      if (!Arg) return 0;
+      Args.push_back(Arg);
+
+      if (CurTok == ')') break;
+
+      if (CurTok != ',')
+        return Error("Expected ')' or ',' in argument list");
+      getNextToken();
+    }
   }
 
   // Eat the ')'.
@@ -327,20 +349,21 @@ static ExprAST *ParseIdentifierExpr() {
 </pre>
 </div>
 
-<p>This routine follows the same style as the other routines (it expects to be
+<p>This routine follows the same style as the other routines.  (It expects to be
 called if the current token is a <tt>tok_identifier</tt> token).  It also has
 recursion and error handling.  One interesting aspect of this is that it uses
 <em>look-ahead</em> to determine if the current identifier is a stand alone
 variable reference or if it is a function call expression.  It handles this by
-checking to see if the token after the identifier is a '(' token, and constructs
+checking to see if the token after the identifier is a '(' token, constructing
 either a <tt>VariableExprAST</tt> or <tt>CallExprAST</tt> node as appropriate.
 </p>
 
-<p>Now that we have all of our simple expression parsing logic in place, we can
-define a helper function to wrap them up in a class.  We call this class of 
-expressions "primary" expressions, for reasons that will become more clear
-later.  In order to parse a primary expression, we need to determine what sort
-of expression it is:</p>
+<p>Now that we have all of our simple expression-parsing logic in place, we can
+define a helper function to wrap it together into one entry point.  We call this
+class of expressions "primary" expressions, for reasons that will become more
+clear <a href="LangImpl6.html#unary">later in the tutorial</a>.  In order to
+parse an arbitrary primary expression, we need to determine what sort of
+expression it is:</p>
 
 <div class="doc_code">
 <pre>
@@ -359,22 +382,21 @@ static ExprAST *ParsePrimary() {
 </pre>
 </div>
 
-<p>Now that you see the definition of this function, it makes it more obvious
-why we can assume the state of CurTok in the various functions.  This uses
-look-ahead to determine which sort of expression is being inspected, and parses
-it with a function call.</p>
+<p>Now that you see the definition of this function, it is more obvious why we
+can assume the state of CurTok in the various functions.  This uses look-ahead
+to determine which sort of expression is being inspected, and then parses it
+with a function call.</p>
 
-<p>Now that basic expressions are handled, we need to handle binary expressions,
-which are a bit more complex.</p>
+<p>Now that basic expressions are handled, we need to handle binary expressions.
+They are a bit more complex.</p>
 
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="parserbinops">Binary Expression
- Parsing</a></div>
+<h2><a name="parserbinops">Binary Expression Parsing</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <p>Binary expressions are significantly harder to parse because they are often
 ambiguous.  For example, when given the string "x+y*z", the parser can choose
@@ -418,16 +440,17 @@ int main() {
 </div>
 
 <p>For the basic form of Kaleidoscope, we will only support 4 binary operators
-(this can obviously be extended by you, the reader).  The
+(this can obviously be extended by you, our brave and intrepid reader).  The
 <tt>GetTokPrecedence</tt> function returns the precedence for the current token,
 or -1 if the token is not a binary operator.  Having a map makes it easy to add
 new operators and makes it clear that the algorithm doesn't depend on the
 specific operators involved, but it would be easy enough to eliminate the map
-and do the comparisons in the <tt>GetTokPrecedence</tt> function.</p>
+and do the comparisons in the <tt>GetTokPrecedence</tt> function.  (Or just use
+a fixed-size array).</p>
 
 <p>With the helper above defined, we can now start parsing binary expressions.
 The basic idea of operator precedence parsing is to break down an expression
-with potentially ambiguous binary operators into pieces.  Consider for example
+with potentially ambiguous binary operators into pieces.  Consider ,for example,
 the expression "a+b+(c+d)*e*f+g".  Operator precedence parsing considers this
 as a stream of primary expressions separated by binary operators.  As such,
 it will first parse the leading primary expression "a", then it will see the
@@ -455,8 +478,8 @@ static ExprAST *ParseExpression() {
 </div>
 
 <p><tt>ParseBinOpRHS</tt> is the function that parses the sequence of pairs for
-us.  It takes a precedence and a pointer to an expression for the part parsed
-so far.   Note that "x" is a perfectly valid expression: As such, "binoprhs" is
+us.  It takes a precedence and a pointer to an expression for the part that has been
+parsed so far.   Note that "x" is a perfectly valid expression: As such, "binoprhs" is
 allowed to be empty, in which case it returns the expression that is passed into
 it. In our example above, the code passes the expression for "a" into
 <tt>ParseBinOpRHS</tt> and the current token is "+".</p>
@@ -503,7 +526,7 @@ operator and that it will be included in this expression:</p>
 </div>
 
 <p>As such, this code eats (and remembers) the binary operator and then parses
-the following primary expression.  This builds up the whole pair, the first of
+the primary expression that follows.  This builds up the whole pair, the first of
 which is [+, b] for the running example.</p>
 
 <p>Now that we parsed the left-hand side of an expression and one pair of the 
@@ -523,8 +546,8 @@ compare it to BinOp's precedence (which is '+' in this case):</p>
 
 <p>If the precedence of the binop to the right of "RHS" is lower or equal to the
 precedence of our current operator, then we know that the parentheses associate
-as "(a+b) binop ...".  In our example, since the next operator is "+" and so is
-our current one, we know that they have the same precedence.  In this case we'll
+as "(a+b) binop ...".  In our example, the current operator is "+" and the next 
+operator is "+", we know that they have the same precedence.  In this case we'll
 create the AST node for "a+b", and then continue parsing:</p>
 
 <div class="doc_code">
@@ -540,10 +563,10 @@ create the AST node for "a+b", and then continue parsing:</p>
 </div>
 
 <p>In our example above, this will turn "a+b+" into "(a+b)" and execute the next
-iteration of the loop, with "+" as the current token.  The code above will eat
-and remember it and parse "(c+d)" as the primary expression, which makes the
-current pair be [+, (c+d)].  It will then enter the 'if' above with "*" as the
-binop to the right of the primary.  In this case, the precedence of "*" is
+iteration of the loop, with "+" as the current token.  The code above will eat
+remember, and parse "(c+d)" as the primary expression, which makes the
+current pair equal to [+, (c+d)].  It will then evaluate the 'if' conditional above with 
+"*" as the binop to the right of the primary.  In this case, the precedence of "*" is
 higher than the precedence of "+" so the if condition will be entered.</p>
 
 <p>The critical question left here is "how can the if condition parse the right
@@ -558,8 +581,8 @@ context):</p>
     // the pending operator take RHS as its LHS.
     int NextPrec = GetTokPrecedence();
     if (TokPrec &lt; NextPrec) {
-      RHS = ParseBinOpRHS(TokPrec+1, RHS);
-      if (RHS == 0) return 0;
+      <b>RHS = ParseBinOpRHS(TokPrec+1, RHS);
+      if (RHS == 0) return 0;</b>
     }
     // Merge LHS/RHS.
     LHS = new BinaryExprAST(BinOp, LHS, RHS);
@@ -577,26 +600,28 @@ precedence required for it to continue.  In our example above, this will cause
 it to return the AST node for "(c+d)*e*f" as RHS, which is then set as the RHS
 of the '+' expression.</p>
 
-<p>Finally, on the next iteration of the while loop, the "+g" piece is parsed.
+<p>Finally, on the next iteration of the while loop, the "+g" piece is parsed
 and added to the AST.  With this little bit of code (14 non-trivial lines), we
 correctly handle fully general binary expression parsing in a very elegant way.
+This was a whirlwind tour of this code, and it is somewhat subtle.  I recommend
+running through it with a few tough examples to see how it works.
 </p>
 
 <p>This wraps up handling of expressions.  At this point, we can point the
-parser at an arbitrary token stream and build an expression from them, stopping
+parser at an arbitrary token stream and build an expression from it, stopping
 at the first token that is not part of the expression.  Next up we need to
-handle function definitions etc.</p>
+handle function definitions, etc.</p>
 
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="parsertop">Parsing the Rest</a></div>
+<h2><a name="parsertop">Parsing the Rest</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <p>
-The first basic thing missing is that of function prototypes.  In Kaleidoscope,
+The next thing missing is handling of function prototypes.  In Kaleidoscope,
 these are used both for 'extern' function declarations as well as function body
 definitions.  The code to do this is straight-forward and not very interesting
 (once you've survived expressions):
@@ -616,6 +641,7 @@ static PrototypeAST *ParsePrototype() {
   if (CurTok != '(')
     return ErrorP("Expected '(' in prototype");
   
+  // Read the list of argument names.
   std::vector&lt;std::string&gt; ArgNames;
   while (getNextToken() == tok_identifier)
     ArgNames.push_back(IdentifierStr);
@@ -649,7 +675,7 @@ static FunctionAST *ParseDefinition() {
 </div>
 
 <p>In addition, we support 'extern' to declare functions like 'sin' and 'cos' as
-well as to support forward declaration of user functions.  'externs' are just
+well as to support forward declaration of user functions.  These 'extern's are just
 prototypes with no body:</p>
 
 <div class="doc_code">
@@ -680,16 +706,16 @@ static FunctionAST *ParseTopLevelExpr() {
 </pre>
 </div>
 
-<p>Now that we have all the pieces, lets build a little driver that will let us
+<p>Now that we have all the pieces, let's build a little driver that will let us
 actually <em>execute</em> this code we've built!</p>
 
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="driver">The Driver</a></div>
+<h2><a name="driver">The Driver</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <p>The driver for this simply invokes all of the parsing pieces with a top-level
 dispatch loop.  There isn't much interesting here, so I'll just include the
@@ -704,7 +730,7 @@ static void MainLoop() {
     fprintf(stderr, "ready&gt; ");
     switch (CurTok) {
     case tok_eof:    return;
-    case ';':        getNextToken(); break;  // ignore top level semicolons.
+    case ';':        getNextToken(); break;  // ignore top-level semicolons.
     case tok_def:    HandleDefinition(); break;
     case tok_extern: HandleExtern(); break;
     default:         HandleTopLevelExpression(); break;
@@ -714,69 +740,71 @@ static void MainLoop() {
 </pre>
 </div>
 
-<p>The most interesting part of this is that we ignore top-level semi colons.
+<p>The most interesting part of this is that we ignore top-level semicolons.
 Why is this, you ask?  The basic reason is that if you type "4 + 5" at the
-command line, the parser doesn't know that that is the end of what you will
-type.  For example, on the next line you could type "def foo..." in which case
+command line, the parser doesn't know whether that is the end of what you will type
+or not.  For example, on the next line you could type "def foo..." in which case
 4+5 is the end of a top-level expression.  Alternatively you could type "* 6",
 which would continue the expression.  Having top-level semicolons allows you to
-type "4+5;" and the parser will know you are done.</p> 
+type "4+5;", and the parser will know you are done.</p> 
 
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="code">Conclusions and the Full Code</a></div>
+<h2><a name="conclusions">Conclusions</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
-<p>With just under 400 lines of commented code, we fully defined our minimal
-language, including a lexer, parser and AST builder.  With this done, the
-executable will validate code and tell us if it is gramatically invalid.  For
+<p>With just under 400 lines of commented code (240 lines of non-comment, 
+non-blank code), we fully defined our minimal language, including a lexer,
+parser, and AST builder.  With this done, the executable will validate 
+Kaleidoscope code and tell us if it is grammatically invalid.  For
 example, here is a sample interaction:</p>
 
 <div class="doc_code">
 <pre>
-$ ./a.out 
-ready&gt; def foo(x y) x+foo(y, 4.0);
-ready&gt; Parsed an function definition.
-ready&gt; def foo(x y) x+y y;
-ready&gt; Parsed an function definition.
-ready&gt; Parsed a top-level expr
-ready&gt; def foo(x y) x+y );
-ready&gt; Parsed an function definition.
-ready&gt; Error: unknown token when expecting an expression
-ready&gt; extern sin(a);
+$ <b>./a.out</b>
+ready&gt; <b>def foo(x y) x+foo(y, 4.0);</b>
+Parsed a function definition.
+ready&gt; <b>def foo(x y) x+y y;</b>
+Parsed a function definition.
+Parsed a top-level expr
+ready&gt; <b>def foo(x y) x+y );</b>
+Parsed a function definition.
+Error: unknown token when expecting an expression
+ready&gt; <b>extern sin(a);</b>
 ready&gt; Parsed an extern
-ready&gt; ^D
+ready&gt; <b>^D</b>
 $ 
 </pre>
 </div>
 
 <p>There is a lot of room for extension here.  You can define new AST nodes,
 extend the language in many ways, etc.  In the <a href="LangImpl3.html">next
-installment</a>, we will describe how to generate LLVM IR from the AST.</p>
+installment</a>, we will describe how to generate LLVM Intermediate
+Representation (IR) from the AST.</p>
 
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="code">Full Code Listing</a></div>
+<h2><a name="code">Full Code Listing</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <p>
 Here is the complete code listing for this and the previous chapter.  
 Note that it is fully self-contained: you don't need LLVM or any external
-libraries at all for this (other than the C and C++ standard libraries of
-course).  To build this, just compile with:</p>
+libraries at all for this.  (Besides the C and C++ standard libraries, of
+course.)  To build this, just compile with:</p>
 
 <div class="doc_code">
 <pre>
-   # Compile
-   g++ -g toy.cpp 
-   # Run
-   ./a.out 
+# Compile
+clang++ -g -O3 toy.cpp
+# Run
+./a.out 
 </pre>
 </div>
 
@@ -785,6 +813,7 @@ course).  To build this, just compile with:</p>
 <div class="doc_code">
 <pre>
 #include &lt;cstdio&gt;
+#include &lt;cstdlib&gt;
 #include &lt;string&gt;
 #include &lt;map&gt;
 #include &lt;vector&gt;
@@ -802,7 +831,7 @@ enum Token {
   tok_def = -2, tok_extern = -3,
 
   // primary
-  tok_identifier = -4, tok_number = -5,
+  tok_identifier = -4, tok_number = -5
 };
 
 static std::string IdentifierStr;  // Filled in if tok_identifier
@@ -840,7 +869,7 @@ static int gettok() {
   if (LastChar == '#') {
     // Comment until end of line.
     do LastChar = getchar();
-    while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp; LastChar != '\r');
+    while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp;&amp; LastChar != '\r');
     
     if (LastChar != EOF)
       return gettok();
@@ -870,14 +899,14 @@ public:
 class NumberExprAST : public ExprAST {
   double Val;
 public:
-  explicit NumberExprAST(double val) : Val(val) {}
+  NumberExprAST(double val) : Val(val) {}
 };
 
 /// VariableExprAST - Expression class for referencing a variable, like "a".
 class VariableExprAST : public ExprAST {
   std::string Name;
 public:
-  explicit VariableExprAST(const std::string &amp;name) : Name(name) {}
+  VariableExprAST(const std::string &amp;name) : Name(name) {}
 };
 
 /// BinaryExprAST - Expression class for a binary operator.
@@ -899,10 +928,11 @@ public:
 };
 
 /// PrototypeAST - This class represents the "prototype" for a function,
-/// which captures its argument names as well as if it is an operator.
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes).
 class PrototypeAST {
   std::string Name;
-  std::vector&lt; Args;
+  std::vector&lt;std::string&gt; Args;
 public:
   PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args)
     : Name(name), Args(args) {}
@@ -924,7 +954,7 @@ public:
 //===----------------------------------------------------------------------===//
 
 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
-/// token the parser it looking at.  getNextToken reads another token from the
+/// token the parser is looking at.  getNextToken reads another token from the
 /// lexer and updates CurTok with its results.
 static int CurTok;
 static int getNextToken() {
@@ -954,12 +984,12 @@ FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
 static ExprAST *ParseExpression();
 
 /// identifierexpr
-///   ::= identifer
-///   ::= identifer '(' expression* ')'
+///   ::= identifier
+///   ::= identifier '(' expression* ')'
 static ExprAST *ParseIdentifierExpr() {
   std::string IdName = IdentifierStr;
   
-  getNextToken();  // eat identifer.
+  getNextToken();  // eat identifier.
   
   if (CurTok != '(') // Simple variable ref.
     return new VariableExprAST(IdName);
@@ -967,16 +997,18 @@ static ExprAST *ParseIdentifierExpr() {
   // Call.
   getNextToken();  // eat (
   std::vector&lt;ExprAST*&gt; Args;
-  while (1) {
-    ExprAST *Arg = ParseExpression();
-    if (!Arg) return 0;
-    Args.push_back(Arg);
-    
-    if (CurTok == ')') break;
-    
-    if (CurTok != ',')
-      return Error("Expected ')'");
-    getNextToken();
+  if (CurTok != ')') {
+    while (1) {
+      ExprAST *Arg = ParseExpression();
+      if (!Arg) return 0;
+      Args.push_back(Arg);
+
+      if (CurTok == ')') break;
+
+      if (CurTok != ',')
+        return Error("Expected ')' or ',' in argument list");
+      getNextToken();
+    }
   }
 
   // Eat the ')'.
@@ -1099,7 +1131,7 @@ static FunctionAST *ParseDefinition() {
 static FunctionAST *ParseTopLevelExpr() {
   if (ExprAST *E = ParseExpression()) {
     // Make an anonymous proto.
-    PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;());
+    PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;std::string&gt;());
     return new FunctionAST(Proto, E);
   }
   return 0;
@@ -1116,7 +1148,7 @@ static PrototypeAST *ParseExtern() {
 //===----------------------------------------------------------------------===//
 
 static void HandleDefinition() {
-  if (FunctionAST *F = ParseDefinition()) {
+  if (ParseDefinition()) {
     fprintf(stderr, "Parsed a function definition.\n");
   } else {
     // Skip token for error recovery.
@@ -1125,7 +1157,7 @@ static void HandleDefinition() {
 }
 
 static void HandleExtern() {
-  if (PrototypeAST *P = ParseExtern()) {
+  if (ParseExtern()) {
     fprintf(stderr, "Parsed an extern\n");
   } else {
     // Skip token for error recovery.
@@ -1134,8 +1166,8 @@ static void HandleExtern() {
 }
 
 static void HandleTopLevelExpression() {
-  // Evaluate a top level expression into an anonymous function.
-  if (FunctionAST *F = ParseTopLevelExpr()) {
+  // Evaluate a top-level expression into an anonymous function.
+  if (ParseTopLevelExpr()) {
     fprintf(stderr, "Parsed a top-level expr\n");
   } else {
     // Skip token for error recovery.
@@ -1149,7 +1181,7 @@ static void MainLoop() {
     fprintf(stderr, "ready&gt; ");
     switch (CurTok) {
     case tok_eof:    return;
-    case ';':        getNextToken(); break;  // ignore top level semicolons.
+    case ';':        getNextToken(); break;  // ignore top-level semicolons.
     case tok_def:    HandleDefinition(); break;
     case tok_extern: HandleExtern(); break;
     default:         HandleTopLevelExpression(); break;
@@ -1173,11 +1205,14 @@ int main() {
   fprintf(stderr, "ready&gt; ");
   getNextToken();
 
+  // Run the main "interpreter loop" now.
   MainLoop();
+
   return 0;
 }
 </pre>
 </div>
+<a href="LangImpl3.html">Next: Implementing Code Generation to LLVM IR</a>
 </div>
 
 <!-- *********************************************************************** -->
@@ -1189,8 +1224,8 @@ int main() {
   src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
 
   <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
-  <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
-  Last modified: $Date: 2007-10-17 11:05:13 -0700 (Wed, 17 Oct 2007) $
+  <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+  Last modified: $Date$
 </address>
 </body>
 </html>