]> git.tdb.fi Git - libs/datafile.git/blob - tool/builtingenerator.cpp
Cosmetic changes
[libs/datafile.git] / tool / builtingenerator.cpp
1 #include <msp/fs/utils.h>
2 #include <msp/strings/format.h>
3 #include <msp/strings/utils.h>
4 #include "builtingenerator.h"
5
6 using namespace std;
7 using namespace Msp;
8
9 BuiltinGenerator::BuiltinGenerator(IO::Base &o):
10         out(o)
11 {
12         out.write("#include <msp/datafile/builtinsource.h>\n\n");
13 }
14
15 void BuiltinGenerator::begin(const std::string &ns)
16 {
17         if(!namespc.empty() || !filenames.empty())
18                 throw logic_error("BuiltinGenerator::begin");
19
20         if(!ns.empty())
21         {
22                 namespc = split(ns, "::");
23                 for(vector<string>::const_iterator i=namespc.begin(); i!=namespc.end(); ++i)
24                         out.write(format("namespace %s {\n", *i));
25         }
26 }
27
28 void BuiltinGenerator::add_file(const std::string &fn)
29 {
30         IO::BufferedFile in(fn);
31
32         string base_fn = FS::basename(fn);
33         filenames.push_back(base_fn);
34
35         out.write(format("\nconst char %s_data[] =\n", mangle_filename(base_fn)));
36         string line;
37         while(!in.eof())
38         {
39                 char buf[19];
40                 unsigned len = in.read(buf, (79-line.size())/4);
41                 line += c_escape(string(buf, len));
42                 if(line.size()>=76 || in.eof())
43                 {
44                         out.write(format("  \"%s\"", line));
45                         line.clear();
46                         if(in.eof())
47                                 out.put(';');
48                         out.put('\n');
49                 }
50         }
51 }
52
53 void BuiltinGenerator::end(const string &module_name)
54 {
55         out.write(format("\nvoid init_%s(DataFile::BuiltinSource &source)\n{\n", module_name));
56         for(vector<string>::const_iterator i=filenames.begin(); i!=filenames.end(); ++i)
57                 out.write(format("  source.add_object(\"%s\", %s_data);\n", *i, mangle_filename(*i)));
58         out.write("}\n");
59
60         if(!namespc.empty())
61         {
62                 out.put('\n');
63                 for(vector<string>::const_iterator i=namespc.begin(); i!=namespc.end(); ++i)
64                         out.write(format("} // namespace %s\n", *i));
65
66                 namespc.clear();
67                 filenames.clear();
68         }
69 }
70
71 string BuiltinGenerator::mangle_filename(const string &fn)
72 {
73         string mangled = fn;
74         for(string::iterator i=mangled.begin(); i!=mangled.end(); ++i)
75                 if(!isalnum(*i))
76                         *i = '_';
77         return mangled;
78 }