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