Fix for PR11652: assertion failures when Type.cpp is compiled with -Os
[oota-llvm.git] / docs / tutorial / LangImpl2.html
index 6dba2607714daf0f66b15d60b77bec4a0cfd2c5f..60e4f7f5e4e928c51c42d7349734fe838bb1190d 100644 (file)
@@ -11,7 +11,7 @@
 
 <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>
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="intro">Chapter 2 Introduction</a></div>
+<h2><a name="intro">Chapter 2 Introduction</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <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 
@@ -61,10 +61,10 @@ 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 such a way that it is easy for
 later stages of the compiler (e.g. code generation) to interpret.  We basically
@@ -84,7 +84,7 @@ public:
 class NumberExprAST : public ExprAST {
   double Val;
 public:
-  explicit NumberExprAST(double val) : Val(val) {}
+  NumberExprAST(double val) : Val(val) {}
 };
 </pre>
 </div>
@@ -98,7 +98,7 @@ 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">
@@ -107,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.
@@ -130,7 +130,7 @@ 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 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 
@@ -178,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
@@ -201,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() {
@@ -239,11 +239,10 @@ 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
@@ -263,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 and finally
+a <tt>NumberExprAST</tt> node, advances the lexer to the next token, and finally
 returns.</p>
 
 <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
+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
@@ -293,7 +292,7 @@ static ExprAST *ParseParenExpr() {
 parser:</p>
 
 <p>
-1) it shows how we use the Error routines.  When called, this function expects
+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 no ')' waiting.  For example, if the user types in
 "(4 x" instead of "(4)", the parser should emit an error.  Because errors can
@@ -305,8 +304,8 @@ calling <tt>ParseExpression</tt> (we will soon see that <tt>ParseExpression</tt>
 <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 it this way, the most important role of parens are to guide the parser and
-provide grouping.  Once the parser constructs the AST, parens are not 
+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
@@ -333,11 +332,11 @@ static ExprAST *ParseIdentifierExpr() {
       ExprAST *Arg = ParseExpression();
       if (!Arg) return 0;
       Args.push_back(Arg);
-    
+
       if (CurTok == ')') break;
-    
+
       if (CurTok != ',')
-        return Error("Expected ')'");
+        return Error("Expected ')' or ',' in argument list");
       getNextToken();
     }
   }
@@ -350,21 +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 it together into one entry-point.  We call this
+<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
-specific expression it is:</p>
+expression it is:</p>
 
 <div class="doc_code">
 <pre>
@@ -383,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
@@ -447,12 +445,12 @@ int main() {
 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 (or just use
+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
@@ -617,10 +615,10 @@ 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 next thing missing is handling of function prototypes.  In Kaleidoscope,
@@ -708,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
@@ -732,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;
@@ -742,26 +740,26 @@ 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 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="conclusions">Conclusions</a></div>
+<h2><a name="conclusions">Conclusions</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <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 gramatically invalid.  For
+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">
@@ -790,23 +788,23 @@ 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 -O3 toy.cpp 
-   # Run
-   ./a.out 
+# Compile
+clang++ -g -O3 toy.cpp
+# Run
+./a.out 
 </pre>
 </div>
 
@@ -815,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;
@@ -832,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
@@ -870,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();
@@ -900,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.
@@ -933,7 +932,7 @@ public:
 /// 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) {}
@@ -955,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() {
@@ -1003,11 +1002,11 @@ static ExprAST *ParseIdentifierExpr() {
       ExprAST *Arg = ParseExpression();
       if (!Arg) return 0;
       Args.push_back(Arg);
-    
+
       if (CurTok == ')') break;
-    
+
       if (CurTok != ',')
-        return Error("Expected ')'");
+        return Error("Expected ')' or ',' in argument list");
       getNextToken();
     }
   }
@@ -1132,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;
@@ -1149,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.
@@ -1158,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.
@@ -1167,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.
@@ -1182,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;
@@ -1206,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>
 
 <!-- *********************************************************************** -->
@@ -1222,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>