MimIR 0.1
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
lexer.cpp
Go to the documentation of this file.
1#include "mim/ast/lexer.h"
2
3#include "mim/ast/ast.h"
4
5using namespace std::literals;
6
7namespace mim::ast {
8
9namespace utf8 = fe::utf8;
10using Tag = Tok::Tag;
11
12Lexer::Lexer(AST& ast, std::istream& istream, const fs::path* path /*= nullptr*/, std::ostream* md /*= nullptr*/)
13 : Super(istream, path)
14 , ast_(ast)
15 , md_(md) {
16#define CODE(t, str) keywords_[ast.sym(str)] = Tag::t;
18#undef CODE
19
20#define CODE(str, t) \
21 if (Tag::t != Tag::Nil) keywords_[ast.sym(str)] = Tag::t;
23#undef CODE
24
25 if (start_md())
26 emit_md(true);
27 else
28 md_fence();
29}
30
32 while (true) {
33 start();
34
35 if (accept(utf8::EoF)) return tok(Tag::EoF);
36 if (accept(utf8::isspace)) continue;
37 if (accept(utf8::Null)) {
38 ast().error(loc_, "invalid UTF-8 character");
39 continue;
40 }
41
42 // clang-format off
43 // delimiters
44 if (accept( '(')) return tok(Tag::D_paren_l);
45 if (accept( ')')) return tok(Tag::D_paren_r);
46 if (accept( '[')) return tok(Tag::D_brckt_l);
47 if (accept( ']')) return tok(Tag::D_brckt_r);
48 if (accept( '{')) return tok(Tag::D_brace_l);
49 if (accept( '}')) return tok(Tag::D_brace_r);
50 if (accept(U'«')) return tok(Tag::D_quote_l);
51 if (accept(U'»')) return tok(Tag::D_quote_r);
52 if (accept(U'⟪')) return tok(Tag::D_quote_l);
53 if (accept(U'⟫')) return tok(Tag::D_quote_r);
54 if (accept(U'‹')) return tok(Tag::D_angle_l);
55 if (accept(U'›')) return tok(Tag::D_angle_r);
56 if (accept(U'⟨')) return tok(Tag::D_angle_l);
57 if (accept(U'⟩')) return tok(Tag::D_angle_r);
58 if (accept( '<')) {
59 if (accept( '<')) return tok(Tag::D_quote_l);
60 return tok(Tag::D_angle_l);
61 }
62 if (accept( '>')) {
63 if (accept( '>')) return tok(Tag::D_quote_r);
64 return tok(Tag::D_angle_r);
65 }
66 // further tokens
67 if (accept('`')) return tok(Tag::T_backtick);
68 if (accept(U'→')) return tok(Tag::T_arrow);
69 if (accept( '@')) return tok(Tag::T_at);
70 if (accept( '=')) return tok(Tag::T_assign);
71 if (accept(U'⊥')) return tok(Tag::T_bot);
72 if (accept(U'⊤')) return tok(Tag::T_top);
73 if (accept(U'□')) return tok(Tag::T_box);
74 if (accept( ',')) return tok(Tag::T_comma);
75 if (accept( '$')) return tok(Tag::T_dollar);
76 if (accept( '#')) return tok(Tag::T_extract);
77 if (accept(U'λ')) return tok(Tag::T_lm);
78 if (accept( ';')) return tok(Tag::T_semicolon);
79 if (accept(U'★')) return tok(Tag::T_star);
80 if (accept( '*')) return tok(Tag::T_star);
81 if (accept( ':')) {
82 if (accept( ':')) return tok(Tag::T_colon_colon);
83 return tok(Tag::T_colon);
84 }
85 // clang-format on
86
87 if (accept('%')) {
88 if (lex_id()) return {loc_, Tag::M_anx, sym()};
89 ast().error(loc_, "invalid axiom name '{}'", str_);
90 continue;
91 }
92
93 if (accept('.')) {
94 if (accept(utf8::isdigit)) {
95 parse_digits();
96 parse_exp();
97 return {loc_, f64(std::strtod(str_.c_str(), nullptr))};
98 }
99
100 return tok(Tag::T_dot);
101 }
102
103 if (accept('\'')) {
104 auto c = lex_char();
105 if (accept('\'')) return {loc_, c};
106 ast().error(loc_, "invalid character literal {}", str_);
107 continue;
108 }
109
110 if (accept<Append::Off>('\"')) {
111 while (lex_char() != '"') {}
112 str_.pop_back(); // remove final '"'
113 return {loc_, Tag::L_str, sym()};
114 }
115
116 if (lex_id()) {
117 if (auto i = keywords_.find(sym()); i != keywords_.end()) return tok(i->second);
118 return {loc_, Tag::M_id, sym()};
119 }
120
121 if (utf8::isdigit(ahead()) || utf8::any('+', '-')(ahead())) {
122 if (auto lit = parse_lit()) return *lit;
123 continue;
124 }
125
126 if (start_md()) {
127 emit_md();
128 continue;
129 }
130
131 // comments
132 if (accept('/')) {
133 if (accept('*')) {
134 eat_comments();
135 continue;
136 }
137 if (accept('/')) {
138 while (ahead() != utf8::EoF && ahead() != '\n') next();
139 continue;
140 }
141
142 ast().error({loc_.path, peek_}, "invalid input char '/'; maybe you wanted to start a comment?");
143 continue;
144 }
145
146 ast().error({loc_.path, peek_}, "invalid input char '{}'", utf8::Char32(ahead()));
147 next();
148 }
149}
150
151bool Lexer::lex_id() {
152 if (accept([](char32_t c) { return c == '_' || utf8::isalpha(c); })) {
153 while (accept([](char32_t c) { return c == '_' || c == '.' || utf8::isalnum(c); })) {}
154 return true;
155 }
156 return false;
157}
158
159// clang-format off
160std::optional<Tok> Lexer::parse_lit() {
161 int base = 10;
162 std::optional<bool> sign;
163
164 if (accept<Append::Off>('+')) {
165 sign = false;
166 } else if (accept<Append::Off>('-')) {
167 if (accept('>')) return tok(Tag::T_arrow);
168 sign = true;
169 }
170
171 // prefix starting with '0'
172 if (accept<Append::Off>('0')) {
173 if (accept<Append::Off>('b')) base = 2;
174 else if (accept<Append::Off>('B')) base = 2;
175 else if (accept<Append::Off>('o')) base = 8;
176 else if (accept<Append::Off>('O')) base = 8;
177 else if (accept<Append::Off>('x')) base = 16;
178 else if (accept<Append::Off>('X')) base = 16;
179 }
180
181 parse_digits(base);
182
183 if (accept(utf8::any('i', 'I'))) {
184 if (sign) str_.insert(0, "-"sv);
185 auto val = std::strtoull(str_.c_str(), nullptr, base);
186 str_.clear();
187 parse_digits();
188 auto width = std::strtoull(str_.c_str(), nullptr, 10);
189 return Tok{loc_, ast().world().lit_int(width, val)};
190 }
191
192 if (!sign && base == 10) {
193 if (utf8::isrange(ahead(), U'₀', U'₉')) {
194 auto i = std::strtoull(str_.c_str(), nullptr, 10);
195 std::string mod;
196 while (utf8::isrange(ahead(), U'₀', U'₉')) mod += next() - U'₀' + '0';
197 auto m = std::strtoull(mod.c_str(), nullptr, 10);
198 return Tok{loc_, ast().world().lit_idx_mod(m, i)};
199 } else if (accept<Append::Off>('_')) {
200 auto i = std::strtoull(str_.c_str(), nullptr, 10);
201 str_.clear();
202 if (accept(utf8::isdigit)) {
203 parse_digits(10);
204 auto m = std::strtoull(str_.c_str(), nullptr, 10);
205 return Tok{loc_, ast().world().lit_idx_mod(m, i)};
206 } else {
207 ast().error(loc_, "stray underscore in Idx literal; size is missing");
208 auto i = std::strtoull(str_.c_str(), nullptr, 10);
209 return Tok{loc_, u64(i)};
210 }
211 }
212 }
213
214 bool is_float = false;
215 if (base == 10 || base == 16) {
216 // parse fractional part
217 if (accept('.')) {
218 is_float = true;
219 parse_digits(base);
220 }
221
222 bool has_exp = parse_exp(base);
223 if (base == 16 && is_float && !has_exp) ast().error(loc_, "hexadecimal floating constants require an exponent");
224 is_float |= has_exp;
225 }
226
227 if (sign && str_.empty()) {
228 ast().error(loc_, "stray '{}'", *sign ? "-" : "+");
229 return {};
230 }
231
232 if (is_float && base == 16) str_.insert(0, "0x"sv);
233 if (sign && *sign) str_.insert(0, "-"sv);
234
235 if (is_float) return Tok{loc_, f64(std::strtod (str_.c_str(), nullptr ))};
236 if (sign) return Tok{loc_, u64(std::strtoll (str_.c_str(), nullptr, base))};
237 else return Tok{loc_, u64(std::strtoull(str_.c_str(), nullptr, base))};
238}
239
240void Lexer::parse_digits(int base /*= 10*/) {
241 switch (base) {
242 // clang-format off
243 case 2: while (accept(utf8::isbdigit)) {} break;
244 case 8: while (accept(utf8::isodigit)) {} break;
245 case 10: while (accept(utf8::isdigit)) {} break;
246 case 16: while (accept(utf8::isxdigit)) {} break;
247 // clang-format on
248 default: fe::unreachable();
249 }
250}
251
252bool Lexer::parse_exp(int base /*= 10*/) {
253 if (accept(base == 10 ? utf8::any('e', 'E') : utf8::any('p', 'P'))) {
254 accept(utf8::any('+', '-'));
255 if (!utf8::isdigit(ahead())) ast().error(loc_, "exponent has no digits");
256 parse_digits();
257 return true;
258 }
259 return false;
260}
261// clang-format on
262
263char8_t Lexer::lex_char() {
264 if (accept<Append::Off>('\\')) {
265 // clang-format off
266 if (false) {}
267 else if (accept<Append::Off>('\'')) str_ += '\'';
268 else if (accept<Append::Off>('\\')) str_ += '\\';
269 else if (accept<Append::Off>( '"')) str_ += '\"';
270 else if (accept<Append::Off>( '0')) str_ += '\0';
271 else if (accept<Append::Off>( 'a')) str_ += '\a';
272 else if (accept<Append::Off>( 'b')) str_ += '\b';
273 else if (accept<Append::Off>( 'f')) str_ += '\f';
274 else if (accept<Append::Off>( 'n')) str_ += '\n';
275 else if (accept<Append::Off>( 'r')) str_ += '\r';
276 else if (accept<Append::Off>( 't')) str_ += '\t';
277 else if (accept<Append::Off>( 'v')) str_ += '\v';
278 else ast().error(loc_.anew_finis(), "invalid escape character '\\{}'", (char)ahead());
279 // clang-format on
280 return str_.back();
281 }
282 auto c = next();
283 str_ += c;
284 if (utf8::isascii(c)) return c;
285 ast().error(loc_, "invalid character '{}'", (char)c);
286 return '\0';
287}
288
289void Lexer::eat_comments() {
290 while (true) {
291 while (ahead() != utf8::EoF && ahead() != '*') next();
292 if (accept(utf8::EoF)) {
293 ast().error(loc_, "non-terminated multiline comment");
294 return;
295 }
296 next();
297 if (accept('/')) break;
298 }
299}
300
301void Lexer::emit_md(bool start_of_file) {
302 if (!start_of_file) md_fence();
303
304 do {
305 out_ = false;
306 for (int i = 0; i < 3; ++i) next();
307 accept(' ');
308 out_ = true;
309
310 while (ahead() != utf8::EoF && ahead() != '\n') next();
311 accept('\n');
312 } while (start_md());
313
314 if (ahead() == utf8::EoF)
315 out_ = false;
316 else
317 md_fence();
318}
319
320Sym Lexer::sym() { return ast().sym(str_); }
321
322} // namespace mim::ast
const Lit * lit_idx_mod(nat_t mod, u64 val)
Constructs a Lit of type Idx of size mod.
Definition world.h:423
const Lit * lit_int(nat_t width, u64 val)
Constructs a Lit of type Idx of size $2^width$.
Definition world.h:410
World & world()
Definition ast.h:61
Error & error()
Definition ast.h:63
Sym sym(const char *s)
Definition ast.h:69
Lexer(AST &, std::istream &, const fs::path *path=nullptr, std::ostream *md=nullptr)
Creates a lexer to read *.mim files (see Lexical Structure).
Definition lexer.cpp:12
AST & ast()
Definition lexer.h:22
Definition ast.h:14
double f64
Definition types.h:41
uint64_t u64
Definition types.h:34
#define MIM_SUBST(m)
Definition tok.h:98
#define CODE(t, str)
Definition tok.h:53
#define MIM_KEY(m)
Definition tok.h:13