Blob


1 /*
2 * Much of the design is taken from doas (parse.y rev 1.29)
3 *
4 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
5 * Copyright (c) 2015 Ted Unangst <tedu@openbsd.org>
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 *
19 */
21 %{
23 #include "compat.h"
25 #include <assert.h>
26 #include <ctype.h>
27 #include <limits.h>
28 #include <ncurses.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
34 #include "cmd.h"
35 #include "defaults.h"
36 #include "iri.h"
37 #include "keymap.h"
38 #include "telescope.h"
39 #include "utils.h"
40 #include "xwrapper.h"
42 typedef struct {
43 union {
44 char *str;
45 int num;
46 };
47 int lineno;
48 int colno;
49 } yystype;
50 #define YYSTYPE yystype
52 static char *current_style;
53 static int color_type;
55 static const char *path;
57 FILE *yyfp;
59 int parse_errors = 0;
61 static void yyerror(const char *, ...);
62 static int yylex(void);
63 static void setprfx(const char *, const char *);
64 static void setvari(char *, int);
65 static void setvars(char *, char *);
66 static void setvarb(char *, int);
67 static int colorname(const char *);
68 static void setcolor(const char *, const char *, const char *);
69 static int attrname(const char *);
70 static void setattr(char *, char *, char *);
71 static void add_proxy(char *, char *);
72 static void bindkey(const char *, const char *, const char *);
73 static void do_parseconfig(const char *, int);
75 %}
77 %token ATTR
78 %token BIND BG
79 %token CONT
80 %token FG
81 %token PRFX PROXY
82 %token SET STYLE
83 %token UNBIND
84 %token VIA
86 /* Sigh... they conflict with ncurses TRUE and FALSE */
87 %token TOK_TRUE TOK_FALSE
89 %token <str> STRING
90 %token <num> NUMBER
91 %type <num> bool
93 %%
95 grammar : /* empty */
96 | grammar '\n'
97 | grammar rule '\n'
98 | error '\n'
99 ;
101 bool : TOK_TRUE { $$ = 1; }
102 | TOK_FALSE { $$ = 0; }
105 rule : set
106 | style {
107 free(current_style);
108 current_style = NULL;
110 | bind
111 | unbind
112 | proxy
115 set : SET STRING '=' STRING { setvars($2, $4); }
116 | SET STRING '=' NUMBER { setvari($2, $4); }
117 | SET STRING '=' bool { setvarb($2, $4); }
120 style : STYLE STRING { current_style = $2; } stylespec ;
121 stylespec : styleopt | '{' optnl styleopts '}' ;
123 styleopts : /* empty */
124 | styleopts styleopt optnl
127 styleopt : PRFX STRING { setprfx($2, $2); }
128 | PRFX STRING STRING { setprfx($2, $3); }
129 | BG { color_type = BG; } colorspec
130 | FG { color_type = FG; } colorspec
131 | ATTR attr
134 colorspec : STRING { setcolor($1, $1, $1); free($1); }
135 | STRING STRING { setcolor($1, $2, $1); free($1); free($2); }
136 | STRING STRING STRING { setcolor($1, $2, $3); free($1); free($2); free($3); }
139 attr : STRING { setattr($1, $1, $1); free($1); }
140 | STRING STRING { setattr($1, $2, $1); free($1); free($2); }
141 | STRING STRING STRING { setattr($1, $2, $3); free($1); free($2); free($3); }
144 bind : BIND STRING STRING STRING { bindkey($2, $3, $4); free($2); free($3); free($4); }
147 unbind : UNBIND STRING STRING { yyerror("TODO: unbind %s %s", $2, $3); }
150 proxy : PROXY STRING VIA STRING { add_proxy($2, $4); free($4); }
153 optnl : '\n' optnl /* zero or more newlines */
154 | /* empty */
157 %%
159 void
160 yyerror(const char *fmt, ...)
162 va_list va;
164 fprintf(stderr, "%s:%d ", path, yylval.lineno+1);
165 va_start(va, fmt);
166 vfprintf(stderr, fmt, va);
167 va_end(va);
168 fprintf(stderr, "\n");
169 parse_errors++;
172 static struct keyword {
173 const char *word;
174 int token;
175 } keywords[] = {
176 { "attr", ATTR },
177 { "bg", BG },
178 { "bind", BIND },
179 { "cont", CONT },
180 { "false", TOK_FALSE },
181 { "fg", FG },
182 { "prefix", PRFX },
183 { "proxy", PROXY },
184 { "set", SET },
185 { "style", STYLE },
186 { "true", TOK_TRUE },
187 { "unbind", UNBIND },
188 { "via", VIA },
189 };
191 int
192 yylex(void)
194 char buf[1024], *ebuf, *p, *str;
195 const char *errstr;
196 int c, quotes = 0, escape = 0, qpos = -1, nonkw = 0;
197 size_t i;
199 p = buf;
200 ebuf = buf + sizeof(buf);
202 repeat:
203 /* skip whitespace first */
204 for (c = getc(yyfp); c == ' ' || c == '\t' || c == '\f'; c = getc(yyfp))
205 yylval.colno++;
207 /* check for special one-character constructions */
208 switch (c) {
209 case '\r':
210 /* silently eat up any \r */
211 goto repeat;
212 case '\n':
213 yylval.colno = 0;
214 yylval.lineno++;
215 /* fallthrough */
216 case '{':
217 case '}':
218 case '=':
219 return c;
220 case '#':
221 /* skip comments; NUL is allowed; no continuation */
222 while ((c = getc(yyfp)) != '\n')
223 if (c == EOF)
224 goto eof;
225 yylval.colno = 0;
226 yylval.lineno++;
227 return c;
228 case EOF:
229 goto eof;
232 /* parsing next word */
233 for (;; c = getc(yyfp), yylval.colno++) {
234 switch (c) {
235 case '\0':
236 yyerror("unallowed character NULL in column %d",
237 yylval.colno+1);
238 escape = 0;
239 continue;
240 case '\\':
241 escape = !escape;
242 if (escape)
243 continue;
244 break;
245 case '\r':
246 /* ignore \r here too */
247 continue;
248 case '\n':
249 if (quotes)
250 yyerror("unterminated quotes in column %d",
251 yylval.colno+1);
252 if (escape) {
253 nonkw = 1;
254 escape = 0;
255 yylval.colno = 0;
256 yylval.lineno++;
258 goto eow;
259 case EOF:
260 if (escape)
261 yyerror("unterminated escape in column %d",
262 yylval.colno);
263 if (quotes)
264 yyerror("unterminated quotes in column %d",
265 qpos + 1);
266 goto eow;
267 case '{':
268 case '}':
269 case '=':
270 case '#':
271 case ' ':
272 case '\t':
273 if (!escape && !quotes)
274 goto eow;
275 break;
276 case '"':
277 if (!escape) {
278 quotes = !quotes;
279 if (quotes) {
280 nonkw = 1;
281 qpos = yylval.colno;
283 continue;
286 *p++ = c;
287 if (p == ebuf) {
288 yyerror("line too long");
289 p = buf;
291 escape = 0;
294 eow:
295 *p = 0;
296 if (c != EOF)
297 ungetc(c, yyfp);
298 if (p == buf) {
299 /*
300 * There could be a number of reason for empty buffer,
301 * and we handle all of them here, to avoid cluttering
302 * the main loop.
303 */
304 if (c == EOF)
305 goto eof;
306 else if (qpos == -1) /* accept, e.g., empty args: cmd foo args "" */
307 goto repeat;
309 if (!nonkw) {
310 for (i = 0; i < sizeof(keywords) / sizeof(keywords[0]); i++) {
311 if (strcmp(buf, keywords[i].word) == 0)
312 return keywords[i].token;
315 c = *buf;
316 if (!nonkw && (c == '-' || isdigit(c))) {
317 yylval.num = strtonum(buf, INT_MIN, INT_MAX, &errstr);
318 if (errstr != NULL)
319 yyerror("number is %s: %s", errstr, buf);
320 return NUMBER;
322 str = xstrdup(buf);
323 yylval.str = str;
324 return STRING;
326 eof:
327 if (ferror(yyfp))
328 yyerror("input error reading config");
329 return 0;
332 static void
333 setprfx(const char *prfx, const char *cont)
335 assert(current_style != NULL);
337 if (!config_setprfx(current_style, prfx, cont))
338 yyerror("invalid style %s", current_style);
341 static void
342 setvari(char *var, int val)
344 /*
345 * For some time, fall back to a boolean as compat
346 * with telescope 0.8 and previous.
347 */
348 if (!config_setvari(var, val) &&
349 !config_setvarb(var, val))
350 yyerror("invalid variable or value: %s = %d",
351 var, val);
353 free(var);
356 static void
357 setvars(char *var, char *val)
359 if (!config_setvars(var, val))
360 yyerror("invalid variable or value: %s = \"%s\"",
361 var, val);
363 free(var);
366 static void
367 setvarb(char *var, int val)
369 if (!config_setvarb(var, val))
370 yyerror("invalid variable or value: %s = %s",
371 var, val ? "true" : "false");
373 free(var);
376 static int
377 colorname(const char *name)
379 struct {
380 const char *name;
381 short val;
382 } *i, colors[] = {
383 { "default", -1 },
384 { "black", COLOR_BLACK },
385 { "red", COLOR_RED },
386 { "green", COLOR_GREEN },
387 { "yellow", COLOR_YELLOW },
388 { "blue", COLOR_BLUE },
389 { "magenta", COLOR_MAGENTA },
390 { "cyan", COLOR_CYAN },
391 { "white", COLOR_WHITE },
392 { NULL, 0 },
393 };
394 const char *errstr;
395 int n;
397 if (!strncmp(name, "colo", 4)) {
398 /* people are strange */
399 if (!strncmp(name, "color", 5))
400 name += 5;
401 else if (!strncmp(name, "colour", 6))
402 name += 6;
403 else
404 goto err;
406 n = strtonum(name, 0, 256, &errstr);
407 if (errstr != NULL)
408 yyerror("color number is %s: %s", errstr, name);
409 return n;
412 for (i = colors; i->name != NULL; ++i) {
413 if (!strcmp(i->name, name))
414 return i->val;
417 err:
418 yyerror("unknown color name \"%s\"", name);
419 return -1;
422 void
423 setcolor(const char *prfx, const char *line, const char *trail)
425 int p, l, t;
427 assert(current_style != NULL);
429 p = colorname(prfx);
430 l = colorname(line);
431 t = colorname(trail);
433 if (!config_setcolor(color_type == BG, current_style, p, l, t))
434 yyerror("invalid style %s", current_style);
437 static int
438 attrname(const char *n)
440 struct {
441 const char *name;
442 unsigned int val;
443 } *i, attrs[] = {
444 { "normal", A_NORMAL },
445 { "standout", A_STANDOUT },
446 { "underline", A_UNDERLINE },
447 { "reverse", A_REVERSE },
448 { "blink", A_BLINK },
449 { "dim", A_DIM },
450 { "bold", A_BOLD },
451 { NULL, 0 },
452 };
453 int ret, found;
454 char *ap, *dup, *orig;
456 dup = xstrdup(n);
458 orig = dup;
460 ret = 0;
461 while ((ap = strsep(&dup, ",")) != NULL) {
462 if (*ap == '\0')
463 continue;
465 found = 0;
466 for (i = attrs; i ->name != NULL; ++i) {
467 if (strcmp(i->name, ap))
468 continue;
469 ret |= i->val;
470 found = 1;
471 break;
474 if (!found)
475 yyerror("unknown attribute \"%s\" at col %d",
476 ap, yylval.colno+1);
479 free(orig);
480 return ret;
483 static void
484 setattr(char *prfx, char *line, char *trail)
486 int p, l, t;
488 assert(current_style != NULL);
490 p = attrname(prfx);
491 l = attrname(line);
492 t = attrname(trail);
494 if (!config_setattr(current_style, p, l, t))
495 yyerror("invalid style %s", current_style);
498 static void
499 add_proxy(char *proto, char *proxy)
501 static struct iri iri;
502 struct proxy *p;
504 if (iri_parse(NULL, proxy, &iri) == -1) {
505 yyerror("can't parse URL: %s", proxy);
506 return;
509 if ((iri.iri_flags & (IH_QUERY|IH_FRAGMENT)) ||
510 iri.iri_path[0] != '\0') {
511 yyerror("proxy url can't have path, query or fragments");
512 return;
515 if (strcmp(iri.iri_scheme, "gemini")) {
516 yyerror("disallowed proxy protocol %s", iri.iri_scheme);
517 return;
520 p = xcalloc(1, sizeof(*p));
522 p->match_proto = proto;
523 p->proto = PROTO_GEMINI;
525 p->host = xstrdup(iri.iri_host);
527 p->port = xstrdup(iri.iri_portstr);
529 TAILQ_INSERT_HEAD(&proxies, p, proxies);
532 static interactivefn *
533 cmdname(const char *name)
535 struct cmd *cmd;
537 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
538 if (!strcmp(cmd->cmd, name))
539 return cmd->fn;
542 return NULL;
545 static void
546 bindkey(const char *map, const char *key, const char *cmd)
548 struct kmap *kmap;
549 interactivefn *fn;
551 if (!strcmp(map, "global-map"))
552 kmap = &global_map;
553 else if (!strcmp(map, "minibuffer-map"))
554 kmap = &minibuffer_map;
555 else {
556 yyerror("unknown map: %s", map);
557 return;
560 if ((fn = cmdname(cmd)) == NULL) {
561 yyerror("unknown cmd: %s", fn);
562 return;
565 if (!kmap_define_key(kmap, key, fn))
566 yyerror("failed to bind %s %s %s", map, key, cmd);
569 static void
570 do_parseconfig(const char *filename, int fonf)
572 if ((yyfp = fopen(filename, "r")) == NULL) {
573 if (fonf)
574 err(1, "%s", filename);
575 return;
578 path = filename;
579 yyparse();
580 fclose(yyfp);
581 if (parse_errors)
582 exit(1);
585 void
586 parseconfig(const char *filename, int fonf)
588 char altconf[PATH_MAX], *term;
590 /* load the given config file */
591 do_parseconfig(filename, fonf);
593 /* then try to load file-TERM */
595 if ((term = getenv("TERM")) == NULL)
596 return;
598 strlcpy(altconf, filename, sizeof(altconf));
599 strlcat(altconf, "-", sizeof(altconf));
600 strlcat(altconf, term, sizeof(altconf));
602 do_parseconfig(altconf, 0);