-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexgen.cpp
68 lines (64 loc) · 1.89 KB
/
lexgen.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include "dfa.h"
#include "rexparser.h"
#include <cstring>
#include <fstream>
#include <string>
#include <iostream>
int lexgen(std::istream &in, std::ostream &out);
int main(int argc, char** argv) {
std::ifstream specs_ifs;
std::ofstream ttab_ofs;
int retval = 0;
std::string usage = "USAGE:\n\n-./lexgen <specs_file> <transition_table_output>\n\n\
-./lexgen <specs_file>\n\toutputs to stdout\n\n\
-./lexgen\n\treads from stdin and outputs to stdout\n";
if (argc == 1) {
retval = lexgen(std::cin, std::cout);
} else if (argc == 2) {
if (strcmp(argv[1], "--help") == 0) {
std::cout << usage << std::endl;
return 0;
}
specs_ifs.open(argv[1]);
retval = lexgen(specs_ifs, std::cout);
specs_ifs.close();
} else if (argc == 3) {
specs_ifs.open(argv[1]);
ttab_ofs.open(argv[2]);
retval = lexgen(specs_ifs, ttab_ofs);
specs_ifs.close();
ttab_ofs.close();
} else {
std::string err_msg = "Invalid number of arguments!\n" + usage;
perror(err_msg.c_str());
errno = EINVAL;
exit(-1);
}
return retval;
}
std::string read_istream(std::istream &in) {
return std::string(std::istreambuf_iterator<char>(in), {});
}
int lexgen(std::istream &in, std::ostream &out) {
try {
if (!in | !out) {
perror("Unable to read file");
return -1;
}
std::string specs = read_istream(in);
rexparser rx;
machine nfa = rx.rules2nfa(specs);
machine dfa = dfa::to_dfa(nfa);
machine min_dfa = dfa::minimize_dfa(dfa);
out << min_dfa;
return 0;
} catch (const std::exception& ex) {
std::cout << ex.what() << std::endl;
return -1;
} catch (const std::string& ex) {
std::cout << ex << std::endl;
return -1;
} catch (...) {
return -1;
}
}