mutable
A Database System for Research and Fast Prototyping
Loading...
Searching...
No Matches
lex.cpp
Go to the documentation of this file.
1#include "lex/Lexer.hpp"
5#include <mutable/util/fn.hpp>
6#include <cerrno>
7#include <cstdlib>
8#include <cstring>
9#include <fstream>
10#include <iostream>
11
12
13using namespace m;
14
15
16void usage(std::ostream &out, const char *name)
17{
18 out << "Performs lexicographic analysis of the input.\n"
19 << "USAGE:\n\t" << name << " <FILE>"
20 << "\n\t" << name << " -"
21 << std::endl;
22}
23
24int main(int argc, const char **argv)
25{
26 ArgParser AP;
27#define ADD(TYPE, VAR, INIT, SHORT, LONG, DESCR, CALLBACK)\
28 TYPE VAR = INIT;\
29 {\
30 AP.add<TYPE>(SHORT, LONG, DESCR, CALLBACK);\
31 }
32 ADD(bool, show_help, false, /* Type, Var, Init */
33 "-h", "--help", /* Short, Long */
34 "prints this help message", /* Description */
35 [&](bool) { show_help = true; }); /* Callback */
36 ADD(bool, color, false, /* Type, Var, Init */
37 nullptr, "--color", /* Short, Long */
38 "use colors", /* Description */
39 [&](bool) { color = true; }); /* Callback */
40#undef ADD
41 AP.parse_args(argc, argv);
42
43 if (show_help) {
44 usage(std::cout, argv[0]);
45 std::cout << "WHERE\n" << AP;
46 std::exit(EXIT_SUCCESS);
47 }
48
49 if (AP.args().size() != 1) {
50 usage(std::cerr, argv[0]);
51 std::cerr << "WHERE\n" << AP;
52 std::exit(EXIT_FAILURE);
53 }
54
55 const char *filename = AP.args()[0];
56 std::istream *in;
57 if (streq(filename, "-")) {
58 /* read from stdin */
59 in = &std::cin;
60 } else {
61 /* read from file */
62 in = new std::ifstream(filename, std::ios_base::in);
63 }
64
65 if (in->fail()) {
66 if (in == &std::cin)
67 std::cerr << "Failed to open stdin: ";
68 else
69 std::cerr << "Failed to open the file '" << filename << "': ";
70 std::cerr << strerror(errno) << std::endl;
71 }
72
73 Diagnostic diag(color, std::cout, std::cerr);
75 ast::Lexer lexer(diag, pool, filename, *in);
76
77 while (auto tok = lexer.next())
78 diag(tok.pos) << tok.text << ' ' << tok.type << std::endl;
79
80 if (in != &std::cin)
81 delete in;
82
83 std::exit(diag.num_errors() ? EXIT_FAILURE : EXIT_SUCCESS);
84}
int main(void)
bool show_help
‍whether to show a help message
A parser for command line arguments.
Definition: ArgParser.hpp:20
void parse_args(int argc, const char **argv)
Parses the arguments from argv.
Definition: ArgParser.cpp:186
const std::vector< const char * > & args() const
Returns all positional arguments.
Definition: ArgParser.hpp:143
void usage(std::ostream &out, const char *name)
Definition: lex.cpp:16
#define ADD(TYPE, VAR, INIT, SHORT, LONG, DESCR, CALLBACK)
‍mutable namespace
Definition: Backend.hpp:10
bool streq(const char *first, const char *second)
Definition: fn.hpp:29
unsigned num_errors() const
Returns the number of errors emitted since the last call to clear().
Definition: Diagnostic.hpp:48
Token next()
Obtains the next token from the input stream.
Definition: Lexer.cpp:20