aboutsummaryrefslogtreecommitdiff
path: root/mktpl/mktpl.lex
blob: e530e451d883b0b05413499c4efee3c3abbc0be7 (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
%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>.		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();
}

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

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

void
text()
{
	char *t;
	
	printf("printf(\"");
	for(t = buf; *t; t++){
		if(*t == '\\') printf("\\\\");
		else if(*t == '"') printf("\\\"");
		else if(*t == '\n') printf("\\n");
		else printf("%c", *t);
	}
	printf("\");\n");
	len = 0;
}

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