-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator.cpp
95 lines (79 loc) · 1.79 KB
/
generator.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "generator.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include "detail/objects.h"
#include "detail/parser.h"
#include "detail/generator.h"
#include "detail/xml_generator.h"
#include "detail/json_generator.h"
#include "detail/binary_generator.h"
namespace
{
bool read_file(const std::string & filename, std::string & data)
{
std::ifstream ifs(filename);
if(!ifs)
{
return false;
}
ifs.seekg(0, std::ios::end);
auto size = ifs.tellg();
ifs.seekg(0, std::ios::beg);
if(size <= 0)
{
return false;
}
data.resize(size);
ifs.read(&data[0], size);
return true;
}
} // namespace
namespace serialization
{
generator::generator()
{
generators_ =
{
{"-xml", new serialization::detail::xml_generator},
{"-json", new serialization::detail::json_generator},
{"-binary", new serialization::detail::binary_generator},
};
}
generator::~generator()
{
for(auto & i : generators_)
{
delete i.second;
}
}
bool generator::gen_code(const std::string & type, const std::string & in, const std::string & out)
{
auto iter = generators_.find(type);
if(iter == generators_.end())
{
std::cout << "unknown code type: " << type << std::endl;
return false;
}
std::string data;
if(!read_file(in, data))
{
std::cout << "read file error: " << in << std::endl;
return false;
}
std::string out_file = out.empty() ? in : out;
detail::tree t;
try
{
parser p(t);
p.parse(data);
iter->second->gen_code(t, out_file);
}
catch(const detail::parse_error& err)
{
std::cout << in << ">> " << err.where() << ":" << err.what() << std::endl;
return false;
}
return true;
}
} // namespace serialization