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"
41 typedef struct {
42 union {
43 char *str;
44 int num;
45 };
46 int lineno;
47 int colno;
48 } yystype;
49 #define YYSTYPE yystype
51 static char *current_style;
52 static int color_type;
54 static const char *path;
56 FILE *yyfp;
58 int parse_errors = 0;
60 static void yyerror(const char *, ...);
61 static int yylex(void);
62 static void setprfx(const char *, const char *);
63 static void setvari(char *, int);
64 static void setvars(char *, char *);
65 static void setvarb(char *, int);
66 static int colorname(const char *);
67 static void setcolor(const char *, const char *, const char *);
68 static int attrname(const char *);
69 static void setattr(char *, char *, char *);
70 static void add_proxy(char *, char *);
71 static void bindkey(const char *, const char *, const char *);
72 static void do_parseconfig(const char *, int);
74 %}
76 %token ATTR
77 %token BIND BG
78 %token CONT
79 %token FG
80 %token PRFX PROXY
81 %token SET STYLE
82 %token UNBIND
83 %token VIA
85 /* Sigh... they conflict with ncurses TRUE and FALSE */
86 %token TOK_TRUE TOK_FALSE
88 %token <str> STRING
89 %token <num> NUMBER
90 %type <num> bool
92 %%
94 grammar : /* empty */
95 | grammar '\n'
96 | grammar rule '\n'
97 | error '\n'
98 ;
100 bool : TOK_TRUE { $$ = 1; }
101 | TOK_FALSE { $$ = 0; }
104 rule : set
105 | style {
106 free(current_style);
107 current_style = NULL;
109 | bind
110 | unbind
111 | proxy
114 set : SET STRING '=' STRING { setvars($2, $4); }
115 | SET STRING '=' NUMBER { setvari($2, $4); }
116 | SET STRING '=' bool { setvarb($2, $4); }
119 style : STYLE STRING { current_style = $2; } stylespec ;
120 stylespec : styleopt | '{' optnl styleopts '}' ;
122 styleopts : /* empty */
123 | styleopts styleopt optnl
126 styleopt : PRFX STRING { setprfx($2, $2); }
127 | PRFX STRING STRING { setprfx($2, $3); }
128 | BG { color_type = BG; } colorspec
129 | FG { color_type = FG; } colorspec
130 | ATTR attr
133 colorspec : STRING { setcolor($1, $1, $1); free($1); }
134 | STRING STRING { setcolor($1, $2, $1); free($1); free($2); }
135 | STRING STRING STRING { setcolor($1, $2, $3); free($1); free($2); free($3); }
138 attr : STRING { setattr($1, $1, $1); free($1); }
139 | STRING STRING { setattr($1, $2, $1); free($1); free($2); }
140 | STRING STRING STRING { setattr($1, $2, $3); free($1); free($2); free($3); }
143 bind : BIND STRING STRING STRING { bindkey($2, $3, $4); free($2); free($3); free($4); }
146 unbind : UNBIND STRING STRING { yyerror("TODO: unbind %s %s", $2, $3); }
149 proxy : PROXY STRING VIA STRING { add_proxy($2, $4); free($4); }
152 optnl : '\n' optnl /* zero or more newlines */
153 | /* empty */
156 %%
158 void
159 yyerror(const char *fmt, ...)
161 va_list va;
163 fprintf(stderr, "%s:%d ", path, yylval.lineno+1);
164 va_start(va, fmt);
165 vfprintf(stderr, fmt, va);
166 va_end(va);
167 fprintf(stderr, "\n");
168 parse_errors++;
171 static struct keyword {
172 const char *word;
173 int token;
174 } keywords[] = {
175 { "attr", ATTR },
176 { "bg", BG },
177 { "bind", BIND },
178 { "cont", CONT },
179 { "false", TOK_FALSE },
180 { "fg", FG },
181 { "prefix", PRFX },
182 { "proxy", PROXY },
183 { "set", SET },
184 { "style", STYLE },
185 { "true", TOK_TRUE },
186 { "unbind", UNBIND },
187 { "via", VIA },
188 };
190 int
191 yylex(void)
193 char buf[1024], *ebuf, *p, *str;
194 const char *errstr;
195 int c, quotes = 0, escape = 0, qpos = -1, nonkw = 0;
196 size_t i;
198 p = buf;
199 ebuf = buf + sizeof(buf);
201 repeat:
202 /* skip whitespace first */
203 for (c = getc(yyfp); c == ' ' || c == '\t' || c == '\f'; c = getc(yyfp))
204 yylval.colno++;
206 /* check for special one-character constructions */
207 switch (c) {
208 case '\r':
209 /* silently eat up any \r */
210 goto repeat;
211 case '\n':
212 yylval.colno = 0;
213 yylval.lineno++;
214 /* fallthrough */
215 case '{':
216 case '}':
217 case '=':
218 return c;
219 case '#':
220 /* skip comments; NUL is allowed; no continuation */
221 while ((c = getc(yyfp)) != '\n')
222 if (c == EOF)
223 goto eof;
224 yylval.colno = 0;
225 yylval.lineno++;
226 return c;
227 case EOF:
228 goto eof;
231 /* parsing next word */
232 for (;; c = getc(yyfp), yylval.colno++) {
233 switch (c) {
234 case '\0':
235 yyerror("unallowed character NULL in column %d",
236 yylval.colno+1);
237 escape = 0;
238 continue;
239 case '\\':
240 escape = !escape;
241 if (escape)
242 continue;
243 break;
244 case '\r':
245 /* ignore \r here too */
246 continue;
247 case '\n':
248 if (quotes)
249 yyerror("unterminated quotes in column %d",
250 yylval.colno+1);
251 if (escape) {
252 nonkw = 1;
253 escape = 0;
254 yylval.colno = 0;
255 yylval.lineno++;
257 goto eow;
258 case EOF:
259 if (escape)
260 yyerror("unterminated escape in column %d",
261 yylval.colno);
262 if (quotes)
263 yyerror("unterminated quotes in column %d",
264 qpos + 1);
265 goto eow;
266 case '{':
267 case '}':
268 case '=':
269 case '#':
270 case ' ':
271 case '\t':
272 if (!escape && !quotes)
273 goto eow;
274 break;
275 case '"':
276 if (!escape) {
277 quotes = !quotes;
278 if (quotes) {
279 nonkw = 1;
280 qpos = yylval.colno;
282 continue;
285 *p++ = c;
286 if (p == ebuf) {
287 yyerror("line too long");
288 p = buf;
290 escape = 0;
293 eow:
294 *p = 0;
295 if (c != EOF)
296 ungetc(c, yyfp);
297 if (p == buf) {
298 /*
299 * There could be a number of reason for empty buffer,
300 * and we handle all of them here, to avoid cluttering
301 * the main loop.
302 */
303 if (c == EOF)
304 goto eof;
305 else if (qpos == -1) /* accept, e.g., empty args: cmd foo args "" */
306 goto repeat;
308 if (!nonkw) {
309 for (i = 0; i < sizeof(keywords) / sizeof(keywords[0]); i++) {
310 if (strcmp(buf, keywords[i].word) == 0)
311 return keywords[i].token;
314 c = *buf;
315 if (!nonkw && (c == '-' || isdigit(c))) {
316 yylval.num = strtonum(buf, INT_MIN, INT_MAX, &errstr);
317 if (errstr != NULL)
318 yyerror("number is %s: %s", errstr, buf);
319 return NUMBER;
321 if ((str = strdup(buf)) == NULL)
322 err(1, "%s", __func__);
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 if ((dup = strdup(n)) == NULL)
457 err(1, "strdup");
459 orig = dup;
461 ret = 0;
462 while ((ap = strsep(&dup, ",")) != NULL) {
463 if (*ap == '\0')
464 continue;
466 found = 0;
467 for (i = attrs; i ->name != NULL; ++i) {
468 if (strcmp(i->name, ap))
469 continue;
470 ret |= i->val;
471 found = 1;
472 break;
475 if (!found)
476 yyerror("unknown attribute \"%s\" at col %d",
477 ap, yylval.colno+1);
480 free(orig);
481 return ret;
484 static void
485 setattr(char *prfx, char *line, char *trail)
487 int p, l, t;
489 assert(current_style != NULL);
491 p = attrname(prfx);
492 l = attrname(line);
493 t = attrname(trail);
495 if (!config_setattr(current_style, p, l, t))
496 yyerror("invalid style %s", current_style);
499 static void
500 add_proxy(char *proto, char *proxy)
502 static struct iri iri;
503 struct proxy *p;
505 if (iri_parse(NULL, proxy, &iri) == -1) {
506 yyerror("can't parse URL: %s", proxy);
507 return;
510 if ((iri.iri_flags & (IH_QUERY|IH_FRAGMENT)) ||
511 iri.iri_path[0] != '\0') {
512 yyerror("proxy url can't have path, query or fragments");
513 return;
516 if (strcmp(iri.iri_scheme, "gemini")) {
517 yyerror("disallowed proxy protocol %s", iri.iri_scheme);
518 return;
521 if ((p = calloc(1, sizeof(*p))) == NULL)
522 err(1, "calloc");
524 p->match_proto = proto;
525 p->proto = PROTO_GEMINI;
527 if ((p->host = strdup(iri.iri_host)) == NULL)
528 err(1, "strdup");
530 if ((p->port = strdup(iri.iri_portstr)) == NULL)
531 err(1, "strdup");
533 TAILQ_INSERT_HEAD(&proxies, p, proxies);
536 static interactivefn *
537 cmdname(const char *name)
539 struct cmd *cmd;
541 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
542 if (!strcmp(cmd->cmd, name))
543 return cmd->fn;
546 return NULL;
549 static void
550 bindkey(const char *map, const char *key, const char *cmd)
552 struct kmap *kmap;
553 interactivefn *fn;
555 if (!strcmp(map, "global-map"))
556 kmap = &global_map;
557 else if (!strcmp(map, "minibuffer-map"))
558 kmap = &minibuffer_map;
559 else {
560 yyerror("unknown map: %s", map);
561 return;
564 if ((fn = cmdname(cmd)) == NULL) {
565 yyerror("unknown cmd: %s", fn);
566 return;
569 if (!kmap_define_key(kmap, key, fn))
570 yyerror("failed to bind %s %s %s", map, key, cmd);
573 static void
574 do_parseconfig(const char *filename, int fonf)
576 if ((yyfp = fopen(filename, "r")) == NULL) {
577 if (fonf)
578 err(1, "%s", filename);
579 return;
582 path = filename;
583 yyparse();
584 fclose(yyfp);
585 if (parse_errors)
586 exit(1);
589 void
590 parseconfig(const char *filename, int fonf)
592 char altconf[PATH_MAX], *term;
594 /* load the given config file */
595 do_parseconfig(filename, fonf);
597 /* then try to load file-TERM */
599 if ((term = getenv("TERM")) == NULL)
600 return;
602 strlcpy(altconf, filename, sizeof(altconf));
603 strlcat(altconf, "-", sizeof(altconf));
604 strlcat(altconf, term, sizeof(altconf));
606 do_parseconfig(altconf, 0);