aboutsummaryrefslogtreecommitdiff
path: root/mktpl/mktpl.lex
blob: 296cc0b704a625f629534c6c6e2a953763e02baf (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
%x PRNT
%x EVAL

	#include <err.h>
	#include <stdio.h>
	#include <stdlib.h>
	#include <string.h>

	void apnd();
	void eval();
	void text();
	void prnt();

	char *buf;
	int len;
	int sz;

%%
(.|\n)		apnd();
\<%=		text(); BEGIN(PRNT);
\<%[^=]		text(); BEGIN(EVAL);

<PRNT>(.|\n)	apnd();
<PRNT>%\>	prnt(); BEGIN(0);

<EVAL>(.|\n)	apnd();
<EVAL>%\>	eval(); BEGIN(0);

<PRNT><<EOF>>	prnt(); yyterminate();
<EVAL><<EOF>>	eval(); yyterminate();
<<EOF>>		text(); yyterminate();
%%

int
main(int argc, char *argv[])
{
	len = 0;
	sz = 512;
	if(!(buf = malloc(sz)))
		err(1, "malloc");

	yylex();
	return 0;
}

void
apnd()
{
	if(len+1 > sz){
		sz += 512;
		if(!(buf = realloc(buf, sz)))
			err(1, "realloc");
	}

	buf[len++] = *yytext;
}

void
eval()
{
	printf("%.*s\n", len, buf);
	len = 0;
}

void
text()
{
	int i, ofs;

	if(!len) return;

	printf("printf(\"");
	for(i = ofs = 0; i < len; i++){
		/*
		 * C89 compilers need only support 509-length
		 * string literals.
		 */
		if(i-ofs >= 509){
			printf("\");\nprintf(\"");
			ofs = i;
		}
		if(buf[i] == '\\') printf("\\\\");
		else if(buf[i] == '"') printf("\\\"");
		else if(buf[i] == '\n') printf("\\n");
		else printf("%c", buf[i]);
	}
	printf("\");\n");
	len = 0;
}

void
prnt()
{
	printf("printf(\"%%s\", %.*s);\n", len, buf);
	len = 0;
}