Blob


1 /*
2 * Copyright (c) 2022 Omar Polo <op@openbsd.org>
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 WHILE
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);
276 | '{' WHILE stringy '}' {
277 fprintf(fp, "while (%s) {\n", $3);
278 free($3);
279 } body end {
280 fputs("}\n", fp);
284 end : '{' END '}'
287 finally : '{' FINALLY '}' {
288 dbg();
289 fputs("err:\n", fp);
290 } verbatims
293 string : STRING string {
294 if (asprintf(&$$, "%s %s", $1, $2) == -1)
295 err(1, "asprintf");
296 free($1);
297 free($2);
299 | STRING
302 stringy : STRING
303 | STRING stringy {
304 if (asprintf(&$$, "%s %s", $1, $2) == -1)
305 err(1, "asprintf");
306 free($1);
307 free($2);
309 | '|' stringy {
310 if (asprintf(&$$, "|%s", $2) == -1)
311 err(1, "asprintf");
312 free($2);
316 %%
318 struct keywords {
319 const char *k_name;
320 int k_val;
321 };
323 int
324 yyerror(const char *fmt, ...)
326 va_list ap;
327 char *msg;
329 file->errors++;
330 va_start(ap, fmt);
331 if (vasprintf(&msg, fmt, ap) == -1)
332 err(1, "yyerror vasprintf");
333 va_end(ap);
334 fprintf(stderr, "%s:%d: %s\n", file->name, yylval.lineno, msg);
335 free(msg);
336 return (0);
339 int
340 kw_cmp(const void *k, const void *e)
342 return (strcmp(k, ((const struct keywords *)e)->k_name));
345 int
346 lookup(char *s)
348 /* this has to be sorted always */
349 static const struct keywords keywords[] = {
350 { "define", DEFINE },
351 { "else", ELSE },
352 { "end", END },
353 { "finally", FINALLY },
354 { "for", FOR },
355 { "if", IF },
356 { "include", INCLUDE },
357 { "printf", PRINTF },
358 { "render", RENDER },
359 { "tailq-foreach", TQFOREACH },
360 { "unsafe", UNSAFE },
361 { "urlescape", URLESCAPE },
362 { "while", WHILE },
363 };
364 const struct keywords *p;
366 p = bsearch(s, keywords, nitems(keywords), sizeof(keywords[0]),
367 kw_cmp);
369 if (p)
370 return (p->k_val);
371 else
372 return (STRING);
375 #define START_EXPAND 1
376 #define DONE_EXPAND 2
378 static int expanding;
380 int
381 igetc(void)
383 int c;
385 while (1) {
386 if (file->ungetpos > 0)
387 c = file->ungetbuf[--file->ungetpos];
388 else
389 c = getc(file->stream);
391 if (c == START_EXPAND)
392 expanding = 1;
393 else if (c == DONE_EXPAND)
394 expanding = 0;
395 else
396 break;
398 return (c);
401 int
402 lgetc(int quotec)
404 int c;
406 if (quotec) {
407 if ((c = igetc()) == EOF) {
408 yyerror("reached end of filewhile parsing "
409 "quoted string");
410 if (file == topfile || popfile() == EOF)
411 return (EOF);
412 return (quotec);
414 return (c);
417 c = igetc();
418 if (c == '\t' || c == ' ') {
419 /* Compress blanks to a sigle space. */
420 do {
421 c = getc(file->stream);
422 } while (c == '\t' || c == ' ');
423 ungetc(c, file->stream);
424 c = ' ';
427 if (c == EOF) {
428 /*
429 * Fake EOL when hit EOF for the first time. This gets line
430 * count right if last line in included file is syntactically
431 * invalid and has no newline.
432 */
433 if (file->eof_reached == 0) {
434 file->eof_reached = 1;
435 return ('\n');
437 while (c == EOF) {
438 if (file == topfile || popfile() == EOF)
439 return (EOF);
440 c = igetc();
443 return (c);
446 void
447 lungetc(int c)
449 if (c == EOF)
450 return;
452 if (file->ungetpos >= file->ungetsize) {
453 void *p = reallocarray(file->ungetbuf, file->ungetsize, 2);
454 if (p == NULL)
455 err(1, "reallocarray");
456 file->ungetbuf = p;
457 file->ungetsize *= 2;
459 file->ungetbuf[file->ungetpos++] = c;
462 int
463 findeol(void)
465 int c;
467 /* skip to either EOF or the first real EOL */
468 while (1) {
469 c = lgetc(0);
470 if (c == '\n') {
471 file->lineno++;
472 break;
474 if (c == EOF)
475 break;
477 return (ERROR);
480 int
481 yylex(void)
483 char buf[8096];
484 char *p = buf;
485 int c;
486 int token;
487 int starting = 0;
488 int ending = 0;
489 int quote = 0;
491 if (!in_define && block == 0) {
492 while ((c = lgetc(0)) != '{' && c != EOF) {
493 if (c == '\n')
494 file->lineno++;
497 if (c == EOF)
498 return (0);
500 newblock:
501 c = lgetc(0);
502 if (c == '{' || c == '!') {
503 if (c == '{')
504 block = '}';
505 else
506 block = c;
507 return (c);
509 if (c == '\n')
510 file->lineno++;
513 while ((c = lgetc(0)) == ' ' || c == '\t' || c == '\n') {
514 if (c == '\n')
515 file->lineno++;
518 if (c == EOF) {
519 yyerror("unterminated block");
520 return (0);
523 yylval.lineno = file->lineno;
525 if (block != 0 && c == block) {
526 if ((c = lgetc(0)) == '}') {
527 if (block == '!') {
528 block = 0;
529 return ('!');
531 block = 0;
532 return ('}');
534 lungetc(c);
535 c = block;
538 if (in_define && block == 0) {
539 if (c == '{')
540 goto newblock;
542 do {
543 if (starting) {
544 if (c == '!' || c == '{') {
545 lungetc(c);
546 lungetc('{');
547 break;
549 starting = 0;
550 lungetc(c);
551 c = '{';
552 } else if (c == '{') {
553 starting = 1;
554 continue;
555 } else if (c == '\n')
556 break;
558 *p++ = c;
559 if ((size_t)(p - buf) >= sizeof(buf)) {
560 yyerror("string too long");
561 return (findeol());
563 } while ((c = lgetc(0)) != EOF);
564 *p = '\0';
565 if (c == EOF) {
566 yyerror("unterminated block");
567 return (0);
569 if (c == '\n')
570 file->lineno++;
571 if ((yylval.v.string = strdup(buf)) == NULL)
572 err(1, "strdup");
573 return (STRING);
576 if (block == '!') {
577 do {
578 if (ending) {
579 if (c == '}') {
580 lungetc(c);
581 lungetc(block);
582 break;
584 ending = 0;
585 lungetc(c);
586 c = block;
587 } else if (c == '!') {
588 ending = 1;
589 continue;
590 } else if (c == '\n')
591 break;
593 *p++ = c;
594 if ((size_t)(p - buf) >= sizeof(buf)) {
595 yyerror("line too long");
596 return (findeol());
598 } while ((c = lgetc(0)) != EOF);
599 *p = '\0';
601 if (c == EOF) {
602 yyerror("unterminated block");
603 return (0);
605 if (c == '\n')
606 file->lineno++;
608 if ((yylval.v.string = strdup(buf)) == NULL)
609 err(1, "strdup");
610 return (STRING);
613 if (c == '|')
614 return (c);
616 do {
617 if (!quote && isspace((unsigned char)c))
618 break;
620 if (c == '"')
621 quote = !quote;
623 if (!quote && c == '|') {
624 lungetc(c);
625 break;
628 if (ending) {
629 if (c == '}') {
630 lungetc(c);
631 lungetc('}');
632 break;
634 ending = 0;
635 lungetc(c);
636 c = block;
637 } else if (!quote && c == '}') {
638 ending = 1;
639 continue;
642 *p++ = c;
643 if ((size_t)(p - buf) >= sizeof(buf)) {
644 yyerror("string too long");
645 return (findeol());
647 } while ((c = lgetc(0)) != EOF);
648 *p = '\0';
650 if (c == EOF) {
651 yyerror(quote ? "unterminated quote" : "unterminated block");
652 return (0);
654 if (c == '\n')
655 file->lineno++;
656 if ((token = lookup(buf)) == STRING)
657 if ((yylval.v.string = strdup(buf)) == NULL)
658 err(1, "strdup");
659 return (token);
662 struct file *
663 pushfile(const char *name, int secret)
665 struct file *nfile;
667 if ((nfile = calloc(1, sizeof(*nfile))) == NULL)
668 err(1, "calloc");
669 if ((nfile->name = strdup(name)) == NULL)
670 err(1, "strdup");
671 if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
672 warn("can't open %s", nfile->name);
673 free(nfile->name);
674 free(nfile);
675 return (NULL);
677 nfile->lineno = TAILQ_EMPTY(&files) ? 1 : 0;
678 nfile->ungetsize = 16;
679 nfile->ungetbuf = malloc(nfile->ungetsize);
680 if (nfile->ungetbuf == NULL)
681 err(1, "malloc");
682 TAILQ_INSERT_TAIL(&files, nfile, entry);
683 return (nfile);
686 int
687 popfile(void)
689 struct file *prev;
691 if ((prev = TAILQ_PREV(file, files, entry)) != NULL)
692 prev->errors += file->errors;
694 TAILQ_REMOVE(&files, file, entry);
695 fclose(file->stream);
696 free(file->name);
697 free(file->ungetbuf);
698 free(file);
699 file = prev;
700 return (file ? 0 : EOF);
703 int
704 parse(FILE *outfile, const char *filename)
706 fp = outfile;
708 if ((file = pushfile(filename, 0)) == 0)
709 return (-1);
710 topfile = file;
712 yyparse();
713 errors = file->errors;
714 popfile();
716 return (errors ? -1 : 0);
719 void
720 dbg(void)
722 if (nodebug)
723 return;
725 if (yylval.lineno == lastline + 1) {
726 lastline = yylval.lineno;
727 return;
729 lastline = yylval.lineno;
731 fprintf(fp, "#line %d ", yylval.lineno);
732 printq(file->name);
733 putc('\n', fp);
736 void
737 printq(const char *str)
739 putc('"', fp);
740 for (; *str; ++str) {
741 if (*str == '"')
742 putc('\\', fp);
743 putc(*str, fp);
745 putc('"', fp);