MimIR 0.1
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
parser.cpp
Go to the documentation of this file.
1#include "mim/ast/parser.h"
2
3#include <filesystem>
4#include <fstream>
5#include <ranges>
6
7#include "mim/driver.h"
8
9// clang-format off
10#define C_PRIMARY \
11 K_Univ: \
12 case Tag::K_Nat: \
13 case Tag::K_Idx: \
14 case Tag::K_Bool: \
15 case Tag::K_ff: \
16 case Tag::K_tt: \
17 case Tag::K_i1: \
18 case Tag::K_i8: \
19 case Tag::K_i16: \
20 case Tag::K_i32: \
21 case Tag::K_i64: \
22 case Tag::K_I1: \
23 case Tag::K_I8: \
24 case Tag::K_I16: \
25 case Tag::K_I32: \
26 case Tag::K_I64: \
27 case Tag::T_star: \
28 case Tag::T_box
29
30#define C_ID \
31 M_anx: \
32 case Tag::M_id
33
34#define C_LIT \
35 T_bot: \
36 case Tag::T_top: \
37 case Tag::L_str: \
38 case Tag::L_c: \
39 case Tag::L_s: \
40 case Tag::L_u: \
41 case Tag::L_f: \
42 case Tag::L_i
43
44#define C_LAM \
45 K_lam: \
46 case Tag::K_con: \
47 case Tag::K_fun
48
49#define C_DECL \
50 K_axm: \
51 case Tag::K_let: \
52 case Tag::K_rec: \
53 case Tag::K_ccon: \
54 case Tag::K_cfun: \
55 case Tag::C_LAM
56
57#define C_PI \
58 D_brace_l: \
59 case Tag::K_Cn: \
60 case Tag::K_Fn
61
62#define C_LM \
63 T_lm: \
64 case Tag::K_cn: \
65 case Tag::K_fn
66
67#define C_EXPR \
68 C_PRIMARY: \
69 case Tag::C_ID: \
70 case Tag::C_LIT: \
71 case Tag::C_DECL: \
72 case Tag::C_PI: \
73 case Tag::C_LM: \
74 case Tag::K_Type: /*TypeExpr*/ \
75 case Tag::K_ins: /*InsertExpr*/ \
76 case Tag::K_ret: /*RetExpr*/ \
77 case Tag::D_angle_l: /*PackExpr*/ \
78 case Tag::D_brckt_l: /*SigmaExpr*/ \
79 case Tag::D_curly_l: /*UniqExpr*/ \
80 case Tag::D_paren_l: /*TupleExpr*/ \
81 case Tag::D_quote_l /*ArrExpr*/
82
83#define C_CURRIED_B \
84 D_brace_l: \
85 case Tag::D_brckt_l: \
86 case Tag::D_quote_l
87
88#define C_CURRIED_P \
89 D_brace_l: \
90 case Tag::D_brckt_l: \
91 case Tag::D_paren_l
92// clang-format on
93
94using namespace std::string_literals;
95
96namespace mim::ast {
97
98using Tag = Tok::Tag;
99
100/*
101 * entry points
102 */
103
104Ptr<Module> Parser::parse_module() {
105 auto track = tracker();
106 Ptrs<Import> imports;
107 while (true) {
108 if (ahead().isa(Tag::K_import) || ahead().isa(Tag::K_plugin)) {
109 if (auto import = parse_import_or_plugin()) imports.emplace_back(std::move(import));
110 } else {
111 break;
112 }
113 }
114 auto decls = parse_decls();
115 bool where = ahead().isa(Tag::K_where);
116 expect(Tag::EoF, "module");
117 auto mod = ptr<Module>(track, std::move(imports), std::move(decls));
118 if (where) ast().note(mod->loc().anew_finis(), "did you accidentally end your declaration expression with a ';'?");
119 return mod;
120}
121
122Ptr<Module> Parser::import(Dbg dbg, std::ostream* md) {
123 auto name = dbg.sym();
124 auto filename = fs::path(name.view());
125 driver().VLOG("📥 import: {}", name);
126
127 if (!filename.has_extension()) filename.replace_extension("mim"); // TODO error cases
128
129 fs::path rel_path;
130 for (const auto& path : driver().search_paths()) {
131 std::error_code ignore;
132 rel_path = path / filename;
133 if (bool reg_file = fs::is_regular_file(rel_path, ignore); reg_file && !ignore) break;
134 rel_path = path / name.view() / filename;
135 if (bool reg_file = fs::is_regular_file(rel_path, ignore); reg_file && !ignore) break;
136 }
137
138 if (auto path = driver().imports().add(std::move(rel_path), name)) {
139 auto ifs = std::ifstream(*path);
140 return import(ifs, dbg.loc(), path, md);
141 }
142 return {};
143}
144
145Ptr<Module> Parser::import(std::istream& is, Loc loc, const fs::path* path, std::ostream* md) {
146 driver().VLOG("📄 reading: {}", path ? path->string() : "<unknown file>"s);
147 if (!is) {
148 ast().error(loc, "cannot read file {}", *path);
149 return {};
150 }
151
152 auto state = std::tuple(curr_, ahead_, lexer_);
153 auto lexer = Lexer(ast(), is, path, md);
154 lexer_ = &lexer;
155 init(path);
156 auto mod = parse_module();
157 std::tie(curr_, ahead_, lexer_) = state;
158 return mod;
159}
160
162 if (!driver().is_loaded(dbg.sym()) && !driver().flags().bootstrap) driver().load(dbg.sym());
163 return import(dbg);
164}
165
166/*
167 * misc
168 */
169
170Ptr<Import> Parser::parse_import_or_plugin() {
171 auto track = tracker();
172 auto tag = lex().tag();
173 auto name = expect(Tag::M_id, "{} name", tag == Tag::K_import ? "import" : "plugin");
174 auto dbg = name.dbg();
175 expect(Tag::T_semicolon, "end of {}", tag == Tag::K_import ? "import" : "plugin");
176 if (auto module = tag == Tag::K_import ? import(dbg) : plugin(dbg))
177 return ptr<Import>(track, tag, name.dbg(), std::move(module));
178 return {};
179}
180
181Dbg Parser::parse_id(std::string_view ctxt) {
182 if (auto id = accept(Tag::M_id)) return id.dbg();
183 syntax_err("identifier", ctxt);
184 return {curr_, driver().sym("<error>")};
185}
186
187Dbg Parser::parse_name(std::string_view ctxt) {
188 if (auto tok = accept(Tag::M_anx)) return tok.dbg();
189 if (auto tok = accept(Tag::M_id)) return tok.dbg();
190 syntax_err("identifier or annex name", ctxt);
191 return Dbg(curr_, ast().sym("<error>"));
192}
193
194Ptr<Expr> Parser::parse_type_ascr(std::string_view ctxt) {
195 if (accept(Tag::T_colon)) return parse_expr(ctxt);
196 if (ctxt.empty()) return nullptr;
197 syntax_err("':'", ctxt);
198 return ptr<ErrorExpr>(curr_);
199}
200
201/*
202 * exprs
203 */
204
205Ptr<Expr> Parser::parse_expr(std::string_view ctxt, Expr::Prec curr_prec) {
206 auto track = tracker();
207 auto lhs = parse_primary_expr(ctxt);
208 return parse_infix_expr(track, std::move(lhs), curr_prec);
209}
210
211Ptr<Expr> Parser::parse_infix_expr(Tracker track, Ptr<Expr>&& lhs, Expr::Prec curr_prec) {
212 while (true) {
213 // If operator in ahead has less left precedence: reduce (break).
214 switch (ahead().tag()) {
215 case Tag::T_extract: {
216 if (curr_prec >= Expr::Prec::Extract) return lhs;
217 lex();
218 if (auto tok = accept(Tag::M_id))
219 lhs = ptr<ExtractExpr>(track, std::move(lhs), tok.dbg());
220 else {
221 auto rhs = parse_expr("right-hand side of an extract", Expr::Prec::Extract);
222 lhs = ptr<ExtractExpr>(track, std::move(lhs), std::move(rhs));
223 }
224 continue;
225 }
226 case Tag::T_arrow: {
227 if (curr_prec > Expr::Prec::Arrow) return lhs; // ">" - Arrow is rassoc
228 lex();
229 auto rhs = parse_expr("right-hand side of a function type", Expr::Prec::Arrow);
230 lhs = ptr<ArrowExpr>(track, std::move(lhs), std::move(rhs));
231 continue;
232 }
233 case Tag::T_union: {
234 if (curr_prec >= Expr::Prec::Union) return lhs;
235 lex();
236 Ptrs<Expr> types;
237 types.emplace_back(std::move(lhs));
238 do {
239 auto t = parse_expr("right-hand side of a union type", Expr::Prec::Union);
240 types.emplace_back(std::move(t));
241 } while (accept(Tag::T_union));
242 lhs = ptr<UnionExpr>(track, std::move(types));
243 continue;
244 }
245 case Tag::K_inj: {
246 if (curr_prec > Expr::Prec::Inj) return lhs;
247 lex();
248 auto rhs = parse_expr("type a value is injected in", Expr::Prec::Inj);
249 lhs = ptr<InjExpr>(track, std::move(lhs), std::move(rhs));
250 continue;
251 }
252 case Tag::T_at: {
253 if (curr_prec >= Expr::Prec::App) return lhs;
254 lex();
255 auto rhs = parse_expr("explicit argument to an application", Expr::Prec::App);
256 lhs = ptr<AppExpr>(track, true, std::move(lhs), std::move(rhs));
257 continue;
258 }
259 case Tag::C_EXPR: {
260 if (curr_prec >= Expr::Prec::App) return lhs;
261 switch (ahead().tag()) {
262 case Tag::C_DECL:
263 ast().warn(ahead().loc(), "you are passing a declaration expression as argument");
264 ast().note(lhs->loc(), "to this expression");
265 ast().note(ahead().loc(),
266 "if this was your intention, consider to parenthesize the declaration expression");
267 ast().note(lhs->loc().anew_finis(), "otherwise, you are probably missing a ';'");
268 default: break;
269 }
270 auto rhs = parse_expr("argument to an application", Expr::Prec::App);
271 lhs = ptr<AppExpr>(track, false, std::move(lhs), std::move(rhs));
272 continue;
273 }
274 case Tag::K_where: {
275 if (curr_prec >= Expr::Prec::Where) return lhs;
276 lex();
277 auto decls = parse_decls();
278 lhs = ptr<DeclExpr>(track, std::move(decls), std::move(lhs), true);
279
280 bool where = ahead().tag() == Tag::K_where;
281 expect(Tag::K_end, "end of a where declaration block");
282 if (where)
283 ast().note(lhs->loc().anew_finis(),
284 "did you accidentally end your declaration expression with a ';'?");
285 return lhs;
286 }
287 default: return lhs;
288 }
289 }
290}
291
292Ptr<Expr> Parser::parse_insert_expr() {
293 eat(Tag::K_ins);
294 auto track = tracker();
295 expect(Tag::D_paren_l, "opening paren for insert arguments");
296 auto tuple = parse_expr("the tuple to insert into");
297 expect(Tag::T_comma, "comma after tuple to insert into");
298 auto index = parse_expr("insert index");
299 expect(Tag::T_comma, "comma after insert index");
300 auto value = parse_expr("insert value");
301 expect(Tag::D_paren_r, "closing paren for insert arguments");
302 return ptr<InsertExpr>(track, std::move(tuple), std::move(index), std::move(value));
303}
304
305Ptr<Expr> Parser::parse_uniq_expr() {
306 auto track = tracker();
307 expect(Tag::D_curly_l, "opening curly bracket for singleton type");
308 auto inhabitant = parse_expr("singleton type");
309 expect(Tag::D_curly_r, "closing curly bracket for singleton type");
310 return ptr<UniqExpr>(track, std::move(inhabitant));
311}
312
313Ptr<Expr> Parser::parse_match_expr() {
314 auto track = tracker();
315 expect(Tag::K_match, "opening match for union destruction");
316 auto scrutinee = parse_expr("destroyed union element");
317 expect(Tag::K_with, "match");
319 accept(Tag::T_pipe);
320 do {
321 auto track = tracker();
322 auto ptrn = parse_ptrn(Paren_Style, "right-hand side of a match-arm", Expr::Prec::Bot);
323 expect(Tag::T_fat_arrow, "arm of a match-expression");
324 auto body = parse_expr("arm of a match-expression");
325 arms.emplace_back(ptr<MatchExpr::Arm>(track, std::move(ptrn), std::move(body)));
326 } while (accept(Tag::T_pipe));
327
328 return ptr<MatchExpr>(track, std::move(scrutinee), std::move(arms));
329}
330
331Ptr<Expr> Parser::parse_primary_expr(std::string_view ctxt) {
332 // clang-format off
333 switch (ahead().tag()) {
334 case Tag::C_PRIMARY: return ptr<PrimaryExpr>(lex());
335 case Tag::C_ID: return ptr<IdExpr>(lex().dbg());
336 case Tag::C_LIT: return parse_lit_expr();
337 case Tag::C_DECL: return parse_decl_expr();
338 case Tag::C_PI: return parse_pi_expr();
339 case Tag::C_LM: return parse_lam_expr();
340 case Tag::K_ins: return parse_insert_expr();
341 case Tag::K_ret: return parse_ret_expr();
342 case Tag::D_curly_l: return parse_uniq_expr();
343 case Tag::D_quote_l:
344 case Tag::D_angle_l: return parse_seq_expr();
345 case Tag::D_brckt_l: return parse_sigma_expr();
346 case Tag::D_paren_l: return parse_tuple_expr();
347 case Tag::K_Type: return parse_type_expr();
348 case Tag::K_match: return parse_match_expr();
349 default:
350 if (ctxt.empty()) return nullptr;
351 syntax_err("primary expression", ctxt);
352 }
353 // clang-format on
354 return ptr<ErrorExpr>(curr_);
355}
356
357Ptr<Expr> Parser::parse_seq_expr() {
358 auto track = tracker();
359 bool is_arr = accept(Tag::D_quote_l) ? true : (eat(Tag::D_angle_l), false);
360
361 std::deque<std::pair<Ptr<IdPtrn>, Ptr<Expr>>> arities;
362
363 do {
364 Dbg dbg;
365 if (ahead(0).isa(Tag::M_id) && ahead(1).isa(Tag::T_colon)) {
366 dbg = eat(Tag::M_id).dbg();
367 eat(Tag::T_colon);
368 }
369
370 auto expr = parse_expr(is_arr ? "shape of an array" : "shape of a pack");
371 auto ptrn = IdPtrn::make_id(ast(), dbg, std::move(expr));
372 arities.emplace_back(std::move(ptrn), std::move(expr));
373 } while (accept(Tag::T_comma));
374
375 expect(Tag::T_semicolon, is_arr ? "array" : "pack");
376 auto body = parse_expr(is_arr ? "body of an array" : "body of a pack");
377 expect(is_arr ? Tag::D_quote_r : Tag::D_angle_r,
378 is_arr ? "closing delimiter of an array" : "closing delimiter of a pack");
379
380 for (auto& [ptrn, expr] : arities | std::ranges::views::reverse)
381 body = ptr<SeqExpr>(track, is_arr, std::move(ptrn), std::move(body));
382
383 return body;
384}
385
386Ptr<Expr> Parser::parse_decl_expr() {
387 auto track = tracker();
388 auto decls = parse_decls();
389 auto expr = parse_expr("final expression of a declaration expression");
390 return ptr<DeclExpr>(track, std::move(decls), std::move(expr), false);
391}
392
393Ptr<Expr> Parser::parse_lit_expr() {
394 auto track = tracker();
395 auto tok = lex();
396 auto type = accept(Tag::T_colon) ? parse_expr("literal", Expr::Prec::Lit) : nullptr;
397 return ptr<LitExpr>(track, tok, std::move(type));
398}
399
400Ptr<Expr> Parser::parse_sigma_expr() {
401 auto track = tracker();
402 auto ptrn = parse_tuple_ptrn(Brckt_Style);
403 switch (ahead().tag()) {
404 case Tag::K_as: {
405 lex();
406 auto alias = ptr<AliasPtrn>(track, std::move(ptrn), parse_name("alias pattern"));
407 return parse_pi_expr(std::move(alias));
408 }
409 case Tag::C_CURRIED_B:
410 case Tag::T_arrow: return parse_pi_expr(std::move(ptrn)); // TODO precedences for patterns
411 default: return ptr<SigmaExpr>(std::move(ptrn));
412 }
413}
414
415Ptr<Expr> Parser::parse_tuple_expr() {
416 auto track = tracker();
417 Ptrs<Expr> elems;
418 parse_list("tuple", Tag::D_paren_l, [&]() { elems.emplace_back(parse_expr("tuple element")); });
419 return ptr<TupleExpr>(track, std::move(elems));
420}
421
422Ptr<Expr> Parser::parse_type_expr() {
423 auto track = tracker();
424 eat(Tag::K_Type);
425 auto level = parse_expr("type level", Expr::Prec::App);
426 return ptr<TypeExpr>(track, std::move(level));
427}
428
429Ptr<Expr> Parser::parse_pi_expr() {
430 auto track = tracker();
431 auto tag = ahead().tag();
432 auto entity = "dependent function type"s;
433
434 if (accept(Tag::K_Cn))
435 entity = "continuation type";
436 else if (accept(Tag::K_Fn))
437 entity = "returning continuation type";
438
439 auto domt = tracker();
440 auto prec = tag == Tag::K_Cn ? Expr::Prec::Bot : Expr::Prec::Pi;
441 auto ptrn = parse_ptrn(Brckt_Style | Implicit, "domain of a "s + entity, prec);
442 auto dom = ptr<PiExpr::Dom>(domt, std::move(ptrn));
443
444 auto codom = tag != Tag::K_Cn
445 ? (expect(Tag::T_arrow, entity), parse_expr("codomain of a "s + entity, Expr::Prec::Arrow))
446 : nullptr;
447
448 if (tag == Tag::K_Fn) dom->add_ret(ast(), codom ? std::move(codom) : ptr<HoleExpr>(curr_));
449 return ptr<PiExpr>(track, tag, std::move(dom), std::move(codom));
450}
451
452Ptr<Expr> Parser::parse_pi_expr(Ptr<Ptrn>&& ptrn) {
453 auto track = tracker(ptrn->loc());
454 auto entity = "dependent function type"s;
455 auto dom = ptr<PiExpr::Dom>(ptrn->loc(), std::move(ptrn));
456 expect(Tag::T_arrow, entity);
457 auto codom = parse_expr("codomain of a "s + entity, Expr::Prec::Arrow);
458 return ptr<PiExpr>(track, Tag::Nil, std::move(dom), std::move(codom));
459}
460
461Ptr<Expr> Parser::parse_lam_expr() { return ptr<LamExpr>(parse_lam_decl()); }
462
463Ptr<Expr> Parser::parse_ret_expr() {
464 auto track = tracker();
465 eat(Tag::K_ret);
466 auto ptrn = parse_ptrn(Paren_Style, "binding pattern of a ret expression");
467 expect(Tag::T_assign, "ret expression");
468 auto callee = parse_expr("continuation expression of a ret expression");
469 expect(Tag::T_dollar, "separator of a ret expression");
470 auto arg = parse_expr("argument of ret expression");
471 expect(Tag::T_semicolon, "ret expression");
472 auto body = parse_expr("body of a ret expression");
473 return ptr<RetExpr>(track, std::move(ptrn), std::move(callee), std::move(arg), std::move(body));
474}
475
476/*
477 * ptrns
478 */
479
480Ptr<Ptrn> Parser::parse_ptrn(int style, std::string_view ctxt, Expr::Prec prec) {
481 auto track = tracker();
482 auto ptrn = parse_ptrn_(style, ctxt, prec);
483 if (accept(Tag::K_as)) return ptr<AliasPtrn>(track, std::move(ptrn), parse_name("alias pattern"));
484 return ptrn;
485}
486
487Ptr<Ptrn> Parser::parse_ptrn_(int style, std::string_view ctxt, Expr::Prec prec) {
488 auto track = tracker();
489
490 // p -> (p, ..., p)
491 // p -> {b, ..., b} b -> {b, ..., b}
492 // p -> [b, ..., b] b -> [b, ..., b]
493 if (is_paren_style(style) && ahead().isa(Tag::D_paren_l)) return parse_tuple_ptrn(style);
494 if (is_implicit(style) && ahead().isa(Tag::D_brace_l)) return parse_tuple_ptrn(style);
495 if (ahead().isa(Tag::D_brckt_l)) return parse_tuple_ptrn(Brckt_Style);
496
497 if (ahead(0).isa(Tag::M_id)) {
498 if (ahead(1).isa(Tag::T_colon)) {
499 // p -> s: e b -> s: e
500 auto dbg = eat(Tag::M_id).dbg();
501 eat(Tag::T_colon);
502 auto type = parse_expr(ctxt, prec);
503 return ptr<IdPtrn>(track, dbg, std::move(type));
504 } else if (is_paren_style(style)) {
505 // p -> s
506 auto dbg = eat(Tag::M_id).dbg();
507 return ptr<IdPtrn>(track, dbg, nullptr);
508 } else {
509 // b -> e where e == id
510 auto type = parse_expr(ctxt, prec);
511 return ptr<IdPtrn>(track, type->loc().anew_begin(), std::move(type));
512 }
513 } else if (is_brket_style(style)) {
514 // b -> e where e != id
515 auto type = parse_expr(ctxt, prec);
516 auto loc = type->loc().anew_begin();
517 return ptr<IdPtrn>(track, Dbg(loc), std::move(type));
518 } else if (!ctxt.empty()) {
519 // p -> ↯
520 syntax_err("pattern", ctxt);
521 return ptr<ErrorPtrn>(curr_);
522 }
523
524 return nullptr;
525}
526
527Ptr<TuplePtrn> Parser::parse_tuple_ptrn(int style) {
528 auto track = tracker();
529 auto delim_l = ahead().tag();
530
531 Ptrs<Ptrn> ptrns;
532 parse_list("tuple pattern", delim_l, [&]() {
533 auto track = tracker();
534 Ptr<Ptrn> ptrn;
535
536 if (ahead(0).isa(Tag::M_id) && ahead(1).isa(Tag::M_id)) {
537 Dbgs dbgs;
538 while (auto tok = accept(Tag::M_id))
539 dbgs.emplace_back(tok.dbg());
540
541 if (accept(Tag::T_colon)) { // identifier group: x y x: T
542 auto dbg = dbgs.back();
543 auto type = parse_expr("type of an identifier group within a tuple pattern");
544 auto id = ptr<IdPtrn>(dbg.loc() + type->loc().finis, dbg, std::move(type));
545
546 for (auto dbg : dbgs | std::views::take(dbgs.size() - 1))
547 ptrns.emplace_back(ptr<GrpPtrn>(dbg, id.get()));
548 ptrns.emplace_back(std::move(id));
549 return;
550 }
551
552 // "x y z" is a curried app and maybe the prefix of a longer type expression
553 Ptr<Expr> lhs = ptr<IdExpr>(dbgs.front());
554 for (auto dbg : dbgs | std::views::drop(1)) {
555 auto rhs = ptr<IdExpr>(dbg);
556 lhs = ptr<AppExpr>(track, false, std::move(lhs), std::move(rhs));
557 }
558 auto expr = parse_infix_expr(track, std::move(lhs), Expr::Prec::App);
559 ptrn = IdPtrn::make_type(ast(), std::move(expr));
560 } else {
561 ptrn = parse_ptrn(style & Style_Bit, "element of a tuple pattern");
562
563 if (is_brket_style(style)) {
564 // [..., [Nat, Nat] -> Nat, ...] ==> [..., _: [Nat, Nat] -> Nat, ...]
565 if (ahead().isa(Tag::T_arrow)) {
566 auto loc = ptrn->loc();
567 auto expr = parse_pi_expr(std::move(ptrn));
568 ptrn = ptr<IdPtrn>(loc, Dbg(loc.anew_begin(), Sym()), std::move(expr));
569 } else if (auto expr = Ptrn::to_expr(ast(), std::move(ptrn))) {
570 // If we are able to parse more stuff, we got an expr instead of a binder
571 auto addr = expr.get();
572 expr = parse_infix_expr(track, std::move(expr));
573 if (expr.get() != addr) {
574 auto loc = expr->loc();
575 ptrn = ptr<IdPtrn>(loc, Dbg(loc.anew_begin(), Sym()), std::move(expr));
576 } else {
577 if (!ptrn) ptrn = Ptrn::to_ptrn(std::move(expr));
578 }
579 }
580 }
581 }
582
583 ptrns.emplace_back(std::move(ptrn));
584 });
585
586 return ptr<TuplePtrn>(track, delim_l, std::move(ptrns));
587}
588
589/*
590 * decls
591 */
592
593Ptrs<ValDecl> Parser::parse_decls() {
594 Ptrs<ValDecl> decls;
595 while (true) {
596 // clang-format off
597 switch (ahead().tag()) {
598 case Tag::T_semicolon: lex(); break; // eat up stray semicolons
599 case Tag::K_axm: decls.emplace_back(parse_axm_decl()); break;
600 case Tag::K_ccon:
601 case Tag::K_cfun: decls.emplace_back(parse_c_decl()); break;
602 case Tag::K_let: decls.emplace_back(parse_let_decl()); break;
603 case Tag::K_rec: decls.emplace_back(parse_rec_decl(true)); break;
604 case Tag::K_con:
605 case Tag::K_fun:
606 case Tag::K_lam: decls.emplace_back(parse_lam_decl()); break;
607 case Tag::K_norm:
608 case Tag::K_rule: decls.emplace_back(parse_rule_decl()); break;
609 default: return decls;
610 }
611 // clang-format on
612 }
613}
614
615Ptr<ValDecl> Parser::parse_axm_decl() {
616 auto track = tracker();
617 eat(Tag::K_axm);
618 Dbg dbg, normalizer;
619 Tok curry, trip;
620 if (auto name = expect(Tag::M_anx, "annex name of an axm"))
621 dbg = name.dbg();
622 else
623 dbg = Dbg(curr_, ast().sym("<error annex name>"));
624
625 std::deque<Ptrs<AxmDecl::Alias>> subs;
626 if (ahead().isa(Tag::D_paren_l)) {
627 parse_list("tag list of an axm", Tag::D_paren_l, [&]() {
628 auto& aliases = subs.emplace_back();
629 aliases.emplace_back(ptr<AxmDecl::Alias>(parse_id("tag of an axm")));
630 while (accept(Tag::T_assign))
631 aliases.emplace_back(ptr<AxmDecl::Alias>(parse_id("alias of an axm tag")));
632 });
633 }
634
635 auto type = parse_type_ascr("type ascription of an axm");
636
637 if (ahead(0).isa(Tag::T_comma) && ahead(1).isa(Tag::M_id)) {
638 lex();
639 normalizer = lex().dbg();
640 }
641 if (accept(Tag::T_comma)) {
642 if (auto c = expect(Tag::L_u, "curry counter for axm")) curry = c;
643 if (accept(Tag::T_comma)) {
644 if (auto t = expect(Tag::L_u, "trip count for axm")) trip = t;
645 }
646 }
647
648 return ptr<AxmDecl>(track, dbg, std::move(subs), std::move(type), normalizer, curry, trip);
649}
650
651Ptr<ValDecl> Parser::parse_let_decl() {
652 auto track = tracker();
653 eat(Tag::K_let);
654
655 Ptr<Ptrn> ptrn;
656 if (auto anx = accept(Tok::Tag::M_anx)) {
657 auto type = parse_type_ascr();
658 ptrn = ptr<IdPtrn>(track, anx.dbg(), std::move(type));
659 } else {
660 ptrn = parse_ptrn(Paren_Style, "binding pattern of a let declaration", Expr::Prec::Bot);
661 }
662
663 expect(Tag::T_assign, "let");
664 auto type = parse_type_ascr();
665 auto value = parse_expr("value of a let declaration");
666 return ptr<LetDecl>(track, std::move(ptrn), std::move(value));
667}
668
669Ptr<ValDecl> Parser::parse_c_decl() {
670 auto track = tracker();
671 auto tag = lex().tag();
672 auto id = expect(Tag::M_id, "C function declaration");
673 auto dom = parse_ptrn(Brckt_Style, "domain of a C function"s, Expr::Prec::App);
674 Ptr<Expr> codom;
675 if (tag == Tag::K_cfun) {
676 expect(Tag::T_colon, "codomain of a C function");
677 codom = parse_expr("codomain of a C function");
678 }
679 return ptr<CDecl>(track, tag, id.dbg(), std::move(dom), std::move(codom));
680}
681
682Ptr<RecDecl> Parser::parse_rec_decl(bool first) {
683 auto track = tracker();
684 eat(first ? Tag::K_rec : Tag::K_and);
685 auto dbg = parse_name("recursive declaration");
686 auto type = accept(Tag::T_colon) ? parse_expr("type of a recursive declaration") : ptr<HoleExpr>(curr_);
687 expect(Tag::T_assign, "recursive declaration");
688 auto body = parse_expr("body of a recursive declaration");
689 auto next = ahead().isa(Tag::K_and) ? parse_and_decl() : nullptr;
690 return ptr<RecDecl>(track, dbg, std::move(type), std::move(body), std::move(next));
691}
692
693Ptr<ValDecl> Parser::parse_rule_decl() {
694 auto track = tracker();
695 auto is_norm = lex().tag() == Tag::K_norm;
696 auto dbg = parse_name("rewrite rule");
697 auto ptrn = parse_ptrn(0, "meta variables in rewrite rule");
698 expect(Tag::T_colon, "rewrite rule declaration");
699 auto lhs = parse_expr("rewrite pattern");
700 auto guard = ahead().isa(Tag::K_when) ? (eat(Tag::K_when), parse_expr("rewrite guard"))
701 : ptr<PrimaryExpr>(track, std::move(Tag::K_tt));
702 expect(Tag::T_fat_arrow, "rewrite rule declaration");
703 auto rhs = parse_expr("rewrite result");
704 return ptr<RuleDecl>(track, dbg, std::move(ptrn), std::move(lhs), std::move(rhs), std::move(guard), is_norm);
705}
706
707Ptr<LamDecl> Parser::parse_lam_decl() {
708 auto track = tracker();
709 auto tag = lex().tag();
710 auto prec = tag == Tag::K_cn || tag == Tag::K_con ? Expr::Prec::Bot : Expr::Prec::Pi;
711 bool external = (bool)accept(Tag::K_extern);
712
713 bool decl;
714 std::string entity;
715 // clang-format off
716 switch (tag) {
717 case Tag::T_lm: decl = false; entity = "function expression"; break;
718 case Tag::K_cn: decl = false; entity = "continuation expression"; break;
719 case Tag::K_fn: decl = false; entity = "returning continuation expression"; break;
720 case Tag::K_lam: decl = true ; entity = "function declaration"; break;
721 case Tag::K_con: decl = true ; entity = "continuation declaration"; break;
722 case Tag::K_fun: decl = true ; entity = "returning continuation declaration"; break;
723 default: fe::unreachable();
724 }
725 // clang-format on
726
727 auto dbg = decl ? parse_name(entity) : Dbg();
729 while (true) {
730 auto track = tracker();
731 auto ptrn = parse_ptrn(Paren_Style | Implicit, "domain pattern of a "s + entity, prec);
732 auto filter = accept(Tag::T_at) ? parse_expr("filter") : nullptr;
733 doms.emplace_back(ptr<LamDecl::Dom>(track, std::move(ptrn), std::move(filter)));
734
735 switch (ahead().tag()) {
736 case Tag::C_CURRIED_P: continue;
737 default: break;
738 }
739 break;
740 }
741
742 auto codom = accept(Tag::T_colon) ? parse_expr("codomain of a "s + entity, Expr::Prec::Arrow) : nullptr;
743 if (tag == Tag::K_fn || tag == Tag::K_fun)
744 doms.back()->add_ret(ast(), codom ? std::move(codom) : ptr<HoleExpr>(curr_));
745
746 expect(Tag::T_assign, "body of a "s + entity);
747 auto body = parse_expr("body of a "s + entity);
748 auto next = ahead().isa(Tag::K_and) ? parse_and_decl() : nullptr;
749
750 return ptr<LamDecl>(track, tag, external, dbg, std::move(doms), std::move(codom), std::move(body), std::move(next));
751}
752
753Ptr<RecDecl> Parser::parse_and_decl() {
754 switch (ahead(1).tag()) {
755 case Tag::C_LAM: return lex(), parse_lam_decl();
756 default: return parse_rec_decl(false);
757 }
758}
759
760} // namespace mim::ast
void load(Sym name)
Definition driver.cpp:50
Error & note(Loc loc, const char *fmt, Args &&... args) const
Definition ast.h:87
Error & error()
Definition ast.h:63
Error & warn(Loc loc, const char *fmt, Args &&... args) const
Definition ast.h:86
static Ptr< IdPtrn > make_type(AST &ast, Ptr< Expr > &&type)
Definition ast.h:227
static Ptr< IdPtrn > make_id(AST &ast, Dbg dbg, Ptr< Expr > &&type)
Definition ast.h:231
Ptr< Module > import(std::string_view sv)
Definition parser.h:39
AST & ast()
Definition parser.h:37
Driver & driver()
Definition parser.h:38
Ptr< Module > plugin(Dbg)
Definition parser.cpp:161
static Ptr< Ptrn > to_ptrn(Ptr< Expr > &&)
Definition ast.cpp:179
static Ptr< Expr > to_expr(AST &, Ptr< Ptrn > &&)
Definition ast.cpp:169
Definition ast.h:14
std::deque< Dbg > Dbgs
Definition ast.h:25
fe::Arena::Ptr< const T > Ptr
Definition ast.h:22
std::deque< Ptr< T > > Ptrs
Definition ast.h:24
Tok::Tag Tag
Definition bind.cpp:7
constexpr decltype(auto) get(Span< T, N > span) noexcept
Definition span.h:115