annotate llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl01.rst @ 266:00f31e85ec16 default tip

Added tag current for changeset 31d058e83c98
author Shinji KONO <kono@ie.u-ryukyu.ac.jp>
date Sat, 14 Oct 2023 10:13:55 +0900
parents 1d019706d866
children
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
150
anatofuz
parents:
diff changeset
1 =====================================================
anatofuz
parents:
diff changeset
2 Kaleidoscope: Kaleidoscope Introduction and the Lexer
anatofuz
parents:
diff changeset
3 =====================================================
anatofuz
parents:
diff changeset
4
anatofuz
parents:
diff changeset
5 .. contents::
anatofuz
parents:
diff changeset
6 :local:
anatofuz
parents:
diff changeset
7
anatofuz
parents:
diff changeset
8 The Kaleidoscope Language
anatofuz
parents:
diff changeset
9 =========================
anatofuz
parents:
diff changeset
10
anatofuz
parents:
diff changeset
11 This tutorial is illustrated with a toy language called
anatofuz
parents:
diff changeset
12 "`Kaleidoscope <http://en.wikipedia.org/wiki/Kaleidoscope>`_" (derived
anatofuz
parents:
diff changeset
13 from "meaning beautiful, form, and view"). Kaleidoscope is a procedural
anatofuz
parents:
diff changeset
14 language that allows you to define functions, use conditionals, math,
anatofuz
parents:
diff changeset
15 etc. Over the course of the tutorial, we'll extend Kaleidoscope to
anatofuz
parents:
diff changeset
16 support the if/then/else construct, a for loop, user defined operators,
anatofuz
parents:
diff changeset
17 JIT compilation with a simple command line interface, debug info, etc.
anatofuz
parents:
diff changeset
18
anatofuz
parents:
diff changeset
19 We want to keep things simple, so the only datatype in Kaleidoscope
anatofuz
parents:
diff changeset
20 is a 64-bit floating point type (aka 'double' in C parlance). As such,
anatofuz
parents:
diff changeset
21 all values are implicitly double precision and the language doesn't
anatofuz
parents:
diff changeset
22 require type declarations. This gives the language a very nice and
anatofuz
parents:
diff changeset
23 simple syntax. For example, the following simple example computes
anatofuz
parents:
diff changeset
24 `Fibonacci numbers: <http://en.wikipedia.org/wiki/Fibonacci_number>`_
anatofuz
parents:
diff changeset
25
anatofuz
parents:
diff changeset
26 ::
anatofuz
parents:
diff changeset
27
anatofuz
parents:
diff changeset
28 # Compute the x'th fibonacci number.
anatofuz
parents:
diff changeset
29 def fib(x)
anatofuz
parents:
diff changeset
30 if x < 3 then
anatofuz
parents:
diff changeset
31 1
anatofuz
parents:
diff changeset
32 else
anatofuz
parents:
diff changeset
33 fib(x-1)+fib(x-2)
anatofuz
parents:
diff changeset
34
anatofuz
parents:
diff changeset
35 # This expression will compute the 40th number.
anatofuz
parents:
diff changeset
36 fib(40)
anatofuz
parents:
diff changeset
37
anatofuz
parents:
diff changeset
38 We also allow Kaleidoscope to call into standard library functions - the
anatofuz
parents:
diff changeset
39 LLVM JIT makes this really easy. This means that you can use the
anatofuz
parents:
diff changeset
40 'extern' keyword to define a function before you use it (this is also
anatofuz
parents:
diff changeset
41 useful for mutually recursive functions). For example:
anatofuz
parents:
diff changeset
42
anatofuz
parents:
diff changeset
43 ::
anatofuz
parents:
diff changeset
44
anatofuz
parents:
diff changeset
45 extern sin(arg);
anatofuz
parents:
diff changeset
46 extern cos(arg);
anatofuz
parents:
diff changeset
47 extern atan2(arg1 arg2);
anatofuz
parents:
diff changeset
48
anatofuz
parents:
diff changeset
49 atan2(sin(.4), cos(42))
anatofuz
parents:
diff changeset
50
anatofuz
parents:
diff changeset
51 A more interesting example is included in Chapter 6 where we write a
anatofuz
parents:
diff changeset
52 little Kaleidoscope application that `displays a Mandelbrot
anatofuz
parents:
diff changeset
53 Set <LangImpl06.html#kicking-the-tires>`_ at various levels of magnification.
anatofuz
parents:
diff changeset
54
anatofuz
parents:
diff changeset
55 Let's dive into the implementation of this language!
anatofuz
parents:
diff changeset
56
anatofuz
parents:
diff changeset
57 The Lexer
anatofuz
parents:
diff changeset
58 =========
anatofuz
parents:
diff changeset
59
anatofuz
parents:
diff changeset
60 When it comes to implementing a language, the first thing needed is the
anatofuz
parents:
diff changeset
61 ability to process a text file and recognize what it says. The
anatofuz
parents:
diff changeset
62 traditional way to do this is to use a
anatofuz
parents:
diff changeset
63 "`lexer <http://en.wikipedia.org/wiki/Lexical_analysis>`_" (aka
anatofuz
parents:
diff changeset
64 'scanner') to break the input up into "tokens". Each token returned by
anatofuz
parents:
diff changeset
65 the lexer includes a token code and potentially some metadata (e.g. the
anatofuz
parents:
diff changeset
66 numeric value of a number). First, we define the possibilities:
anatofuz
parents:
diff changeset
67
anatofuz
parents:
diff changeset
68 .. code-block:: c++
anatofuz
parents:
diff changeset
69
anatofuz
parents:
diff changeset
70 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
anatofuz
parents:
diff changeset
71 // of these for known things.
anatofuz
parents:
diff changeset
72 enum Token {
anatofuz
parents:
diff changeset
73 tok_eof = -1,
anatofuz
parents:
diff changeset
74
anatofuz
parents:
diff changeset
75 // commands
anatofuz
parents:
diff changeset
76 tok_def = -2,
anatofuz
parents:
diff changeset
77 tok_extern = -3,
anatofuz
parents:
diff changeset
78
anatofuz
parents:
diff changeset
79 // primary
anatofuz
parents:
diff changeset
80 tok_identifier = -4,
anatofuz
parents:
diff changeset
81 tok_number = -5,
anatofuz
parents:
diff changeset
82 };
anatofuz
parents:
diff changeset
83
anatofuz
parents:
diff changeset
84 static std::string IdentifierStr; // Filled in if tok_identifier
anatofuz
parents:
diff changeset
85 static double NumVal; // Filled in if tok_number
anatofuz
parents:
diff changeset
86
anatofuz
parents:
diff changeset
87 Each token returned by our lexer will either be one of the Token enum
anatofuz
parents:
diff changeset
88 values or it will be an 'unknown' character like '+', which is returned
anatofuz
parents:
diff changeset
89 as its ASCII value. If the current token is an identifier, the
anatofuz
parents:
diff changeset
90 ``IdentifierStr`` global variable holds the name of the identifier. If
anatofuz
parents:
diff changeset
91 the current token is a numeric literal (like 1.0), ``NumVal`` holds its
anatofuz
parents:
diff changeset
92 value. We use global variables for simplicity, but this is not the
anatofuz
parents:
diff changeset
93 best choice for a real language implementation :).
anatofuz
parents:
diff changeset
94
anatofuz
parents:
diff changeset
95 The actual implementation of the lexer is a single function named
anatofuz
parents:
diff changeset
96 ``gettok``. The ``gettok`` function is called to return the next token
anatofuz
parents:
diff changeset
97 from standard input. Its definition starts as:
anatofuz
parents:
diff changeset
98
anatofuz
parents:
diff changeset
99 .. code-block:: c++
anatofuz
parents:
diff changeset
100
anatofuz
parents:
diff changeset
101 /// gettok - Return the next token from standard input.
anatofuz
parents:
diff changeset
102 static int gettok() {
anatofuz
parents:
diff changeset
103 static int LastChar = ' ';
anatofuz
parents:
diff changeset
104
anatofuz
parents:
diff changeset
105 // Skip any whitespace.
anatofuz
parents:
diff changeset
106 while (isspace(LastChar))
anatofuz
parents:
diff changeset
107 LastChar = getchar();
anatofuz
parents:
diff changeset
108
anatofuz
parents:
diff changeset
109 ``gettok`` works by calling the C ``getchar()`` function to read
anatofuz
parents:
diff changeset
110 characters one at a time from standard input. It eats them as it
anatofuz
parents:
diff changeset
111 recognizes them and stores the last character read, but not processed,
anatofuz
parents:
diff changeset
112 in LastChar. The first thing that it has to do is ignore whitespace
anatofuz
parents:
diff changeset
113 between tokens. This is accomplished with the loop above.
anatofuz
parents:
diff changeset
114
anatofuz
parents:
diff changeset
115 The next thing ``gettok`` needs to do is recognize identifiers and
anatofuz
parents:
diff changeset
116 specific keywords like "def". Kaleidoscope does this with this simple
anatofuz
parents:
diff changeset
117 loop:
anatofuz
parents:
diff changeset
118
anatofuz
parents:
diff changeset
119 .. code-block:: c++
anatofuz
parents:
diff changeset
120
anatofuz
parents:
diff changeset
121 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
anatofuz
parents:
diff changeset
122 IdentifierStr = LastChar;
anatofuz
parents:
diff changeset
123 while (isalnum((LastChar = getchar())))
anatofuz
parents:
diff changeset
124 IdentifierStr += LastChar;
anatofuz
parents:
diff changeset
125
anatofuz
parents:
diff changeset
126 if (IdentifierStr == "def")
anatofuz
parents:
diff changeset
127 return tok_def;
anatofuz
parents:
diff changeset
128 if (IdentifierStr == "extern")
anatofuz
parents:
diff changeset
129 return tok_extern;
anatofuz
parents:
diff changeset
130 return tok_identifier;
anatofuz
parents:
diff changeset
131 }
anatofuz
parents:
diff changeset
132
anatofuz
parents:
diff changeset
133 Note that this code sets the '``IdentifierStr``' global whenever it
anatofuz
parents:
diff changeset
134 lexes an identifier. Also, since language keywords are matched by the
anatofuz
parents:
diff changeset
135 same loop, we handle them here inline. Numeric values are similar:
anatofuz
parents:
diff changeset
136
anatofuz
parents:
diff changeset
137 .. code-block:: c++
anatofuz
parents:
diff changeset
138
anatofuz
parents:
diff changeset
139 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
anatofuz
parents:
diff changeset
140 std::string NumStr;
anatofuz
parents:
diff changeset
141 do {
anatofuz
parents:
diff changeset
142 NumStr += LastChar;
anatofuz
parents:
diff changeset
143 LastChar = getchar();
anatofuz
parents:
diff changeset
144 } while (isdigit(LastChar) || LastChar == '.');
anatofuz
parents:
diff changeset
145
anatofuz
parents:
diff changeset
146 NumVal = strtod(NumStr.c_str(), 0);
anatofuz
parents:
diff changeset
147 return tok_number;
anatofuz
parents:
diff changeset
148 }
anatofuz
parents:
diff changeset
149
anatofuz
parents:
diff changeset
150 This is all pretty straightforward code for processing input. When
anatofuz
parents:
diff changeset
151 reading a numeric value from input, we use the C ``strtod`` function to
anatofuz
parents:
diff changeset
152 convert it to a numeric value that we store in ``NumVal``. Note that
anatofuz
parents:
diff changeset
153 this isn't doing sufficient error checking: it will incorrectly read
anatofuz
parents:
diff changeset
154 "1.23.45.67" and handle it as if you typed in "1.23". Feel free to
anatofuz
parents:
diff changeset
155 extend it! Next we handle comments:
anatofuz
parents:
diff changeset
156
anatofuz
parents:
diff changeset
157 .. code-block:: c++
anatofuz
parents:
diff changeset
158
anatofuz
parents:
diff changeset
159 if (LastChar == '#') {
anatofuz
parents:
diff changeset
160 // Comment until end of line.
anatofuz
parents:
diff changeset
161 do
anatofuz
parents:
diff changeset
162 LastChar = getchar();
anatofuz
parents:
diff changeset
163 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
anatofuz
parents:
diff changeset
164
anatofuz
parents:
diff changeset
165 if (LastChar != EOF)
anatofuz
parents:
diff changeset
166 return gettok();
anatofuz
parents:
diff changeset
167 }
anatofuz
parents:
diff changeset
168
anatofuz
parents:
diff changeset
169 We handle comments by skipping to the end of the line and then return
anatofuz
parents:
diff changeset
170 the next token. Finally, if the input doesn't match one of the above
anatofuz
parents:
diff changeset
171 cases, it is either an operator character like '+' or the end of the
anatofuz
parents:
diff changeset
172 file. These are handled with this code:
anatofuz
parents:
diff changeset
173
anatofuz
parents:
diff changeset
174 .. code-block:: c++
anatofuz
parents:
diff changeset
175
anatofuz
parents:
diff changeset
176 // Check for end of file. Don't eat the EOF.
anatofuz
parents:
diff changeset
177 if (LastChar == EOF)
anatofuz
parents:
diff changeset
178 return tok_eof;
anatofuz
parents:
diff changeset
179
anatofuz
parents:
diff changeset
180 // Otherwise, just return the character as its ascii value.
anatofuz
parents:
diff changeset
181 int ThisChar = LastChar;
anatofuz
parents:
diff changeset
182 LastChar = getchar();
anatofuz
parents:
diff changeset
183 return ThisChar;
anatofuz
parents:
diff changeset
184 }
anatofuz
parents:
diff changeset
185
anatofuz
parents:
diff changeset
186 With this, we have the complete lexer for the basic Kaleidoscope
anatofuz
parents:
diff changeset
187 language (the `full code listing <LangImpl02.html#full-code-listing>`_ for the Lexer
anatofuz
parents:
diff changeset
188 is available in the `next chapter <LangImpl02.html>`_ of the tutorial).
anatofuz
parents:
diff changeset
189 Next we'll `build a simple parser that uses this to build an Abstract
anatofuz
parents:
diff changeset
190 Syntax Tree <LangImpl02.html>`_. When we have that, we'll include a
anatofuz
parents:
diff changeset
191 driver so that you can use the lexer and parser together.
anatofuz
parents:
diff changeset
192
anatofuz
parents:
diff changeset
193 `Next: Implementing a Parser and AST <LangImpl02.html>`_
anatofuz
parents:
diff changeset
194