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 rigchtif last line 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;
557 *p++ = c;
558 if ((size_t)(p - buf) >= sizeof(buf)) {
559 yyerror("string too long");
560 return (findeol());
562 } while ((c = lgetc(0)) != EOF && c != '\n');
563 *p = '\0';
564 if (c == EOF) {
565 yyerror("unterminated block");
566 return (0);
568 if (c == '\n')
569 file->lineno++;
570 if ((yylval.v.string = strdup(buf)) == NULL)
571 err(1, "strdup");
572 return (STRING);
575 if (block == '!') {
576 do {
577 if (ending) {
578 if (c == '}') {
579 lungetc(c);
580 lungetc(block);
581 break;
583 ending = 0;
584 lungetc(c);
585 c = block;
586 } else if (c == '!') {
587 ending = 1;
588 continue;
591 *p++ = c;
592 if ((size_t)(p - buf) >= sizeof(buf)) {
593 yyerror("line too long");
594 return (findeol());
596 } while ((c = lgetc(0)) != EOF && c != '\n');
597 *p = '\0';
599 if (c == EOF) {
600 yyerror("unterminated block");
601 return (0);
603 if (c == '\n')
604 file->lineno++;
606 if ((yylval.v.string = strdup(buf)) == NULL)
607 err(1, "strdup");
608 return (STRING);
611 if (c == '|')
612 return (c);
614 do {
615 if (!quote && isspace((unsigned char)c))
616 break;
618 if (c == '"')
619 quote = !quote;
621 if (!quote && c == '|') {
622 lungetc(c);
623 break;
626 if (ending) {
627 if (c == '}') {
628 lungetc(c);
629 lungetc('}');
630 break;
632 ending = 0;
633 lungetc(c);
634 c = block;
635 } else if (!quote && c == '}') {
636 ending = 1;
637 continue;
640 *p++ = c;
641 if ((size_t)(p - buf) >= sizeof(buf)) {
642 yyerror("string too long");
643 return (findeol());
645 } while ((c = lgetc(0)) != EOF);
646 *p = '\0';
648 if (c == EOF) {
649 yyerror(quote ? "unterminated quote" : "unterminated block");
650 return (0);
652 if (c == '\n')
653 file->lineno++;
654 if ((token = lookup(buf)) == STRING)
655 if ((yylval.v.string = strdup(buf)) == NULL)
656 err(1, "strdup");
657 return (token);
660 struct file *
661 pushfile(const char *name, int secret)
663 struct file *nfile;
665 if ((nfile = calloc(1, sizeof(*nfile))) == NULL)
666 err(1, "calloc");
667 if ((nfile->name = strdup(name)) == NULL)
668 err(1, "strdup");
669 if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
670 warn("can't open %s", nfile->name);
671 free(nfile->name);
672 free(nfile);
673 return (NULL);
675 nfile->lineno = TAILQ_EMPTY(&files) ? 1 : 0;
676 nfile->ungetsize = 16;
677 nfile->ungetbuf = malloc(nfile->ungetsize);
678 if (nfile->ungetbuf == NULL)
679 err(1, "malloc");
680 TAILQ_INSERT_TAIL(&files, nfile, entry);
681 return (nfile);
684 int
685 popfile(void)
687 struct file *prev;
689 if ((prev = TAILQ_PREV(file, files, entry)) != NULL)
690 prev->errors += file->errors;
692 TAILQ_REMOVE(&files, file, entry);
693 fclose(file->stream);
694 free(file->name);
695 free(file->ungetbuf);
696 free(file);
697 file = prev;
698 return (file ? 0 : EOF);
701 int
702 parse(FILE *outfile, const char *filename)
704 fp = outfile;
706 if ((file = pushfile(filename, 0)) == 0)
707 return (-1);
708 topfile = file;
710 yyparse();
711 errors = file->errors;
712 popfile();
714 return (errors ? -1 : 0);
717 void
718 dbg(void)
720 if (nodebug)
721 return;
723 if (yylval.lineno == lastline + 1) {
724 lastline = yylval.lineno;
725 return;
727 lastline = yylval.lineno;
729 fprintf(fp, "#line %d ", yylval.lineno);
730 printq(file->name);
731 putc('\n', fp);
734 void
735 printq(const char *str)
737 putc('"', fp);
738 for (; *str; ++str) {
739 if (*str == '"')
740 putc('\\', fp);
741 putc(*str, fp);
743 putc('"', fp);