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().add_import(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 parse_list("match branches", Tag::D_brace_l, [&]() {
320 auto track = tracker();
321 auto ptrn = parse_ptrn(Paren_Style, "right-hand side of a match-arm", Expr::Prec::Bot);
322 expect(Tag::T_fat_arrow, "arm of a match-expression");
323 auto body = parse_expr("arm of a match-expression");
324 arms.emplace_back(ptr<MatchExpr::Arm>(track, std::move(ptrn), std::move(body)));
325 });
326 return ptr<MatchExpr>(track, std::move(scrutinee), std::move(arms));
327}
328
329Ptr<Expr> Parser::parse_primary_expr(std::string_view ctxt) {
330 // clang-format off
331 switch (ahead().tag()) {
332 case Tag::C_PRIMARY: return ptr<PrimaryExpr>(lex());
333 case Tag::C_ID: return ptr<IdExpr>(lex().dbg());
334 case Tag::C_LIT: return parse_lit_expr();
335 case Tag::C_DECL: return parse_decl_expr();
336 case Tag::C_PI: return parse_pi_expr();
337 case Tag::C_LM: return parse_lam_expr();
338 case Tag::K_ins: return parse_insert_expr();
339 case Tag::K_ret: return parse_ret_expr();
340 case Tag::D_curly_l: return parse_uniq_expr();
341 case Tag::D_quote_l:
342 case Tag::D_angle_l: return parse_seq_expr();
343 case Tag::D_brckt_l: return parse_sigma_expr();
344 case Tag::D_paren_l: return parse_tuple_expr();
345 case Tag::K_Type: return parse_type_expr();
346 case Tag::K_match: return parse_match_expr();
347 default:
348 if (ctxt.empty()) return nullptr;
349 syntax_err("primary expression", ctxt);
350 }
351 // clang-format on
352 return ptr<ErrorExpr>(curr_);
353}
354
355Ptr<Expr> Parser::parse_seq_expr() {
356 auto track = tracker();
357 bool is_arr = accept(Tag::D_quote_l) ? true : (eat(Tag::D_angle_l), false);
358
359 std::deque<std::pair<Ptr<IdPtrn>, Ptr<Expr>>> shapes;
360
361 do {
362 Dbg dbg;
363 if (ahead(0).isa(Tag::M_id) && ahead(1).isa(Tag::T_colon)) {
364 dbg = eat(Tag::M_id).dbg();
365 eat(Tag::T_colon);
366 }
367
368 auto expr = parse_expr(is_arr ? "shape of an array" : "shape of a pack");
369 auto ptrn = IdPtrn::make_id(ast(), dbg, std::move(expr));
370 shapes.emplace_back(std::move(ptrn), std::move(expr));
371 } while (accept(Tag::T_comma));
372
373 expect(Tag::T_semicolon, is_arr ? "array" : "pack");
374 auto body = parse_expr(is_arr ? "body of an array" : "body of a pack");
375 expect(is_arr ? Tag::D_quote_r : Tag::D_angle_r,
376 is_arr ? "closing delimiter of an array" : "closing delimiter of a pack");
377
378 for (auto& [ptrn, expr] : shapes | std::ranges::views::reverse)
379 body = ptr<SeqExpr>(track, is_arr, std::move(ptrn), std::move(body));
380
381 return body;
382}
383
384Ptr<Expr> Parser::parse_decl_expr() {
385 auto track = tracker();
386 auto decls = parse_decls();
387 auto expr = parse_expr("final expression of a declaration expression");
388 return ptr<DeclExpr>(track, std::move(decls), std::move(expr), false);
389}
390
391Ptr<Expr> Parser::parse_lit_expr() {
392 auto track = tracker();
393 auto tok = lex();
394 auto type = accept(Tag::T_colon) ? parse_expr("literal", Expr::Prec::Lit) : nullptr;
395 return ptr<LitExpr>(track, tok, std::move(type));
396}
397
398Ptr<Expr> Parser::parse_sigma_expr() {
399 auto track = tracker();
400 auto ptrn = parse_tuple_ptrn(Brckt_Style);
401 switch (ahead().tag()) {
402 case Tag::K_as: {
403 lex();
404 auto alias = ptr<AliasPtrn>(track, std::move(ptrn), parse_name("alias pattern"));
405 return parse_pi_expr(std::move(alias));
406 }
407 case Tag::C_CURRIED_B:
408 case Tag::T_arrow: return parse_pi_expr(std::move(ptrn)); // TODO precedences for patterns
409 default: return ptr<SigmaExpr>(std::move(ptrn));
410 }
411}
412
413Ptr<Expr> Parser::parse_tuple_expr() {
414 auto track = tracker();
415 Ptrs<Expr> elems;
416 parse_list("tuple", Tag::D_paren_l, [&]() { elems.emplace_back(parse_expr("tuple element")); });
417 return ptr<TupleExpr>(track, std::move(elems));
418}
419
420Ptr<Expr> Parser::parse_type_expr() {
421 auto track = tracker();
422 eat(Tag::K_Type);
423 auto level = parse_expr("type level", Expr::Prec::App);
424 return ptr<TypeExpr>(track, std::move(level));
425}
426
427Ptr<Expr> Parser::parse_pi_expr() {
428 auto track = tracker();
429 auto tag = ahead().tag();
430 auto entity = "dependent function type"s;
431
432 if (accept(Tag::K_Cn))
433 entity = "continuation type";
434 else if (accept(Tag::K_Fn))
435 entity = "returning continuation type";
436
437 auto domt = tracker();
438 auto prec = tag == Tag::K_Cn ? Expr::Prec::Bot : Expr::Prec::Pi;
439 auto ptrn = parse_ptrn(Brckt_Style | Implicit, "domain of a "s + entity, prec);
440 auto dom = ptr<PiExpr::Dom>(domt, std::move(ptrn));
441
442 auto codom = tag != Tag::K_Cn
443 ? (expect(Tag::T_arrow, entity), parse_expr("codomain of a "s + entity, Expr::Prec::Arrow))
444 : nullptr;
445
446 if (tag == Tag::K_Fn) dom->add_ret(ast(), codom ? std::move(codom) : ptr<HoleExpr>(curr_));
447 return ptr<PiExpr>(track, tag, std::move(dom), std::move(codom));
448}
449
450Ptr<Expr> Parser::parse_pi_expr(Ptr<Ptrn>&& ptrn) {
451 auto track = tracker(ptrn->loc());
452 auto entity = "dependent function type"s;
453 auto dom = ptr<PiExpr::Dom>(ptrn->loc(), std::move(ptrn));
454 expect(Tag::T_arrow, entity);
455 auto codom = parse_expr("codomain of a "s + entity, Expr::Prec::Arrow);
456 return ptr<PiExpr>(track, Tag::Nil, std::move(dom), std::move(codom));
457}
458
459Ptr<Expr> Parser::parse_lam_expr() { return ptr<LamExpr>(parse_lam_decl()); }
460
461Ptr<Expr> Parser::parse_ret_expr() {
462 auto track = tracker();
463 eat(Tag::K_ret);
464 auto ptrn = parse_ptrn(Paren_Style, "binding pattern of a ret expression");
465 expect(Tag::T_assign, "ret expression");
466 auto callee = parse_expr("continuation expression of a ret expression");
467 expect(Tag::T_dollar, "separator of a ret expression");
468 auto arg = parse_expr("argument of ret expression");
469 expect(Tag::T_semicolon, "ret expression");
470 auto body = parse_expr("body of a ret expression");
471 return ptr<RetExpr>(track, std::move(ptrn), std::move(callee), std::move(arg), std::move(body));
472}
473
474/*
475 * ptrns
476 */
477
478Ptr<Ptrn> Parser::parse_ptrn(int style, std::string_view ctxt, Expr::Prec prec) {
479 auto track = tracker();
480 auto ptrn = parse_ptrn_(style, ctxt, prec);
481 if (accept(Tag::K_as)) return ptr<AliasPtrn>(track, std::move(ptrn), parse_name("alias pattern"));
482 return ptrn;
483}
484
485Ptr<Ptrn> Parser::parse_ptrn_(int style, std::string_view ctxt, Expr::Prec prec) {
486 auto track = tracker();
487
488 // p -> (p, ..., p)
489 // p -> {b, ..., b} b -> {b, ..., b}
490 // p -> [b, ..., b] b -> [b, ..., b]
491 if (is_paren_style(style) && ahead().isa(Tag::D_paren_l)) return parse_tuple_ptrn(style);
492 if (is_implicit(style) && ahead().isa(Tag::D_brace_l)) return parse_tuple_ptrn(style);
493 if (ahead().isa(Tag::D_brckt_l)) return parse_tuple_ptrn(Brckt_Style);
494
495 if (ahead(0).isa(Tag::M_id)) {
496 if (ahead(1).isa(Tag::T_colon)) {
497 // p -> s: e b -> s: e
498 auto dbg = eat(Tag::M_id).dbg();
499 eat(Tag::T_colon);
500 auto type = parse_expr(ctxt, prec);
501 return ptr<IdPtrn>(track, dbg, std::move(type));
502 } else if (is_paren_style(style)) {
503 // p -> s
504 // p -> `s
505 auto dbg = eat(Tag::M_id).dbg();
506 return ptr<IdPtrn>(track, dbg, nullptr);
507 } else {
508 // b -> e where e == id
509 auto type = parse_expr(ctxt, prec);
510 return ptr<IdPtrn>(track, type->loc().anew_begin(), std::move(type));
511 }
512 } else if (is_brket_style(style)) {
513 // b -> e where e != id
514 auto type = parse_expr(ctxt, prec);
515 auto loc = type->loc().anew_begin();
516 return ptr<IdPtrn>(track, Dbg(loc), std::move(type));
517 } else if (!ctxt.empty()) {
518 // p -> ↯
519 syntax_err("pattern", ctxt);
520 return ptr<ErrorPtrn>(curr_);
521 }
522
523 return nullptr;
524}
525
526Ptr<TuplePtrn> Parser::parse_tuple_ptrn(int style) {
527 auto track = tracker();
528 auto delim_l = ahead().tag();
529
530 Ptrs<Ptrn> ptrns;
531 parse_list("tuple pattern", delim_l, [&]() {
532 auto track = tracker();
533 Ptr<Ptrn> ptrn;
534
535 if (ahead(0).isa(Tag::M_id) && ahead(1).isa(Tag::M_id)) {
536 Dbgs dbgs;
537 while (auto tok = accept(Tag::M_id)) dbgs.emplace_back(tok.dbg());
538
539 if (accept(Tag::T_colon)) { // identifier group: x y x: T
540 auto dbg = dbgs.back();
541 auto type = parse_expr("type of an identifier group within a tuple pattern");
542 auto id = ptr<IdPtrn>(dbg.loc() + type->loc().finis, dbg, std::move(type));
543
544 for (auto dbg : dbgs | std::views::take(dbgs.size() - 1))
545 ptrns.emplace_back(ptr<GrpPtrn>(dbg, id.get()));
546 ptrns.emplace_back(std::move(id));
547 return;
548 }
549
550 // "x y z" is a curried app and maybe the prefix of a longer type expression
551 Ptr<Expr> lhs = ptr<IdExpr>(dbgs.front());
552 for (auto dbg : dbgs | std::views::drop(1)) {
553 auto rhs = ptr<IdExpr>(dbg);
554 lhs = ptr<AppExpr>(track, false, std::move(lhs), std::move(rhs));
555 }
556 auto expr = parse_infix_expr(track, std::move(lhs), Expr::Prec::App);
557 ptrn = IdPtrn::make_type(ast(), std::move(expr));
558 } else {
559 ptrn = parse_ptrn(style & Style_Bit, "element of a tuple pattern");
560
561 if (is_brket_style(style)) {
562 // [..., [Nat, Nat] -> Nat, ...] ==> [..., _: [Nat, Nat] -> Nat, ...]
563 if (ahead().isa(Tag::T_arrow)) {
564 auto loc = ptrn->loc();
565 auto expr = parse_pi_expr(std::move(ptrn));
566 ptrn = ptr<IdPtrn>(loc, Dbg(loc.anew_begin(), Sym()), std::move(expr));
567 } else if (auto expr = Ptrn::to_expr(ast(), std::move(ptrn))) {
568 // If we are able to parse more stuff, we got an expr instead of a binder
569 auto addr = expr.get();
570 expr = parse_infix_expr(track, std::move(expr));
571 if (expr.get() != addr) {
572 auto loc = expr->loc();
573 ptrn = ptr<IdPtrn>(loc, Dbg(loc.anew_begin(), Sym()), std::move(expr));
574 } else {
575 if (!ptrn) ptrn = Ptrn::to_ptrn(std::move(expr));
576 }
577 }
578 }
579 }
580
581 ptrns.emplace_back(std::move(ptrn));
582 });
583
584 return ptr<TuplePtrn>(track, delim_l, std::move(ptrns));
585}
586
587/*
588 * decls
589 */
590
591Ptrs<ValDecl> Parser::parse_decls() {
592 Ptrs<ValDecl> decls;
593 while (true) {
594 // clang-format off
595 switch (ahead().tag()) {
596 case Tag::T_semicolon: lex(); break; // eat up stray semicolons
597 case Tag::K_axm: decls.emplace_back(parse_axm_decl()); break;
598 case Tag::K_ccon:
599 case Tag::K_cfun: decls.emplace_back(parse_c_decl()); break;
600 case Tag::K_let: decls.emplace_back(parse_let_decl()); break;
601 case Tag::K_rec: decls.emplace_back(parse_rec_decl(true)); break;
602 case Tag::K_con:
603 case Tag::K_fun:
604 case Tag::K_lam: decls.emplace_back(parse_lam_decl()); break;
605 default: return decls;
606 }
607 // clang-format on
608 }
609}
610
611Ptr<ValDecl> Parser::parse_axm_decl() {
612 auto track = tracker();
613 eat(Tag::K_axm);
614 Dbg dbg, normalizer;
615 Tok curry, trip;
616 if (auto name = expect(Tag::M_anx, "annex name of an axm"))
617 dbg = name.dbg();
618 else
619 dbg = Dbg(curr_, ast().sym("<error annex name>"));
620
621 std::deque<Ptrs<AxmDecl::Alias>> subs;
622 if (ahead().isa(Tag::D_paren_l)) {
623 parse_list("tag list of an axm", Tag::D_paren_l, [&]() {
624 auto& aliases = subs.emplace_back();
625 aliases.emplace_back(ptr<AxmDecl::Alias>(parse_id("tag of an axm")));
626 while (accept(Tag::T_assign)) aliases.emplace_back(ptr<AxmDecl::Alias>(parse_id("alias of an axm tag")));
627 });
628 }
629
630 auto type = parse_type_ascr("type ascription of an axm");
631
632 if (ahead(0).isa(Tag::T_comma) && ahead(1).isa(Tag::M_id)) {
633 lex();
634 normalizer = lex().dbg();
635 }
636 if (accept(Tag::T_comma)) {
637 if (auto c = expect(Tag::L_u, "curry counter for axm")) curry = c;
638 if (accept(Tag::T_comma)) {
639 if (auto t = expect(Tag::L_u, "trip count for axm")) trip = t;
640 }
641 }
642
643 return ptr<AxmDecl>(track, dbg, std::move(subs), std::move(type), normalizer, curry, trip);
644}
645
646Ptr<ValDecl> Parser::parse_let_decl() {
647 auto track = tracker();
648 eat(Tag::K_let);
649
650 Ptr<Ptrn> ptrn;
651 if (auto anx = accept(Tok::Tag::M_anx)) {
652 auto type = parse_type_ascr();
653 ptrn = ptr<IdPtrn>(track, anx.dbg(), std::move(type));
654 } else {
655 ptrn = parse_ptrn(Paren_Style, "binding pattern of a let declaration", Expr::Prec::Bot);
656 }
657
658 expect(Tag::T_assign, "let");
659 auto type = parse_type_ascr();
660 auto value = parse_expr("value of a let declaration");
661 return ptr<LetDecl>(track, std::move(ptrn), std::move(value));
662}
663
664Ptr<ValDecl> Parser::parse_c_decl() {
665 auto track = tracker();
666 auto tag = lex().tag();
667 auto id = expect(Tag::M_id, "C function declaration");
668 auto dom = parse_ptrn(Brckt_Style, "domain of a C function"s, Expr::Prec::App);
669 Ptr<Expr> codom;
670 if (tag == Tag::K_cfun) {
671 expect(Tag::T_colon, "codomain of a C function");
672 codom = parse_expr("codomain of a C function");
673 }
674 return ptr<CDecl>(track, tag, id.dbg(), std::move(dom), std::move(codom));
675}
676
677Ptr<RecDecl> Parser::parse_rec_decl(bool first) {
678 auto track = tracker();
679 eat(first ? Tag::K_rec : Tag::K_and);
680 auto dbg = parse_name("recursive declaration");
681 auto type = accept(Tag::T_colon) ? parse_expr("type of a recursive declaration") : ptr<HoleExpr>(curr_);
682 expect(Tag::T_assign, "recursive declaration");
683 auto body = parse_expr("body of a recursive declaration");
684 auto next = ahead().isa(Tag::K_and) ? parse_and_decl() : nullptr;
685 return ptr<RecDecl>(track, dbg, std::move(type), std::move(body), std::move(next));
686}
687
688Ptr<LamDecl> Parser::parse_lam_decl() {
689 auto track = tracker();
690 auto tag = lex().tag();
691 auto prec = tag == Tag::K_cn || tag == Tag::K_con ? Expr::Prec::Bot : Expr::Prec::Pi;
692 bool external = (bool)accept(Tag::K_extern);
693
694 bool decl;
695 std::string entity;
696 // clang-format off
697 switch (tag) {
698 case Tag::T_lm: decl = false; entity = "function expression"; break;
699 case Tag::K_cn: decl = false; entity = "continuation expression"; break;
700 case Tag::K_fn: decl = false; entity = "returning continuation expression"; break;
701 case Tag::K_lam: decl = true ; entity = "function declaration"; break;
702 case Tag::K_con: decl = true ; entity = "continuation declaration"; break;
703 case Tag::K_fun: decl = true ; entity = "returning continuation declaration"; break;
704 default: fe::unreachable();
705 }
706 // clang-format on
707
708 auto dbg = decl ? parse_name(entity) : Dbg();
710 while (true) {
711 auto track = tracker();
712 auto ptrn = parse_ptrn(Paren_Style | Implicit, "domain pattern of a "s + entity, prec);
713 auto filter = accept(Tag::T_at) ? parse_expr("filter") : nullptr;
714 doms.emplace_back(ptr<LamDecl::Dom>(track, std::move(ptrn), std::move(filter)));
715
716 switch (ahead().tag()) {
717 case Tag::C_CURRIED_P: continue;
718 default: break;
719 }
720 break;
721 }
722
723 auto codom = accept(Tag::T_colon) ? parse_expr("codomain of a "s + entity, Expr::Prec::Arrow) : nullptr;
724 if (tag == Tag::K_fn || tag == Tag::K_fun)
725 doms.back()->add_ret(ast(), codom ? std::move(codom) : ptr<HoleExpr>(curr_));
726
727 expect(Tag::T_assign, "body of a "s + entity);
728 auto body = parse_expr("body of a "s + entity);
729 auto next = ahead().isa(Tag::K_and) ? parse_and_decl() : nullptr;
730
731 return ptr<LamDecl>(track, tag, external, dbg, std::move(doms), std::move(codom), std::move(body), std::move(next));
732}
733
734Ptr<RecDecl> Parser::parse_and_decl() {
735 switch (ahead(1).tag()) {
736 case Tag::C_LAM: return lex(), parse_lam_decl();
737 default: return parse_rec_decl(false);
738 }
739}
740
741} // namespace mim::ast
void load(Sym name)
Definition driver.cpp:53
Error & note(Loc loc, const char *fmt, Args &&... args) const
Definition ast.h:84
Error & error()
Definition ast.h:61
Error & warn(Loc loc, const char *fmt, Args &&... args) const
Definition ast.h:83
static Ptr< IdPtrn > make_type(AST &ast, Ptr< Expr > &&type)
Definition ast.h:224
static Ptr< IdPtrn > make_id(AST &ast, Dbg dbg, Ptr< Expr > &&type)
Definition ast.h:228
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:177
static Ptr< Expr > to_expr(AST &, Ptr< Ptrn > &&)
Definition ast.cpp:167
Definition ast.h:14
std::deque< Dbg > Dbgs
Definition ast.h:23
fe::Arena::Ptr< const T > Ptr
Definition ast.h:21
std::deque< Ptr< T > > Ptrs
Definition ast.h:22
constexpr decltype(auto) get(Span< T, N > span) noexcept
Definition span.h:107