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;
482 int quote = 0;
484 if (!in_define && block == 0) {
485 while ((c = lgetc(0)) != '{' && c != EOF) {
486 if (c == '\n')
487 file->lineno++;
490 if (c == EOF)
491 return (0);
493 newblock:
494 c = lgetc(0);
495 if (c == '{' || c == '!') {
496 if (c == '{')
497 block = '}';
498 else
499 block = c;
500 return (c);
502 if (c == '\n')
503 file->lineno++;
506 while ((c = lgetc(0)) == ' ' || c == '\t' || c == '\n') {
507 if (c == '\n')
508 file->lineno++;
511 if (c == EOF) {
512 yyerror("unterminated block");
513 return (0);
516 yylval.lineno = file->lineno;
518 if (block != 0 && c == block) {
519 if ((c = lgetc(0)) == '}') {
520 if (block == '!') {
521 block = 0;
522 return ('!');
524 block = 0;
525 return ('}');
527 lungetc(c);
528 c = block;
531 if (in_define && block == 0) {
532 if (c == '{')
533 goto newblock;
535 do {
536 if (starting) {
537 if (c == '!' || c == '{') {
538 lungetc(c);
539 lungetc('{');
540 break;
542 starting = 0;
543 lungetc(c);
544 c = '{';
545 } else if (c == '{') {
546 starting = 1;
547 continue;
550 *p++ = c;
551 if ((size_t)(p - buf) >= sizeof(buf)) {
552 yyerror("string too long");
553 return (findeol());
555 } while ((c = lgetc(0)) != EOF && c != '\n');
556 *p = '\0';
557 if (c == EOF) {
558 yyerror("unterminated block");
559 return (0);
561 if (c == '\n')
562 file->lineno++;
563 if ((yylval.v.string = strdup(buf)) == NULL)
564 err(1, "strdup");
565 return (STRING);
568 if (block == '!') {
569 do {
570 if (ending) {
571 if (c == '}') {
572 lungetc(c);
573 lungetc(block);
574 break;
576 ending = 0;
577 lungetc(c);
578 c = block;
579 } else if (c == '!') {
580 ending = 1;
581 continue;
584 *p++ = c;
585 if ((size_t)(p - buf) >= sizeof(buf)) {
586 yyerror("line too long");
587 return (findeol());
589 } while ((c = lgetc(0)) != EOF && c != '\n');
590 *p = '\0';
592 if (c == EOF) {
593 yyerror("unterminated block");
594 return (0);
596 if (c == '\n')
597 file->lineno++;
599 if ((yylval.v.string = strdup(buf)) == NULL)
600 err(1, "strdup");
601 return (STRING);
604 if (c == '|')
605 return (c);
607 do {
608 if (!quote && isspace((unsigned char)c))
609 break;
611 if (c == '"')
612 quote = !quote;
614 if (!quote && c == '|') {
615 lungetc(c);
616 break;
619 if (ending) {
620 if (c == '}') {
621 lungetc(c);
622 lungetc('}');
623 break;
625 ending = 0;
626 lungetc(c);
627 c = block;
628 } else if (!quote && c == '}') {
629 ending = 1;
630 continue;
633 *p++ = c;
634 if ((size_t)(p - buf) >= sizeof(buf)) {
635 yyerror("string too long");
636 return (findeol());
638 } while ((c = lgetc(0)) != EOF);
639 *p = '\0';
641 if (c == EOF) {
642 yyerror(quote ? "unterminated quote" : "unterminated block");
643 return (0);
645 if (c == '\n')
646 file->lineno++;
647 if ((token = lookup(buf)) == STRING)
648 if ((yylval.v.string = strdup(buf)) == NULL)
649 err(1, "strdup");
650 return (token);
653 struct file *
654 pushfile(const char *name, int secret)
656 struct file *nfile;
658 if ((nfile = calloc(1, sizeof(*nfile))) == NULL)
659 err(1, "calloc");
660 if ((nfile->name = strdup(name)) == NULL)
661 err(1, "strdup");
662 if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
663 warn("can't open %s", nfile->name);
664 free(nfile->name);
665 free(nfile);
666 return (NULL);
668 nfile->lineno = TAILQ_EMPTY(&files) ? 1 : 0;
669 nfile->ungetsize = 16;
670 nfile->ungetbuf = malloc(nfile->ungetsize);
671 if (nfile->ungetbuf == NULL)
672 err(1, "malloc");
673 TAILQ_INSERT_TAIL(&files, nfile, entry);
674 return (nfile);
677 int
678 popfile(void)
680 struct file *prev;
682 if ((prev = TAILQ_PREV(file, files, entry)) != NULL)
683 prev->errors += file->errors;
685 TAILQ_REMOVE(&files, file, entry);
686 fclose(file->stream);
687 free(file->name);
688 free(file->ungetbuf);
689 free(file);
690 file = prev;
691 return (file ? 0 : EOF);
694 int
695 parse(FILE *outfile, const char *filename)
697 fp = outfile;
699 if ((file = pushfile(filename, 0)) == 0)
700 return (-1);
701 topfile = file;
703 yyparse();
704 errors = file->errors;
705 popfile();
707 return (errors ? -1 : 0);
710 void
711 dbg(void)
713 if (nodebug)
714 return;
716 if (yylval.lineno == lastline + 1) {
717 lastline = yylval.lineno;
718 return;
720 lastline = yylval.lineno;
722 fprintf(fp, "#line %d ", yylval.lineno);
723 printq(file->name);
724 putc('\n', fp);
727 void
728 printq(const char *str)
730 putc('"', fp);
731 for (; *str; ++str) {
732 if (*str == '"')
733 putc('\\', fp);
734 putc(*str, fp);
736 putc('"', fp);