summaryrefslogtreecommitdiffabout
path: root/src/cliche.rl
blob: 1f1f07fe5035f9dba86430c1af036eac417f3698 (plain)
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#include <getopt.h>
#include <iostream>
#include <cstring>
#include <cassert>
#include <algorithm>
#include <fstream>

#include "config.h"

struct line_counting_monkey {
	int n;
	const char *p;
	const char *fn;

	line_counting_monkey(const char *fn_,const char *p_) : fn(fn_), n(1), p(p_) { }

	int lineno(const char *pp) {
		if(pp>p) {
			n += std::count(p,pp,'\n');
			p = pp;
		}
		return n;
	}
};

struct code_writing_monkey {
	std::ostream& o;
	enum omode_type {
		om_code = 0, om_output, om_inline, om_literal,
		oms
	};
	omode_type omode;
	int last_anchor, since_anchor;

	code_writing_monkey(std::ostream& o_) : o(o_), omode(om_code), last_anchor(-1), since_anchor(0) { }

	void modify(omode_type om,line_counting_monkey* lcm=0,const char *p=0) {
		static const char *om_transitions[oms][oms] = {
		// To:                                                                            From:
		// code    output                          inline                      literal
		 { "",     "CLICHE_OUTPUT_LITERAL(\n",     "CLICHE_STREAM << (",       "" }, // code
		 { ");\n", "",                             ");\n(CLICHE_STREAM) << (", 0  }, // output
		 { ");\n", ");\nCLICHE_OUTPUT_LITERAL(\n", "",                         0  }, // inline
		 { " ",    0,                              0,                          "" }, // literal
		};
		assert(0 <= omode && omode < oms);
		assert(0 <= om && om < oms);
		const char *t = om_transitions[omode][om];
		assert(t); // TODO: complain?
		o << t;
		since_anchor += std::count(t,t+strlen(t),'\n');
		if(lcm && t && *t && om!=omode && p) anchor(*lcm,p);
		omode = om;
	}

	void prologue() {
		assert(omode==om_code);
		o <<
		"#ifndef CLICHE_STREAM\n"
		"# define CLICHE_STREAM (std::cout)\n"
		"# define CLICHE_STREAM_AUTODEFINED\n"
		"#endif\n"
		"#ifndef CLICHE_OUTPUT_LITERAL\n"
		"# define CLICHE_OUTPUT_LITERAL(sl) (CLICHE_STREAM).write((sl),sizeof(sl)-sizeof(\"\"))\n"
		"#endif\n";
	}
	void epilogue() {
		modify(om_code);
		o << "\n"
		"#ifdef CLICHE_STREAM_AUTODEFINED\n"
		"# undef CLICHE_STREAM\n"
		"# undef CLICHE_STREAM_AUTODEFINED\n"
		"#endif\n";
	}

	void monkey(const char *d,size_t l=0) {
		if(!(l || (l=strlen(d)))) return;
		if(omode!=om_output && omode!=om_literal) {
			since_anchor += std::count(d,d+l,'\n');
			o.write(d,l);
			return;
		}
		o.put('"');
		const char *p=d;
		while(l--) {
			char c;
			switch(*d) {
			case '\r': c='r'; break;
			case '\n': c='n'; break;
			case '\t': c='t'; break;
			case '\a': c='a'; break;
			case '\b': c='b'; break;
			case '\v': c='v'; break;
			case '\f': c='f'; break;
			case '\'': case '\"': case '\\': c=*d; break;
			case 0: c='0'; break;
			default: c=0; break;
			};
			if(!c) {
				++d;
				continue;
			}
			if(p!=d) o.write(p,d-p);
			o.put('\\');
			if(c=='0')
				o.write("000",3);
			else
				o.put(c);
			p=++d;
		}
		if(p!=d) o.write(p,d-p);
		o.write("\"\n",2); ++since_anchor;
	}

	void monkey_as(omode_type om,const char *d,size_t l=0,line_counting_monkey *lcm=0,const char *p=0) { modify(om,lcm,p); monkey(d,l); }

	void anchor(line_counting_monkey& lcm,const char *p) {
		// modify(om_code);
		int l = lcm.lineno(p);
		if(last_anchor>0 && last_anchor+since_anchor==l) return;
		o << "\n#line " << (since_anchor=0,last_anchor=l) << " \"" << lcm.fn << "\"\n";
	}
};


%%{
	machine cliche;

	linebreak = /[\r\n]/;

	action monkey {
		cwm.monkey(ts,te-ts);
	}
	action monkey_code {
		cwm.monkey_as(cwm.om_code,ts,te-ts,&lcm,p);
	}
	action monkey_output {
		cwm.monkey_as(cwm.om_output,ts,te-ts,&lcm,p);
	}
	action monkey_literal {
		cwm.monkey_as(cwm.om_literal,ts,te-ts,&lcm,p);
	}

	slashstar_comment :=
		( any* :>> '*/' ) ${ cwm.monkey(fpc,1); } @{ fret; };

	outputblock := |*
		'%' (^linebreak)* linebreak { cwm.monkey_as(cwm.om_code,ts+1,te-ts-1,&lcm,p); };
		 any=> { fhold; fcall outputline; };
		
	*|;
	outputline := |*
		(^linebreak)* linebreak -- ('</%output>' | '<%code>' | ('<%' space) ) { cwm.monkey_as(cwm.om_output,ts,te-ts,&lcm,p); fret; };
		'<%code>' { cwm.modify(cwm.om_code,&lcm,p); fcall codeblock; };
		'</%output>' { --top; fret; };
		'<%' space { cwm.modify(cwm.om_inline,&lcm,p); fcall inlineblock; };
		(^linebreak)+ -- ( '%' | '<' ) => monkey_output;
		any => monkey_output;
	*|;

	inlineblock := |*
		space '%>' { cwm.modify(cwm.om_code,&lcm,p); fret; };
		"'" ( [^'\\] | /\\./ )* "'" => monkey;
		'"' ( [^"\\] | /\\./ )* '"' => monkey;
		'/*' { cwm.monkey("/*",2); fcall slashstar_comment; };
		'//' (^linebreak)* (linebreak) => monkey;
		any => monkey;
	*|;

	literalblock := |*
		any => { fhold; fcall literalline; };
	*|;
	literalline := |*
		(^linebreak)* linebreak -- ('</%literal>' | ('<%' space) ) { cwm.monkey_as(cwm.om_literal,ts,te-ts,&lcm,p); fret; };
		'</%literal>' { --top; fret; };
		'<%' space { cwm.modify(cwm.om_code,&lcm,p); fcall inlineblock; };
		(^linebreak)+ -- ( '%' | '<' ) => monkey_literal;
		any => monkey_literal;
	*|;

	codeblock := |*
		'<%output>'	{ fcall outputblock; };
		'<%literal>'	{ fcall literalblock; };
		'</%code>'	{ fret; };
		"'" ( [^'\\] | /\\./ )* "'" => monkey_code;
		'"' ( [^"\\] | /\\./ )* '"' => monkey_code;
		'/*' { cwm.monkey("/*",2); fcall slashstar_comment; };
		'//' (^linebreak)* (linebreak) => monkey_code;
		any => monkey_code;
	*|;

	main :=  any >{
		fhold;
		switch(topmode) {
		case code_writing_monkey::om_output: fgoto outputblock;
		case code_writing_monkey::om_code: fgoto  codeblock;
		default: ;/* TODO: WTD? */
		};
	};
}%%

%% write data;

static const char *biname = 0;
static void display_usage() {
	std::cerr << PACKAGE " Version " VERSION "\n"
	"Copyright (c) 2011 Klever Group\n"
	"\n"
	" " << biname << " [otpions] [input-file]\n"
	"\n"
#ifdef HAVE_GETOPT_LONG
	" -h, --help\n"
	" --usage                     display this text\n"
	" -V, --version               display version number\n"
	" -L, --license               show license\n"
	" -o <file>, --output=<file>  write output to the named file\n"
	" -t code|output, --top=code|output\n"
#else
	" -h                          display this text\n"
	" -V                          display version number\n"
	" -L                          show license\n"
	" -o <file>                   write output to the named file\n"
	" -t code|output\n"
#endif
	"                             set toplevel processing mode [output]\n"
	" -C                          same as -t=code\n"
	" -O                          same as -t=output (default)\n"
	"\n";
}

int main(int argc,char *argv[]) {
	biname = *argv;
	std::string ofile;
	code_writing_monkey::omode_type topmode = code_writing_monkey::om_output;
	while(true) {
		static const char shopts[] = "hVLo:t:CO";
#if HAVE_GETOPT_LONG
		static struct option opts[] = {
			{ "help", no_argument, 0, 'h' },
			{ "usage", no_argument, 0, 'h' },
			{ "version", no_argument, 0, 'V' },
			{ "license", no_argument, 0, 'L' },
			{ "output", required_argument, 0, 'o' },
			{ "top", required_argument, 0, 't' },
			{ NULL, 0, 0, 0 }
		};
		int c = getopt_long(argc,argv,shopts,opts,NULL);
#else
		int c = getopt(argc,argv,shopts);
#endif
		if(c==-1) break;
		switch(c) {
		case 't':
			if(!strcasecmp(optarg,"code")) {
				topmode = code_writing_monkey::om_code;
				break;
			}else if(!strcasecmp(optarg,"output")) {
				topmode = code_writing_monkey::om_output;
				break;
			}
			std::cerr << "Unkown '" << optarg << "' mode" << std::endl;
		case '?': /* unknown option */
		case 'h': display_usage(); exit(0); break;
		case 'V': std::cerr << VERSION << std::endl; exit(0); break;
		case 'L':
			extern const char *COPYING;
			std::cerr << COPYING << std::endl;
			exit(0); break;
		case 'o': ofile = optarg; break;
		case 'C': topmode = code_writing_monkey::om_code; break;
		case 'O': topmode = code_writing_monkey::om_output; break;
		default:
			std::cerr << "Huh?" << std::endl;
			exit(1); break;
		}
	}
#undef LS
	if((optind+1)!=argc) {
		display_usage(); exit(1);
		/* TODO: or use stdin if no parameter specified? */
	}

	std::string ifile = argv[optind];
	if(ofile.empty()) ofile = ifile+".cc";
	std::ifstream ist(ifile.c_str(),std::ios::in);
	std::ofstream ost(ofile.c_str(),std::ios::out);
	if(!ost) {
		std::cerr << "failed to open '" << ofile << "' for writing" << std::endl;
		exit(2);
	}

	int cs, act;
	char *ts, *te;
	int stack[128], top=0;
	%% write init;
	char input[512];
	int have = 0;
	char *eof = 0;
	code_writing_monkey cwm(ost);
	cwm.prologue();
	line_counting_monkey lcm(ifile.c_str(),input);
	cwm.anchor(lcm,0);
	while(!eof) {
		if(have==sizeof(input)) {
			std::cerr << "No space to read in" << std::endl;
			break;
		}
		char *p = input+have;
		int lw = sizeof(input)-have;
		int lp = ist.read(p,lw).gcount();
		char *pe = p+lp;
		eof = (lp==lw)?0:pe;
		%%write exec;
		if(cs==cliche_error) {
			std::cerr << "cliche error" << std::endl;
			break;
		}
		if(ts) {
			lcm.lineno(ts);
			te = ((char*)memmove(input,ts,have=pe-ts)) + (te-ts);
			ts = input;
		}else{
			lcm.lineno(pe);
			have = 0;
		}
		lcm.p = input;
	}
	cwm.epilogue();
	return 0;
}
/* vim:set ft=ragel ts=8 sw=8 cin si ai: */