-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhcpp2cpp.cpp
More file actions
148 lines (127 loc) · 2.6 KB
/
hcpp2cpp.cpp
File metadata and controls
148 lines (127 loc) · 2.6 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#include <errno.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool debug = false;
bool atbeginingosstring = true;
void escape (ostream & out, char c) {
switch (c) {
case 10:
case 13:
if (!atbeginingosstring)
out << "\\015\\012\"";
out << c;
atbeginingosstring = true;
break;
default:
if (atbeginingosstring) {
out << '"';
atbeginingosstring = false;
}
switch (c) {
case '"': out << "\\\""; break;
case '\\': out << "\\\\"; break;
default: out << c; break;
}
}
}
bool parse (istream &in, ostream &out) {
string matchbegin ("{{"),
matchend ("}}");
#define MATCHLEN 2
string const * match = &matchbegin;
bool incpp = true;
char c;
size_t pos = 0;
while (in && in.get(c)) {
if (c == (*match)[pos]) {
pos ++;
if (pos == MATCHLEN) {
if (incpp) {
incpp = false;
match = &matchend;
atbeginingosstring = true;
out << " ";
} else {
incpp = true;
match = &matchbegin;
if (!atbeginingosstring)
out << '"';
out << " ";
}
pos = 0;
}
} else {
if (pos != 0) {
for (size_t i=0 ; i<pos ; i++) {
if (incpp)
out << (*match)[i];
else
escape(out, (*match)[i]);
}
pos = 0;
}
if (incpp)
out << c;
else
escape(out, c);
}
}
return true;
}
void usage (void) {
cout << "usage : hcpp2cpp [ ... input.hcpp ... ] -o[ ]output.cc" << endl << endl;
}
int main (int nb, char ** cmde) {
if (nb == 1) {
usage();
return 1;
}
string outputfname;
int i;
for (i=1 ; i<nb ; i++) { // let's seek for the output name
if (strncmp (cmde[i], "-o", 2) == 0) {
if (cmde[i][2] != 0) {
outputfname += (cmde[i] + 2);
} else if (i+1 < nb) {
outputfname += cmde[i+1];
}
break;
}
}
if (outputfname.empty()) {
cerr << "hcpp2cpp error, missing filename output" << endl;
usage();
return 1;
}
ofstream out(outputfname.c_str());
if (!out) {
int e = errno;
cerr << "hcpp2cpp error, cannot open " << outputfname << " , "
<< strerror(e) << endl;
return 1;
}
for (i=1 ; i<nb ; i++) {
if (strncmp (cmde[i], "-o", 2) == 0) {
if (cmde[i][2] == 0) {
i++;
}
continue;
}
ifstream in(cmde[i]);
if (!in) {
int e = errno;
cerr << "hcpp2cpp error, cannot open " << cmde[i] << " , "
<< strerror(e) << endl;
return 1;
}
if (debug)
cerr << "parsing " << cmde[i] << " ..." << endl;
out << "# 1 \"" << cmde[i] << "\"" << endl;
if (!parse (in, out))
break;
}
return 0;
}