MimIR 0.1
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
lexer.h
Go to the documentation of this file.
1#pragma once
2
3#include <optional>
4
5#include <absl/container/flat_hash_map.h>
6#include <fe/lexer.h>
7
8#include "mim/ast/tok.h"
9
10namespace mim::ast {
11
12namespace fs = std::filesystem;
13
14class AST;
15
16class Lexer : public fe::Lexer<3, Lexer> {
17 using Super = fe::Lexer<3, Lexer>;
18
19public:
20 /// Creates a lexer to read `*.mim` files (see [Lexical Structure](@ref lex)).
21 /// If @p md is not `nullptr`, a Markdown output will be generated.
22 Lexer(AST&, std::istream&, const fs::path* path = nullptr, std::ostream* md = nullptr);
23
24 AST& ast() { return ast_; }
25 const fs::path* path() const { return loc_.path; }
26 Loc loc() const { return loc_; }
27 Tok lex();
28
29private:
30 char32_t next() {
31 auto res = Super::next();
32 if (md_ && out_) {
33 if (res == fe::utf8::EoF) {
34 *md_ << "\n```\n";
35 out_ = false;
36 } else if (res) {
37 bool success = fe::utf8::encode(*md_, res);
38 assert_unused(success);
39 }
40 }
41 return res;
42 }
43
44 Tok tok(Tok::Tag tag) { return {loc(), tag}; }
45 Sym sym();
46 Loc cache_trailing_dot();
47 bool lex_id();
48 char8_t lex_char();
49 std::optional<Tok> parse_lit();
50 void parse_digits(int base = 10);
51 bool parse_exp(int base = 10);
52 void eat_comments();
53 bool start_md() const { return ahead(0) == '/' && ahead(1) == '/' && ahead(2) == '/'; }
54 void emit_md(bool start_of_file = false);
55 void md_fence() {
56 if (md_) *md_ << "```\n";
57 }
58
59 AST& ast_;
60 std::ostream* md_;
61 bool out_ = true;
62 fe::SymMap<Tok::Tag> keywords_;
63 std::optional<Tok> cache_ = std::nullopt;
64
65 friend class fe::Lexer<3, Lexer>;
66};
67
68} // namespace mim::ast
Lexer(AST &, std::istream &, const fs::path *path=nullptr, std::ostream *md=nullptr)
Creates a lexer to read *.mim files (see Lexical Structure).
Definition lexer.cpp:12
AST & ast()
Definition lexer.h:24
const fs::path * path() const
Definition lexer.h:25
Loc loc() const
Definition lexer.h:26
Definition ast.h:13