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, Tok::Tag tag) {
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, fresh] = driver().imports().add(std::move(rel_path), name, tag); fresh) {
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, nullptr, Tag::K_plugin);
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, 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, 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 (should_reduce(curr_prec, 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", Prec::Extract);
223 lhs = ptr<ExtractExpr>(track, std::move(lhs), std::move(rhs));
224 }
225 continue;
226 }
227 case Tag::T_arrow: {
228 if (should_reduce(curr_prec, Prec::Arrow)) return lhs;
229 lex();
230 auto rhs = parse_expr("right-hand side of a function type", Prec::Arrow);
231 lhs = ptr<ArrowExpr>(track, std::move(lhs), std::move(rhs));
232 continue;
233 }
234 case Tag::T_union: {
235 if (should_reduce(curr_prec, 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", 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 (should_reduce(curr_prec, Prec::Inj)) return lhs;
248 lex();
249 auto rhs = parse_expr("type a value is injected in", Prec::Inj);
250 lhs = ptr<InjExpr>(track, std::move(lhs), std::move(rhs));
251 continue;
252 }
253 case Tag::T_at: {
254 if (should_reduce(curr_prec, Prec::App)) return lhs;
255 lex();
256 auto rhs = parse_expr("explicit argument to an application", Prec::App);
257 lhs = ptr<AppExpr>(track, true, std::move(lhs), std::move(rhs));
258 continue;
259 }
260 case Tag::C_EXPR: {
261 if (should_reduce(curr_prec, 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", Prec::App);
272 lhs = ptr<AppExpr>(track, false, std::move(lhs), std::move(rhs));
273 continue;
274 }
275 case Tag::K_where: {
276 if (should_reduce(curr_prec, 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", 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_pack = accept(Tag::D_angle_l) ? true : (eat(Tag::D_quote_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_pack ? "shape of pack" : "shape of a array");
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_pack ? "pack" : "array");
378 auto body = parse_expr(is_pack ? "body of a pack" : "body of an array");
379 expect(is_pack ? Tag::D_angle_r : Tag::D_quote_r,
380 is_pack ? "closing delimiter of a pack" : "closing delimiter of an array");
381
382 for (auto& [ptrn, expr] : arities | std::ranges::views::reverse)
383 body = ptr<SeqExpr>(track, is_pack, 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", 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();
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", 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", 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 ? Prec::Bot : 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 ? (expect(Tag::T_arrow, entity), parse_expr("codomain of a "s + entity, Prec::Arrow))
454 : nullptr;
455
456 if (tag == Tag::K_Fn) dom->add_ret(ast(), codom ? std::move(codom) : ptr<HoleExpr>(curr_));
457 return ptr<PiExpr>(track, tag, std::move(dom), std::move(codom));
458}
459
460Ptr<Expr> Parser::parse_pi_expr(Ptr<Ptrn>&& ptrn) {
461 auto track = tracker(ptrn->loc());
462 auto entity = "dependent function type"s;
463 auto dom = ptr<PiExpr::Dom>(ptrn->loc(), std::move(ptrn));
464 expect(Tag::T_arrow, entity);
465 auto codom = parse_expr("codomain of a "s + entity, Prec::Arrow);
466 return ptr<PiExpr>(track, Tag::Nil, std::move(dom), std::move(codom));
467}
468
469Ptr<Expr> Parser::parse_lam_expr() { return ptr<LamExpr>(parse_lam_decl()); }
470
471Ptr<Expr> Parser::parse_ret_expr() {
472 auto track = tracker();
473 eat(Tag::K_ret);
474 auto ptrn = parse_ptrn(Paren_Style, "binding pattern of a ret expression");
475 expect(Tag::T_assign, "ret expression");
476 auto callee = parse_expr("continuation expression of a ret expression");
477 expect(Tag::T_dollar, "separator of a ret expression");
478 auto arg = parse_expr("argument of ret expression");
479 expect(Tag::T_semicolon, "ret expression");
480 auto body = parse_expr("body of a ret expression");
481 return ptr<RetExpr>(track, std::move(ptrn), std::move(callee), std::move(arg), std::move(body));
482}
483
484/*
485 * ptrns
486 */
487
488Ptr<Ptrn> Parser::parse_ptrn(int style, std::string_view ctxt, Prec prec) {
489 auto track = tracker();
490 auto ptrn = parse_ptrn_(style, ctxt, prec);
491 if (accept(Tag::K_as)) return ptr<AliasPtrn>(track, std::move(ptrn), parse_name("alias pattern"));
492 return ptrn;
493}
494
495Ptr<Ptrn> Parser::parse_ptrn_(int style, std::string_view ctxt, Prec prec) {
496 auto track = tracker();
497
498 // p -> (p, ..., p)
499 // p -> {b, ..., b} b -> {b, ..., b}
500 // p -> [b, ..., b] b -> [b, ..., b]
501 if (is_paren_style(style) && ahead().isa(Tag::D_paren_l)) return parse_tuple_ptrn(style);
502 if (is_implicit(style) && ahead().isa(Tag::D_brace_l)) return parse_tuple_ptrn(style);
503 if (ahead().isa(Tag::D_brckt_l)) return parse_tuple_ptrn(Brckt_Style);
504
505 if (ahead(0).isa(Tag::M_id)) {
506 if (ahead(1).isa(Tag::T_colon)) {
507 // p -> s: e b -> s: e
508 auto dbg = eat(Tag::M_id).dbg();
509 eat(Tag::T_colon);
510 auto type = parse_expr(ctxt, prec);
511 return ptr<IdPtrn>(track, dbg, std::move(type));
512 } else if (is_paren_style(style)) {
513 // p -> s
514 auto dbg = eat(Tag::M_id).dbg();
515 return ptr<IdPtrn>(track, dbg, nullptr);
516 } else {
517 // b -> e where e == id
518 auto type = parse_expr(ctxt, prec);
519 return ptr<IdPtrn>(track, type->loc().anew_begin(), std::move(type));
520 }
521 } else if (is_brket_style(style)) {
522 // b -> e where e != id
523 auto type = parse_expr(ctxt, prec);
524 auto loc = type->loc().anew_begin();
525 return ptr<IdPtrn>(track, Dbg(loc), std::move(type));
526 } else if (!ctxt.empty()) {
527 // p -> ↯
528 syntax_err("pattern", ctxt);
529 return ptr<ErrorPtrn>(curr_);
530 }
531
532 return nullptr;
533}
534
535Ptr<TuplePtrn> Parser::parse_tuple_ptrn(int style) {
536 auto track = tracker();
537 auto delim_l = ahead().tag();
538
539 Ptrs<Ptrn> ptrns;
540 parse_list("tuple pattern", delim_l, [&]() {
541 auto track = tracker();
542 Ptr<Ptrn> ptrn;
543
544 if (ahead(0).isa(Tag::M_id) && ahead(1).isa(Tag::M_id)) {
545 Dbgs dbgs;
546 while (auto tok = accept(Tag::M_id))
547 dbgs.emplace_back(tok.dbg());
548
549 if (accept(Tag::T_colon)) { // identifier group: x y x: T
550 auto dbg = dbgs.back();
551 auto type = parse_expr("type of an identifier group within a tuple pattern");
552 auto id = ptr<IdPtrn>(dbg.loc() + type->loc().finis, dbg, std::move(type));
553
554 for (auto dbg : dbgs | std::views::take(dbgs.size() - 1))
555 ptrns.emplace_back(ptr<GrpPtrn>(dbg, id.get()));
556 ptrns.emplace_back(std::move(id));
557 return;
558 }
559
560 // "x y z" is a curried app and maybe the prefix of a longer type expression
561 Ptr<Expr> lhs = ptr<IdExpr>(dbgs.front());
562 for (auto dbg : dbgs | std::views::drop(1)) {
563 auto rhs = ptr<IdExpr>(dbg);
564 lhs = ptr<AppExpr>(track, false, std::move(lhs), std::move(rhs));
565 }
566 auto expr = parse_infix_expr(track, std::move(lhs), Prec::App);
567 ptrn = IdPtrn::make_type(ast(), std::move(expr));
568 } else {
569 ptrn = parse_ptrn(style & Style_Bit, "element of a tuple pattern");
570
571 if (is_brket_style(style)) {
572 // [..., [Nat, Nat] -> Nat, ...] ==> [..., _: [Nat, Nat] -> Nat, ...]
573 if (ahead().isa(Tag::T_arrow)) {
574 auto loc = ptrn->loc();
575 auto expr = parse_pi_expr(std::move(ptrn));
576 ptrn = ptr<IdPtrn>(loc, Dbg(loc.anew_begin(), Sym()), std::move(expr));
577 } else if (auto expr = Ptrn::to_expr(ast(), std::move(ptrn))) {
578 // If we are able to parse more stuff, we got an expr instead of a binder
579 auto addr = expr.get();
580 expr = parse_infix_expr(track, std::move(expr));
581 if (expr.get() != addr) {
582 auto loc = expr->loc();
583 ptrn = ptr<IdPtrn>(loc, Dbg(loc.anew_begin(), Sym()), std::move(expr));
584 } else {
585 if (!ptrn) ptrn = Ptrn::to_ptrn(std::move(expr));
586 }
587 }
588 }
589 }
590
591 ptrns.emplace_back(std::move(ptrn));
592 });
593
594 return ptr<TuplePtrn>(track, delim_l, std::move(ptrns));
595}
596
597/*
598 * decls
599 */
600
601Ptrs<ValDecl> Parser::parse_decls() {
602 Ptrs<ValDecl> decls;
603 while (true) {
604 // clang-format off
605 switch (ahead().tag()) {
606 case Tag::T_semicolon: lex(); break; // eat up stray semicolons
607 case Tag::K_axm: decls.emplace_back(parse_axm_decl()); break;
608 case Tag::K_ccon:
609 case Tag::K_cfun: decls.emplace_back(parse_c_decl()); break;
610 case Tag::K_let: decls.emplace_back(parse_let_decl()); break;
611 case Tag::K_rec: decls.emplace_back(parse_rec_decl(true)); break;
612 case Tag::K_con:
613 case Tag::K_fun:
614 case Tag::K_lam: decls.emplace_back(parse_lam_decl()); break;
615 case Tag::K_norm:
616 case Tag::K_rule: decls.emplace_back(parse_rule_decl()); break;
617 default: return decls;
618 }
619 // clang-format on
620 }
621}
622
623Ptr<ValDecl> Parser::parse_axm_decl() {
624 auto track = tracker();
625 eat(Tag::K_axm);
626 Dbg dbg, normalizer;
627 Tok curry, trip;
628 // TODO if we check this later, we also have to report this error later
629 if (auto name = expect(Tag::M_anx, "annex name of an axm"))
630 dbg = name.dbg();
631 else {
632 accept(Tag::M_id);
633 dbg = Dbg(curr_, ast().sym("<error annex name>"));
634 }
635
636 std::deque<Ptrs<AxmDecl::Alias>> subs;
637 if (ahead().isa(Tag::D_paren_l)) {
638 parse_list("tag list of an axm", Tag::D_paren_l, [&]() {
639 auto& aliases = subs.emplace_back();
640 aliases.emplace_back(ptr<AxmDecl::Alias>(parse_id("tag of an axm")));
641 while (accept(Tag::T_assign))
642 aliases.emplace_back(ptr<AxmDecl::Alias>(parse_id("alias of an axm tag")));
643 });
644 }
645
646 auto type = parse_type_ascr("type ascription of an axm");
647
648 if (ahead(0).isa(Tag::T_comma) && ahead(1).isa(Tag::M_id)) {
649 lex();
650 normalizer = lex().dbg();
651 }
652 if (accept(Tag::T_comma)) {
653 if (auto c = expect(Tag::L_u, "curry counter for axm")) curry = c;
654 if (accept(Tag::T_comma)) {
655 if (auto t = expect(Tag::L_u, "trip count for axm")) trip = t;
656 }
657 }
658
659 return ptr<AxmDecl>(track, dbg, std::move(subs), std::move(type), normalizer, curry, trip);
660}
661
662Ptr<ValDecl> Parser::parse_let_decl() {
663 auto track = tracker();
664 eat(Tag::K_let);
665
666 Ptr<Ptrn> ptrn;
667 if (auto anx = accept(Tok::Tag::M_anx)) {
668 auto type = parse_type_ascr();
669 ptrn = ptr<IdPtrn>(track, anx.dbg(), std::move(type));
670 } else {
671 ptrn = parse_ptrn(Paren_Style, "binding pattern of a let declaration", Prec::Bot);
672 }
673
674 expect(Tag::T_assign, "let");
675 auto type = parse_type_ascr();
676 auto value = parse_expr("value of a let declaration");
677 return ptr<LetDecl>(track, std::move(ptrn), std::move(value));
678}
679
680Ptr<ValDecl> Parser::parse_c_decl() {
681 auto track = tracker();
682 auto tag = lex().tag();
683 auto id = expect(Tag::M_id, "C function declaration");
684 auto dom = parse_ptrn(Brckt_Style, "domain of a C function"s, Prec::App);
685 Ptr<Expr> codom;
686 if (tag == Tag::K_cfun) {
687 expect(Tag::T_colon, "codomain of a C function");
688 codom = parse_expr("codomain of a C function");
689 }
690 return ptr<CDecl>(track, tag, id.dbg(), std::move(dom), std::move(codom));
691}
692
693Ptr<RecDecl> Parser::parse_rec_decl(bool first) {
694 auto track = tracker();
695 eat(first ? Tag::K_rec : Tag::K_and);
696 auto dbg = parse_name("recursive declaration");
697 auto type = accept(Tag::T_colon) ? parse_expr("type of a recursive declaration") : ptr<HoleExpr>(curr_);
698 expect(Tag::T_assign, "recursive declaration");
699 auto body = parse_expr("body of a recursive declaration");
700 auto next = ahead().isa(Tag::K_and) ? parse_and_decl() : nullptr;
701 return ptr<RecDecl>(track, dbg, std::move(type), std::move(body), std::move(next));
702}
703
704Ptr<ValDecl> Parser::parse_rule_decl() {
705 auto track = tracker();
706 auto is_norm = lex().tag() == Tag::K_norm;
707 auto dbg = parse_name("rewrite rule");
708 auto ptrn = parse_ptrn(0, "meta variables in rewrite rule");
709 expect(Tag::T_colon, "rewrite rule declaration");
710 auto lhs = parse_expr("rewrite pattern");
711 auto guard = ahead().isa(Tag::K_when) ? (eat(Tag::K_when), parse_expr("rewrite guard"))
712 : ptr<PrimaryExpr>(track, std::move(Tag::K_tt));
713 expect(Tag::T_fat_arrow, "rewrite rule declaration");
714 auto rhs = parse_expr("rewrite result");
715 return ptr<RuleDecl>(track, dbg, std::move(ptrn), std::move(lhs), std::move(rhs), std::move(guard), is_norm);
716}
717
718Ptr<LamDecl> Parser::parse_lam_decl() {
719 auto track = tracker();
720 auto tag = lex().tag();
721 auto prec = tag == Tag::K_cn || tag == Tag::K_con ? Prec::Bot : Prec::Pi;
722 bool external = (bool)accept(Tag::K_extern);
723
724 bool decl;
725 std::string entity;
726 // clang-format off
727 switch (tag) {
728 case Tag::T_lm: decl = false; entity = "function expression"; break;
729 case Tag::K_cn: decl = false; entity = "continuation expression"; break;
730 case Tag::K_fn: decl = false; entity = "returning continuation expression"; break;
731 case Tag::K_lam: decl = true ; entity = "function declaration"; break;
732 case Tag::K_con: decl = true ; entity = "continuation declaration"; break;
733 case Tag::K_fun: decl = true ; entity = "returning continuation declaration"; break;
734 default: fe::unreachable();
735 }
736 // clang-format on
737
738 auto dbg = decl ? parse_name(entity) : Dbg();
740 while (true) {
741 auto track = tracker();
742 auto ptrn = parse_ptrn(Paren_Style | Implicit, "domain pattern of a "s + entity, prec);
743 auto filter = accept(Tag::T_at) ? parse_expr("filter") : nullptr;
744 doms.emplace_back(ptr<LamDecl::Dom>(track, std::move(ptrn), std::move(filter)));
745
746 switch (ahead().tag()) {
747 case Tag::C_CURRIED_P: continue;
748 default: break;
749 }
750 break;
751 }
752
753 auto codom = accept(Tag::T_colon) ? parse_expr("codomain of a "s + entity, Prec::Arrow) : nullptr;
754 if (tag == Tag::K_fn || tag == Tag::K_fun)
755 doms.back()->add_ret(ast(), codom ? std::move(codom) : ptr<HoleExpr>(curr_));
756
757 expect(Tag::T_assign, "body of a "s + entity);
758 auto body = parse_expr("body of a "s + entity);
759 auto next = ahead().isa(Tag::K_and) ? parse_and_decl() : nullptr;
760
761 return ptr<LamDecl>(track, tag, external, dbg, std::move(doms), std::move(codom), std::move(body), std::move(next));
762}
763
764Ptr<RecDecl> Parser::parse_and_decl() {
765 switch (ahead(1).tag()) {
766 case Tag::C_LAM: return lex(), parse_lam_decl();
767 default: return parse_rec_decl(false);
768 }
769}
770
771} // namespace mim::ast
void load(Sym name)
Definition driver.cpp:71
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:211
static Ptr< IdPtrn > make_id(AST &ast, Dbg dbg, Ptr< Expr > &&type)
Definition ast.h:215
Ptr< Module > import(std::string_view sv, Tok::Tag tag=Tok::Tag::K_import)
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
constexpr bool should_reduce(Prec curr, Prec op)
Should a Pratt parser reduce when the current binding power is curr and the infix operator has preced...
Definition tok.h:58
std::deque< Ptr< T > > Ptrs
Definition ast.h:24
Tok::Tag Tag
Definition bind.cpp:7
Prec
Expression precedences used by the parser and the dumper; ordered low to high.
Definition tok.h:37
auto elems(std::ostream &os, const auto &range)
Wrap all elements in range through os << T(elem).
Definition print.h:97
constexpr decltype(auto) get(Span< T, N > span) noexcept
Definition span.h:115