Blob


1 /*
2 * Copyright (c) 2022 Omar Polo <op@omarpolo.com>
3 * Copyright (c) 2007-2016 Reyk Floeter <reyk@openbsd.org>
4 * Copyright (c) 2004, 2005 Esben Norby <norby@openbsd.org>
5 * Copyright (c) 2004 Ryan McBride <mcbride@openbsd.org>
6 * Copyright (c) 2002, 2003, 2004 Henning Brauer <henning@openbsd.org>
7 * Copyright (c) 2001 Markus Friedl. All rights reserved.
8 * Copyright (c) 2001 Daniel Hartmeier. All rights reserved.
9 * Copyright (c) 2001 Theo de Raadt. All rights reserved.
10 *
11 * Permission to use, copy, modify, and distribute this software for any
12 * purpose with or without fee is hereby granted, provided that the above
13 * copyright notice and this permission notice appear in all copies.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
16 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
17 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
18 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
21 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22 */
24 %{
26 #include <sys/queue.h>
28 #include <ctype.h>
29 #include <err.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <stdint.h>
34 #include <string.h>
35 #include <unistd.h>
37 #ifndef nitems
38 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
39 #endif
41 TAILQ_HEAD(files, file) files = TAILQ_HEAD_INITIALIZER(files);
42 static struct file {
43 TAILQ_ENTRY(file) entry;
44 FILE *stream;
45 char *name;
46 size_t ungetpos;
47 size_t ungetsize;
48 unsigned char *ungetbuf;
49 int eof_reached;
50 int lineno;
51 int errors;
52 } *file, *topfile;
53 int parse(FILE *, const char *);
54 struct file *pushfile(const char *, int);
55 int popfile(void);
56 int yyparse(void);
57 int yylex(void);
58 int yyerror(const char *, ...)
59 __attribute__((__format__ (printf, 1, 2)))
60 __attribute__((__nonnull__ (1)));
61 int kw_cmp(const void *, const void *);
62 int lookup(char *);
63 int igetc(void);
64 int lgetc(int);
65 void lungetc(int);
66 int findeol(void);
68 void dbg(void);
69 void printq(const char *);
71 extern int nodebug;
73 static FILE *fp;
75 static int block;
76 static int in_define;
77 static int errors;
78 static int lastline = -1;
80 typedef struct {
81 union {
82 char *string;
83 } v;
84 int lineno;
85 } YYSTYPE;
87 %}
89 %token DEFINE ELSE END ERROR FINALLY FOR IF INCLUDE PRINTF
90 %token RENDER TQFOREACH UNSAFE URLESCAPE
91 %token <v.string> STRING
92 %type <v.string> string
93 %type <v.string> stringy
95 %%
97 grammar : /* empty */
98 | grammar include
99 | grammar verbatim
100 | grammar block
101 | grammar error { file->errors++; }
104 include : INCLUDE STRING {
105 struct file *nfile;
107 if ((nfile = pushfile($2, 0)) == NULL) {
108 yyerror("failed to include file %s", $2);
109 free($2);
110 YYERROR;
112 free($2);
114 file = nfile;
115 lungetc('\n');
119 verbatim : '!' verbatim1 '!' {
120 if (in_define) {
121 /* TODO: check template status and exit in case */
126 verbatim1 : /* empty */
127 | verbatim1 STRING {
128 if (*$2 != '\0') {
129 dbg();
130 fprintf(fp, "%s\n", $2);
132 free($2);
136 verbatims : /* empty */
137 | verbatims verbatim
140 raw : STRING {
141 dbg();
142 fprintf(fp, "if ((tp_ret = tp->tp_puts(tp, ");
143 printq($1);
144 fputs(")) == -1) goto err;\n", fp);
146 free($1);
150 block : define body end {
151 fputs("err:\n", fp);
152 fputs("return tp_ret;\n", fp);
153 fputs("}\n", fp);
154 in_define = 0;
156 | define body finally end {
157 fputs("return tp_ret;\n", fp);
158 fputs("}\n", fp);
159 in_define = 0;
163 define : '{' DEFINE string '}' {
164 in_define = 1;
166 dbg();
167 fprintf(fp, "int\n%s\n{\n", $3);
168 fputs("int tp_ret = 0;\n", fp);
170 free($3);
174 body : /* empty */
175 | body verbatim
176 | body raw
177 | body special
180 special : '{' RENDER string '}' {
181 dbg();
182 fprintf(fp, "if ((tp_ret = %s) == -1) goto err;\n",
183 $3);
184 free($3);
186 | printf
187 | if body endif { fputs("}\n", fp); }
188 | loop
189 | '{' string '|' UNSAFE '}' {
190 dbg();
191 fprintf(fp,
192 "if ((tp_ret = tp->tp_puts(tp, %s)) == -1)\n",
193 $2);
194 fputs("goto err;\n", fp);
195 free($2);
197 | '{' string '|' URLESCAPE '}' {
198 dbg();
199 fprintf(fp,
200 "if ((tp_ret = tp_urlescape(tp, %s)) == -1)\n",
201 $2);
202 fputs("goto err;\n", fp);
203 free($2);
205 | '{' string '}' {
206 dbg();
207 fprintf(fp,
208 "if ((tp_ret = tp->tp_escape(tp, %s)) == -1)\n",
209 $2);
210 fputs("goto err;\n", fp);
211 free($2);
215 printf : '{' PRINTF {
216 dbg();
217 fprintf(fp, "if (asprintf(&tp->tp_tmp, ");
218 } printfargs '}' {
219 fputs(") == -1)\n", fp);
220 fputs("goto err;\n", fp);
221 fputs("if ((tp_ret = tp->tp_escape(tp, tp->tp_tmp)) "
222 "== -1)\n", fp);
223 fputs("goto err;\n", fp);
224 fputs("free(tp->tp_tmp);\n", fp);
225 fputs("tp->tp_tmp = NULL;\n", fp);
229 printfargs : /* empty */
230 | printfargs STRING {
231 fprintf(fp, " %s", $2);
232 free($2);
236 if : '{' IF stringy '}' {
237 dbg();
238 fprintf(fp, "if (%s) {\n", $3);
239 free($3);
243 endif : end
244 | else body end
245 | elsif body endif
248 elsif : '{' ELSE IF stringy '}' {
249 dbg();
250 fprintf(fp, "} else if (%s) {\n", $4);
251 free($4);
255 else : '{' ELSE '}' {
256 dbg();
257 fputs("} else {\n", fp);
261 loop : '{' FOR stringy '}' {
262 fprintf(fp, "for (%s) {\n", $3);
263 free($3);
264 } body end {
265 fputs("}\n", fp);
267 | '{' TQFOREACH STRING STRING STRING '}' {
268 fprintf(fp, "TAILQ_FOREACH(%s, %s, %s) {\n",
269 $3, $4, $5);
270 free($3);
271 free($4);
272 free($5);
273 } body end {
274 fputs("}\n", fp);
278 end : '{' END '}'
281 finally : '{' FINALLY '}' {
282 dbg();
283 fputs("err:\n", fp);
284 } verbatims
287 string : STRING string {
288 if (asprintf(&$$, "%s %s", $1, $2) == -1)
289 err(1, "asprintf");
290 free($1);
291 free($2);
293 | STRING
296 stringy : STRING
297 | STRING stringy {
298 if (asprintf(&$$, "%s %s", $1, $2) == -1)
299 err(1, "asprintf");
300 free($1);
301 free($2);
303 | '|' stringy {
304 if (asprintf(&$$, "|%s", $2) == -1)
305 err(1, "asprintf");
306 free($2);
310 %%
312 struct keywords {
313 const char *k_name;
314 int k_val;
315 };
317 int
318 yyerror(const char *fmt, ...)
320 va_list ap;
321 char *msg;
323 file->errors++;
324 va_start(ap, fmt);
325 if (vasprintf(&msg, fmt, ap) == -1)
326 err(1, "yyerror vasprintf");
327 va_end(ap);
328 fprintf(stderr, "%s:%d: %s\n", file->name, yylval.lineno, msg);
329 free(msg);
330 return (0);
333 int
334 kw_cmp(const void *k, const void *e)
336 return (strcmp(k, ((const struct keywords *)e)->k_name));
339 int
340 lookup(char *s)
342 /* this has to be sorted always */
343 static const struct keywords keywords[] = {
344 { "define", DEFINE },
345 { "else", ELSE },
346 { "end", END },
347 { "finally", FINALLY },
348 { "for", FOR },
349 { "if", IF },
350 { "include", INCLUDE },
351 { "printf", PRINTF },
352 { "render", RENDER },
353 { "tailq-foreach", TQFOREACH },
354 { "unsafe", UNSAFE },
355 { "urlescape", URLESCAPE },
356 };
357 const struct keywords *p;
359 p = bsearch(s, keywords, nitems(keywords), sizeof(keywords[0]),
360 kw_cmp);
362 if (p)
363 return (p->k_val);
364 else
365 return (STRING);
368 #define START_EXPAND 1
369 #define DONE_EXPAND 2
371 static int expanding;
373 int
374 igetc(void)
376 int c;
378 while (1) {
379 if (file->ungetpos > 0)
380 c = file->ungetbuf[--file->ungetpos];
381 else
382 c = getc(file->stream);
384 if (c == START_EXPAND)
385 expanding = 1;
386 else if (c == DONE_EXPAND)
387 expanding = 0;
388 else
389 break;
391 return (c);
394 int
395 lgetc(int quotec)
397 int c;
399 if (quotec) {
400 if ((c = igetc()) == EOF) {
401 yyerror("reached end of filewhile parsing "
402 "quoted string");
403 if (file == topfile || popfile() == EOF)
404 return (EOF);
405 return (quotec);
407 return (c);
410 c = igetc();
411 if (c == '\t' || c == ' ') {
412 /* Compress blanks to a sigle space. */
413 do {
414 c = getc(file->stream);
415 } while (c == '\t' || c == ' ');
416 ungetc(c, file->stream);
417 c = ' ';
420 if (c == EOF) {
421 /*
422 * Fake EOL when hit EOF for the first time. This gets line
423 * count rigchtif last line included file is syntactically
424 * invalid and has no newline.
425 */
426 if (file->eof_reached == 0) {
427 file->eof_reached = 1;
428 return ('\n');
430 while (c == EOF) {
431 if (file == topfile || popfile() == EOF)
432 return (EOF);
433 c = igetc();
436 return (c);
439 void
440 lungetc(int c)
442 if (c == EOF)
443 return;
445 if (file->ungetpos >= file->ungetsize) {
446 void *p = reallocarray(file->ungetbuf, file->ungetsize, 2);
447 if (p == NULL)
448 err(1, "reallocarray");
449 file->ungetbuf = p;
450 file->ungetsize *= 2;
452 file->ungetbuf[file->ungetpos++] = c;
455 int
456 findeol(void)
458 int c;
460 /* skip to either EOF or the first real EOL */
461 while (1) {
462 c = lgetc(0);
463 if (c == '\n') {
464 file->lineno++;
465 break;
467 if (c == EOF)
468 break;
470 return (ERROR);
473 int
474 yylex(void)
476 char buf[8096];
477 char *p = buf;
478 int c;
479 int token;
480 int starting = 0;
481 int ending = 0;
483 if (!in_define && block == 0) {
484 while ((c = lgetc(0)) != '{' && c != EOF) {
485 if (c == '\n')
486 file->lineno++;
489 if (c == EOF)
490 return (0);
492 newblock:
493 c = lgetc(0);
494 if (c == '{' || c == '!') {
495 if (c == '{')
496 block = '}';
497 else
498 block = c;
499 return (c);
501 if (c == '\n')
502 file->lineno++;
505 while ((c = lgetc(0)) == ' ' || c == '\t' || c == '\n') {
506 if (c == '\n')
507 file->lineno++;
510 if (c == EOF) {
511 yyerror("unterminated block");
512 return (0);
515 yylval.lineno = file->lineno;
517 if (block != 0 && c == block) {
518 if ((c = lgetc(0)) == '}') {
519 if (block == '!') {
520 block = 0;
521 return ('!');
523 block = 0;
524 return ('}');
526 lungetc(c);
527 c = block;
530 if (in_define && block == 0) {
531 if (c == '{')
532 goto newblock;
534 do {
535 if (starting) {
536 if (c == '!' || c == '{') {
537 lungetc(c);
538 lungetc('{');
539 break;
541 starting = 0;
542 lungetc(c);
543 c = '{';
544 } else if (c == '{') {
545 starting = 1;
546 continue;
549 *p++ = c;
550 if ((size_t)(p - buf) >= sizeof(buf)) {
551 yyerror("string too long");
552 return (findeol());
554 } while ((c = lgetc(0)) != EOF && c != '\n');
555 *p = '\0';
556 if (c == EOF) {
557 yyerror("unterminated block");
558 return (0);
560 if (c == '\n')
561 file->lineno++;
562 if ((yylval.v.string = strdup(buf)) == NULL)
563 err(1, "strdup");
564 return (STRING);
567 if (block == '!') {
568 do {
569 if (ending) {
570 if (c == '}') {
571 lungetc(c);
572 lungetc(block);
573 break;
575 ending = 0;
576 lungetc(c);
577 c = block;
578 } else if (c == '!') {
579 ending = 1;
580 continue;
583 *p++ = c;
584 if ((size_t)(p - buf) >= sizeof(buf)) {
585 yyerror("line too long");
586 return (findeol());
588 } while ((c = lgetc(0)) != EOF && c != '\n');
589 *p = '\0';
591 if (c == EOF) {
592 yyerror("unterminated block");
593 return (0);
595 if (c == '\n')
596 file->lineno++;
598 if ((yylval.v.string = strdup(buf)) == NULL)
599 err(1, "strdup");
600 return (STRING);
603 if (c == '|')
604 return (c);
606 do {
607 if (c == '|') {
608 lungetc(c);
609 break;
612 if (ending) {
613 if (c == '}') {
614 lungetc(c);
615 lungetc('}');
616 break;
618 ending = 0;
619 lungetc(c);
620 c = block;
621 } else if (c == '}') {
622 ending = 1;
623 continue;
626 *p++ = c;
627 if ((size_t)(p - buf) >= sizeof(buf)) {
628 yyerror("string too long");
629 return (findeol());
631 } while ((c = lgetc(0)) != EOF && !isspace((unsigned char)c));
632 *p = '\0';
634 if (c == EOF) {
635 yyerror("unterminated block");
636 return (0);
638 if (c == '\n')
639 file->lineno++;
640 if ((token = lookup(buf)) == STRING)
641 if ((yylval.v.string = strdup(buf)) == NULL)
642 err(1, "strdup");
643 return (token);
646 struct file *
647 pushfile(const char *name, int secret)
649 struct file *nfile;
651 if ((nfile = calloc(1, sizeof(*nfile))) == NULL)
652 err(1, "calloc");
653 if ((nfile->name = strdup(name)) == NULL)
654 err(1, "strdup");
655 if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
656 warn("can't open %s", nfile->name);
657 free(nfile->name);
658 free(nfile);
659 return (NULL);
661 nfile->lineno = TAILQ_EMPTY(&files) ? 1 : 0;
662 nfile->ungetsize = 16;
663 nfile->ungetbuf = malloc(nfile->ungetsize);
664 if (nfile->ungetbuf == NULL)
665 err(1, "malloc");
666 TAILQ_INSERT_TAIL(&files, nfile, entry);
667 return (nfile);
670 int
671 popfile(void)
673 struct file *prev;
675 if ((prev = TAILQ_PREV(file, files, entry)) != NULL)
676 prev->errors += file->errors;
678 TAILQ_REMOVE(&files, file, entry);
679 fclose(file->stream);
680 free(file->name);
681 free(file->ungetbuf);
682 free(file);
683 file = prev;
684 return (file ? 0 : EOF);
687 int
688 parse(FILE *outfile, const char *filename)
690 fp = outfile;
692 if ((file = pushfile(filename, 0)) == 0)
693 return (-1);
694 topfile = file;
696 yyparse();
697 errors = file->errors;
698 popfile();
700 return (errors ? -1 : 0);
703 void
704 dbg(void)
706 if (nodebug)
707 return;
709 if (yylval.lineno == lastline + 1) {
710 lastline = yylval.lineno;
711 return;
713 lastline = yylval.lineno;
715 fprintf(fp, "#line %d ", yylval.lineno);
716 printq(file->name);
717 putc('\n', fp);
720 void
721 printq(const char *str)
723 putc('"', fp);
724 for (; *str; ++str) {
725 if (*str == '"')
726 putc('\\', fp);
727 putc(*str, fp);
729 putc('"', fp);