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