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