aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

bc.y (22187B)


      1 %{
      2 #if FEATURE_BC_ASCII
      3 #ifndef _DEFAULT_SOURCE
      4 #define _DEFAULT_SOURCE
      5 #endif
      6 #endif
      7 #include <libgen.h>
      8 #include <unistd.h>
      9 
     10 #include <assert.h>
     11 #include <ctype.h>
     12 #include <errno.h>
     13 #include <setjmp.h>
     14 #include <stdarg.h>
     15 #include <stdio.h>
     16 #include <stdlib.h>
     17 #include <string.h>
     18 
     19 #include "arg.h"
     20 #include "util.h"
     21 #include "wexec.h"
     22 
     23 #define DIGITS   "0123456789ABCDEF"
     24 #define NESTED_MAX 32
     25 
     26 #define funid(f) ((f)[0] - 'a' + 1)
     27 
     28 int yydebug;
     29 
     30 typedef struct macro Macro;
     31 
     32 struct macro {
     33 	int op;
     34 	int id;
     35 	char *name;
     36 	int flowid;
     37 	int nested;
     38 };
     39 
     40 static int yyerror(char *);
     41 static int yylex(void);
     42 
     43 static void quit(void);
     44 static char *code(char *, ...);
     45 static char *forcode(Macro *, char *, char *, char *, char *);
     46 static char *whilecode(Macro *, char *, char *);
     47 static char *ifcode(Macro *, char *, char *, char *);
     48 static char *funcode(Macro *, char *, char *, char *);
     49 static char *param(char *, char *), *local(char *, char *);
     50 static char *retcode(char *);
     51 static char *brkcode(void);
     52 static Macro *macro(int);
     53 
     54 static char *ftn(char *);
     55 static char *var(char *);
     56 static char *ary(char *);
     57 static void writeout(char *);
     58 
     59 static char *yytext, *buff, *unwind;
     60 static size_t buffcap;
     61 static char *filename;
     62 static FILE *filep;
     63 static int lineno, nerr, flowid;
     64 static jmp_buf recover;
     65 static int nested, inhome;
     66 static Macro macros[NESTED_MAX];
     67 int cflag, dflag, lflag, sflag;
     68 
     69 static char *dcprog = "dc";
     70 
     71 %}
     72 
     73 %union {
     74 	char *str;
     75 	char id[16]; // dc REGSIZ: cap on an extended register name
     76 	Macro *macro;
     77 }
     78 
     79 %token <id> ID
     80 %token <str> STRING NUMBER
     81 %token <str> EQOP '+' '-' '*' '/' '%' '^' INCDEC
     82 %token HOME LOOP
     83 %token DOT
     84 %token EQ
     85 %token LE
     86 %token GE
     87 %token NE
     88 %token DEF
     89 %token BREAK
     90 %token QUIT
     91 %token LENGTH
     92 %token RETURN
     93 %token FOR
     94 %token IF
     95 %token WHILE
     96 %token SQRT
     97 %token SCALE
     98 %token IBASE
     99 %token OBASE
    100 %token AUTO PARAM
    101 %token PRINT
    102 %token ELSE
    103 %token HALT
    104 %token READ
    105 
    106 %type <str> item statlst scolonlst
    107 %type <str> function assign nexpr expr exprstat rel stat ary cond
    108 %type <str> autolst arglst parlst
    109 %type <str> prlst pritem
    110 %type <str> params param locals local
    111 %type <macro> def if for while
    112 
    113 %right	'=' EQOP
    114 %left	'+' '-'
    115 %left	'*' '/' '%'
    116 %right	'^'
    117 
    118 %start    program
    119 
    120 %%
    121 
    122 program  :
    123          | item program
    124          ;
    125 
    126 item     : scolonlst '\n'       {writeout($1);}
    127          | function             {writeout($1);}
    128          ;
    129 
    130 function : def parlst '{' '\n' autolst statlst '}' {$$ = funcode($1, $2, $5, $6);}
    131          ;
    132 
    133 scolonlst:                      {$$ = code("");}
    134          | stat
    135          | scolonlst ';' stat   {$$ = code("%s%s", $1, $3);}
    136          | scolonlst ';'
    137          ;
    138 
    139 statlst :                       {$$ = code("");}
    140         | stat
    141         | statlst '\n' stat     {$$ = code("%s%s", $1, $3);}
    142         | statlst ';' stat      {$$ = code("%s%s", $1, $3);}
    143         | statlst '\n'
    144         | statlst ';'
    145         ;
    146 
    147 stat    : exprstat
    148         | PRINT prlst           {$$ = $2;}
    149         | STRING                {$$ = code("[%s]P", $1);}
    150         | BREAK                 {$$ = brkcode();}
    151         | QUIT                  {quit();}
    152         | HALT                  {$$ = code("q");}
    153         | RETURN                {$$ = retcode(code(" 0"));}
    154         | RETURN expr           {$$ = retcode($2);}
    155         | RETURN '(' ')'        {$$ = retcode(code(" 0"));}
    156         | while cond optnl stat       {$$ = whilecode($1, $2, $4);}
    157         | if cond optnl stat          {$$ = ifcode($1, $2, $4, NULL);}
    158         | if cond optnl stat ELSE optnl stat  {$$ = ifcode($1, $2, $4, $7);}
    159         | '{' statlst '}'       {$$ = $2;}
    160         | for '(' expr ';' rel ';' expr ')' optnl stat  {$$ = forcode($1, $3, $5, $7, $10);}
    161         ;
    162 
    163 // a while/if/for body may start on the next line. a { } body goes
    164 // through statlst, which handles its own newlines
    165 optnl   :
    166         | optnl '\n'
    167         ;
    168 
    169 // print takes any number of strings and expressions, mixed. no item
    170 // gets an implicit trailing newline, as in real bc
    171 prlst   : pritem
    172         | prlst ',' pritem      {$$ = code("%s%s", $1, $3);}
    173         ;
    174 
    175 pritem  : expr                  {$$ = code("%sn", $1);}
    176         | STRING                {$$ = code("[%s]P", $1);}
    177         ;
    178 
    179 while   : WHILE                 {$$ = macro(LOOP);}
    180         ;
    181 
    182 if      : IF                    {$$ = macro(IF);}
    183         ;
    184 
    185 for     : FOR                   {$$ = macro(LOOP);}
    186         ;
    187 
    188 def     : DEF ID                {$$ = macro(DEF);}
    189         ;
    190 
    191 parlst  : '(' ')'               {$$ = code("");}
    192         | '(' params ')'        {$$ = $2;}
    193         ;
    194 
    195 params  : param                 {$$ = param(NULL, $1);}
    196         | params ',' param      {$$ = param($1, $3);}
    197         ;
    198 
    199 param   : ID                    {$$ = var($1);}
    200         | ID '[' ']'            {$$ = ary($1);}
    201         ;
    202 
    203 autolst :                       {$$ = code("");}
    204         | AUTO locals '\n'      {$$ = $2;}
    205         | AUTO locals ';'       {$$ = $2;}
    206         ;
    207 
    208 locals  : local                 {$$ = local(NULL, $1);}
    209         | locals ',' local      {$$ = local($1, $3);}
    210         ;
    211 
    212 local   : ID                    {$$ = var($1);}
    213         | ID '[' ']'            {$$ = ary($1);}
    214         ;
    215 
    216 arglst  : expr
    217         | ID '[' ']'            {$$ = code("%s", ary($1));}
    218         | expr ',' arglst       {$$ = code("%s%s", $1, $3);}
    219         | ID '[' ']' ',' arglst {$$ = code("%s%s", ary($1), $5);}
    220         ;
    221 
    222 cond    : '(' rel ')'           {$$ = $2;}
    223         ;
    224 
    225 rel     : expr                  {$$ = code("%s 0!=", $1);}
    226         | expr EQ expr          {$$ = code("%s%s=", $1, $3);}
    227         | expr LE expr          {$$ = code("%s%s!<", $1, $3);}
    228         | expr GE expr          {$$ = code("%s%s!>", $1, $3);}
    229         | expr NE expr          {$$ = code("%s%s!=", $1, $3);}
    230         | expr '<' expr         {$$ = code("%s%s>", $1, $3);}
    231         | expr '>' expr         {$$ = code("%s%s<", $1, $3);}
    232         ;
    233 
    234 exprstat: nexpr                 {$$ = code("%s%ss.", $1, code(sflag ? "" : "p"));}
    235         | assign                {$$ = code("%ss.", $1);}
    236         ;
    237 
    238 expr    : nexpr
    239         | assign
    240         ;
    241 
    242 nexpr   : NUMBER                {$$ = code(" %s", code($1));}
    243         | ID                    {$$ = code("l%s", var($1));}
    244         | READ '(' ')'          {$$ = code("?");}
    245         | DOT                   {$$ = code("l.");}
    246         | SCALE                 {$$ = code("K");}
    247         | IBASE                 {$$ = code("I");}
    248         | OBASE                 {$$ = code("O");}
    249         | ID ary                {$$ = code("%s;%s", $2, ary($1));}
    250         | '(' expr ')'          {$$ = $2;}
    251         | ID '(' arglst ')'     {$$ = code("%sl%sx", $3, ftn($1));}
    252         | ID '(' ')'            {$$ = code("l%sx", ftn($1));}
    253         | '-' expr              {$$ = code("0%s-", $2);}
    254         | expr '+' expr         {$$ = code("%s%s+", $1, $3);}
    255         | expr '-' expr         {$$ = code("%s%s-", $1, $3);}
    256         | expr '*' expr         {$$ = code("%s%s*", $1, $3);}
    257         | expr '/' expr         {$$ = code("%s%s/", $1, $3);}
    258         | expr '%' expr         {$$ = code("%s%s%%", $1, $3);}
    259         | expr '^' expr         {$$ = code("%s%s^", $1, $3);}
    260         | LENGTH '(' expr ')'   {$$ = code("%sZ", $3);}
    261         | SQRT '(' expr ')'     {$$ = code("%sv", $3);}
    262         | SCALE '(' expr ')'    {$$ = code("%sX", $3);}
    263         | INCDEC ID             {$$ = code("l%s1%sds%s", var($2), code($1), var($2));}
    264         | INCDEC SCALE          {$$ = code("K1%sk", code($1));}
    265         | INCDEC IBASE          {$$ = code("I1%sdi", code($1));}
    266         | INCDEC OBASE          {$$ = code("O1%sdo", code($1));}
    267         | INCDEC ID ary         {$$ = code("%sdS_;%s1%sdL_:%s", $3, ary($2), code($1), ary($2));}
    268         | ID INCDEC             {$$ = code("l%sd1%ss%s", var($1), code($2), var($1));}
    269         | SCALE INCDEC          {$$ = code("Kd1%sk", code($2));}
    270         | IBASE INCDEC          {$$ = code("Id1%si", code($2));}
    271         | OBASE INCDEC          {$$ = code("Od1%so", code($2));}
    272         | ID ary INCDEC         {$$ = code("%sds.;%sd1%sl.:%s", $2, ary($1), code($3), ary($1));}
    273         ;
    274 
    275 assign  : ID '=' expr           {$$ = code("%sds%s", $3, var($1));}
    276         | SCALE '=' expr        {$$ = code("%sdk", $3);}
    277         | IBASE '=' expr        {$$ = code("%sdi", $3);}
    278         | OBASE '=' expr        {$$ = code("%sdo", $3);}
    279         | ID ary '=' expr       {$$ = code("%sd%s:%s", $4, $2, ary($1));}
    280         | ID EQOP expr          {$$ = code("%sl%s%sds%s", $3, var($1), code($2), var($1));}
    281         | SCALE EQOP expr       {$$ = code("%sK%sdk", $3, code($2));}
    282         | IBASE EQOP expr       {$$ = code("%sI%sdi", $3, code($2));}
    283         | OBASE EQOP expr       {$$ = code("%sO%sdo", $3, code($2));}
    284         | ID ary EQOP expr      {$$ = code("%s%sds.;%s%sdl.:s", $4, $2, ary($1), code($3), ary($1));}
    285         ;
    286 
    287 ary     : '[' expr ']'          {$$ = $2;}
    288         ;
    289 
    290 %%
    291 static int
    292 yyerror(char *s)
    293 {
    294 	fprintf(stderr, "bc: %s:%d: %s\n", filename, lineno, s);
    295 	nerr++;
    296 	longjmp(recover, 1);
    297 }
    298 
    299 static void
    300 writeout(char *s)
    301 {
    302 	if (write(1, s, strlen(s)) < 0)
    303 		goto err;
    304 	if (write(1, "\n", 1) < 0)
    305 		goto err;
    306 	free(s);
    307 	return;
    308 
    309 err:
    310 	eprintf("writing to dc:");
    311 }
    312 
    313 // grow the code buffer geometrically to fit need bytes. a generated dc
    314 // macro has no fixed upper bound, unlike BUFSIZ
    315 static void
    316 growbuff(size_t need)
    317 {
    318 	size_t newcap;
    319 
    320 	newcap = buffcap;
    321 	while (newcap < need)
    322 		newcap *= 2;
    323 	buff    = erealloc(buff, newcap);
    324 	buffcap = newcap;
    325 }
    326 
    327 static char *
    328 code(char *fmt, ...)
    329 {
    330 	char  *t;
    331 	va_list ap;
    332 	int    c, len;
    333 	size_t off, room;
    334 
    335 	va_start(ap, fmt);
    336 	for (off = 0; *fmt; off += (size_t)len) {
    337 		len = 1;
    338 		if ((c = *fmt++) != '%')
    339 			goto append;
    340 
    341 		switch (*fmt++) {
    342 		case 'd':
    343 			c = va_arg(ap, int);
    344 			for (;;) {
    345 				room = buffcap - off;
    346 				len  = snprintf(buff + off, room, "%d", c);
    347 				if (len < 0)
    348 					eprintf("unable to code requested operation\n");
    349 				if ((size_t)len < room)
    350 					break;
    351 				growbuff(off + (size_t)len + 1);
    352 			}
    353 			break;
    354 		case 'c':
    355 			c = va_arg(ap, int);
    356 			goto append;
    357 		case 's':
    358 			t   = va_arg(ap, void *);
    359 			len = strlen(t);
    360 			if ((size_t)len >= buffcap - off)
    361 				growbuff(off + (size_t)len + 1);
    362 			memcpy(buff + off, t, len);
    363 			free(t);
    364 			break;
    365 		case '%':
    366 		append:
    367 			if (buffcap - off <= 1)
    368 				growbuff(off + 2);
    369 			buff[off] = c;
    370 			break;
    371 		default:
    372 			abort();
    373 		}
    374 	}
    375 	va_end(ap);
    376 
    377 	buff[off] = '\0';
    378 	return estrdup(buff);
    379 }
    380 
    381 static Macro *
    382 macro(int op)
    383 {
    384 	int preop;
    385 	Macro *d, *p;
    386 
    387 	if (nested == NESTED_MAX)
    388 		yyerror("too much nesting");
    389 
    390 	d = &macros[nested];
    391 	d->op = op;
    392 	d->nested = nested++;
    393 	d->name = NULL;
    394 
    395 	switch (op) {
    396 	case HOME:
    397 		d->id = 0;
    398 		d->flowid = flowid;
    399 		inhome = 1;
    400 		break;
    401 	case DEF:
    402 		unwind = estrdup("");
    403 		inhome = 0;
    404 		d->id = funid(yytext);
    405 		d->name = estrdup(yytext);
    406 		d->flowid = macros[0].flowid;
    407 		break;
    408 	default:
    409 		assert(nested > 1);
    410 		preop = d[-1].op;
    411 		d->flowid = d[-1].flowid;
    412 		if (preop != HOME && preop != DEF) {
    413 			if (d->flowid == 255)
    414 				eprintf("too many control flow structures");
    415 			d->flowid++;
    416 		}
    417 		d->id = d->flowid;
    418 		if (!inhome) {
    419 			/* populate reserved id */
    420 			flowid = d->flowid;
    421 			for (p = d; p != macros; --p)
    422 				p[-1].flowid++;
    423 		}
    424 		break;
    425 	}
    426 
    427 	return d;
    428 }
    429 
    430 static char *
    431 decl(int type, char *list, char *id)
    432 {
    433 	char *i1, *i2;
    434 
    435 	i1 = estrdup(id);
    436 	i2 = estrdup(id);
    437 	free(id);
    438 
    439 	if (!list)
    440 		list = estrdup("");
    441 
    442 	unwind = code("%sL%ss.", unwind, i1);
    443 
    444 	return code((type == AUTO) ? "0S%s%s" : "S%s%s", i2, list);
    445 }
    446 
    447 static char *
    448 param(char *list, char *id)
    449 {
    450 	return decl(PARAM, list, id);
    451 }
    452 
    453 static char *
    454 local(char *list, char *id)
    455 {
    456 	return decl(AUTO, list, id);
    457 }
    458 
    459 static char *
    460 funcode(Macro *d, char *params, char *vars, char *body)
    461 {
    462 	char *s;
    463 
    464 	if (strlen(d->name) > 1) {
    465 		s = code("[%s%s%s%s]s\"()%s\"",
    466 			 vars, params,
    467 			 body,
    468 			 retcode(code(" 0")),
    469 			 d->name);
    470 	} else {
    471 		s = code(sflag ? "[%s%s%s%s]s<%d>" : "[%s%s%s%s]s%c",
    472 			 vars, params,
    473 			 body,
    474 			 retcode(code(" 0")),
    475 			 d->id);
    476 		free(d->name);
    477 	}
    478 
    479 	free(unwind);
    480 	unwind = NULL;
    481 	nested--;
    482 	inhome = 0;
    483 
    484 	return s;
    485 }
    486 
    487 static char *
    488 brkcode(void)
    489 {
    490 	Macro *d;
    491 
    492 	for (d = &macros[nested-1]; d->op != HOME && d->op != LOOP; --d)
    493 		;
    494 	if (d->op == HOME)
    495 		yyerror("break not in for or while");
    496 	return code(" %dQ", nested  - d->nested);
    497 }
    498 
    499 static char *
    500 forcode(Macro *d, char *init, char *cmp, char *inc, char *body)
    501 {
    502 	char *s;
    503 
    504 	s = code(sflag ? "[%s%ss.%s<%d>]s<%d>" : "[%s%ss.%s%c]s%c",
    505 	         body,
    506 	         inc,
    507 	         estrdup(cmp),
    508 	         d->id, d->id);
    509 	writeout(s);
    510 
    511 	s = code(sflag ? "%ss.%s<%d> " : "%ss.%s%c ",
    512 	         init,
    513 	         cmp,
    514 	         d->id);
    515 	nested--;
    516 
    517 	return s;
    518 }
    519 
    520 static char *
    521 whilecode(Macro *d, char *cmp, char *body)
    522 {
    523 	char *s;
    524 
    525 	s = code(sflag ? "[%s%s<%d>]s<%d>" : "[%s%s%c]s%c",
    526 	         body,
    527 	         estrdup(cmp),
    528 	         d->id, d->id);
    529 	writeout(s);
    530 
    531 	s = code(sflag ? "%s<%d> " : "%s%c ",
    532 	         cmp, d->id);
    533 	nested--;
    534 
    535 	return s;
    536 }
    537 
    538 // the trailing relational op (see rel) is one of these six, else runs
    539 // on the opposite one
    540 static char *
    541 invertrel(char *cmp)
    542 {
    543 	size_t n = strlen(cmp);
    544 	const char *suffix;
    545 	size_t keep;
    546 	char *s;
    547 
    548 	if (n >= 2 && strcmp(cmp + n - 2, "!=") == 0) {
    549 		keep = n - 2;
    550 		suffix = "=";
    551 	} else if (n >= 2 && strcmp(cmp + n - 2, "!<") == 0) {
    552 		keep = n - 2;
    553 		suffix = "<";
    554 	} else if (n >= 2 && strcmp(cmp + n - 2, "!>") == 0) {
    555 		keep = n - 2;
    556 		suffix = ">";
    557 	} else if (n >= 1 && cmp[n - 1] == '=') {
    558 		keep = n - 1;
    559 		suffix = "!=";
    560 	} else if (n >= 1 && cmp[n - 1] == '<') {
    561 		keep = n - 1;
    562 		suffix = "!<";
    563 	} else if (n >= 1 && cmp[n - 1] == '>') {
    564 		keep = n - 1;
    565 		suffix = "!>";
    566 	} else {
    567 		yyerror("cannot invert comparison for else");
    568 		return NULL;
    569 	}
    570 
    571 	s = emalloc(keep + strlen(suffix) + 1);
    572 	memcpy(s, cmp, keep);
    573 	strcpy(s + keep, suffix);
    574 
    575 	return s;
    576 }
    577 
    578 // an else body needs a register distinct from the then branch d->id.
    579 // nested bounds d->id, so offsetting by it never collides with another
    580 // nesting level or a named variable
    581 static char *
    582 ifcode(Macro *d, char *cmp, char *body, char *ebody)
    583 {
    584 	char *s, *inv;
    585 
    586 	s = code(sflag ? "[%s]s<%d>" : "[%s]s%c",
    587 	         body, d->id);
    588 	writeout(s);
    589 
    590 	if (ebody) {
    591 		s = code(sflag ? "[%s]s<%d>" : "[%s]s%c",
    592 		         ebody, d->id + NESTED_MAX);
    593 		writeout(s);
    594 
    595 		inv = invertrel(cmp);
    596 		s = code(sflag ? "%s<%d> %s<%d> " : "%s%c %s%c ",
    597 		         cmp, d->id, inv, d->id + NESTED_MAX);
    598 	} else {
    599 		s = code(sflag ? "%s<%d> " : "%s%c ",
    600 		         cmp, d->id);
    601 	}
    602 	nested--;
    603 
    604 	return s;
    605 }
    606 
    607 static char *
    608 retcode(char *expr)
    609 {
    610 	if (nested < 2 || macros[1].op != DEF)
    611 		yyerror("return must be in a function");
    612 	return code("%s %s %dQ", expr, estrdup(unwind), nested - 1);
    613 }
    614 
    615 static char *
    616 ary(char *s)
    617 {
    618 	if (strlen(s) == 1)
    619 		return code("%c", toupper(s[0]));
    620 	return code("\"[]%s\"", estrdup(s));
    621 }
    622 
    623 static char *
    624 ftn(char *s)
    625 {
    626 	if (strlen(s) == 1)
    627 		return code(sflag ? "<%d>" : "%c", funid(s));
    628 	return code("\"()%s\"", estrdup(s));
    629 }
    630 
    631 static char *
    632 var(char *s)
    633 {
    634 	if (strlen(s) == 1)
    635 		return code(s);
    636 	return code("\"%s\"", estrdup(s));
    637 }
    638 
    639 static void
    640 quit(void)
    641 {
    642 	exit(nerr > 0 ? 1 : 0);
    643 }
    644 
    645 static void
    646 skipspaces(void)
    647 {
    648 	int ch;
    649 
    650 	while (isascii(ch = getc(filep)) && isspace(ch)) {
    651 		if (ch == '\n') {
    652 			lineno++;
    653 			break;
    654 		}
    655 	}
    656 	ungetc(ch, filep);
    657 }
    658 
    659 static int
    660 iden(int ch)
    661 {
    662 	static struct keyword {
    663 		char *str;
    664 		int token;
    665 	} keywords[] = {
    666 		{"define", DEF},
    667 		{"break", BREAK},
    668 		{"quit", QUIT},
    669 		{"length", LENGTH},
    670 		{"return", RETURN},
    671 		{"for", FOR},
    672 		{"if", IF},
    673 		{"while", WHILE},
    674 		{"sqrt", SQRT},
    675 		{"scale", SCALE},
    676 		{"ibase", IBASE},
    677 		{"obase", OBASE},
    678 		{"auto", AUTO},
    679 		{"print", PRINT},
    680 		{"else", ELSE},
    681 		{"halt", HALT},
    682 		{"read", READ},
    683 		{NULL, 0}
    684 	};
    685 	struct keyword *p;
    686 	char *bp;
    687 
    688 	ungetc(ch, filep);
    689 	for (bp = yytext; bp < &yytext[BUFSIZ]; ++bp) {
    690 		ch = getc(filep);
    691 		if (!isascii(ch) || !islower(ch))
    692 			break;
    693 		*bp = ch;
    694 	}
    695 
    696 	if (bp == &yytext[BUFSIZ])
    697 		yyerror("too long token");
    698 	*bp = '\0';
    699 	ungetc(ch, filep);
    700 
    701 	if (strlen(yytext) == 1) {
    702 		strcpy(yylval.id, yytext);
    703 		return ID;
    704 	}
    705 
    706 	for (p = keywords; p->str && strcmp(p->str, yytext); ++p)
    707 		;
    708 	if (p->str)
    709 		return p->token;
    710 
    711 	// posix bc names variables and functions with one lowercase letter,
    712 	// but real scripts use longer names, as GNU bc does
    713 #if !FEATURE_BC_MULTICHAR
    714 	if (!sflag)
    715 		yyerror("invalid keyword");
    716 #endif
    717 	if (strlen(yytext) >= sizeof(yylval.id))
    718 		yyerror("identifier too long");
    719 	strcpy(yylval.id, yytext);
    720 	return ID;
    721 }
    722 
    723 static char *
    724 digits(char *bp)
    725 {
    726 	int ch;
    727 	char *digits = DIGITS, *p;
    728 
    729 	while (bp < &yytext[BUFSIZ]) {
    730 		ch = getc(filep);
    731 		p = strchr(digits, ch);
    732 		if (!p)
    733 			break;
    734 		*bp++ = ch;
    735 	}
    736 
    737 	if (bp == &yytext[BUFSIZ])
    738 		return NULL;
    739 	ungetc(ch, filep);
    740 
    741 	return bp;
    742 }
    743 
    744 static int
    745 number(int ch)
    746 {
    747 	char *bp;
    748 
    749 	ungetc(ch, filep);
    750 	if ((bp = digits(yytext)) == NULL)
    751 		goto toolong;
    752 
    753 	if ((ch = getc(filep)) != '.') {
    754 		ungetc(ch, filep);
    755 		goto end;
    756 	}
    757 	*bp++ = '.';
    758 
    759 	if ((bp = digits(bp)) == NULL)
    760 		goto toolong;
    761 
    762 end:
    763 	if (bp ==  &yytext[BUFSIZ])
    764 		goto toolong;
    765 	*bp = '\0';
    766 	yylval.str = yytext;
    767 
    768 	return NUMBER;
    769 
    770 toolong:
    771 	yyerror("too long number");
    772 	return 0;
    773 }
    774 
    775 static int
    776 string(int ch)
    777 {
    778 	char *bp;
    779 
    780 	for (bp = yytext; bp < &yytext[BUFSIZ]; ++bp) {
    781 		if ((ch = getc(filep)) == '"')
    782 			break;
    783 #if FEATURE_BC_ESCAPES
    784 		// posix bc has no string escapes, but scripts assume GNU \n \t etc,
    785 		// and dc passes a literal byte through with nothing to turn it into a
    786 		// newline later
    787 		if (ch == '\\') {
    788 			switch (ch = getc(filep)) {
    789 			case 'a':
    790 				ch = '\a';
    791 				break;
    792 			case 'b':
    793 				ch = '\b';
    794 				break;
    795 			case 'f':
    796 				ch = '\f';
    797 				break;
    798 			case 'n':
    799 				ch = '\n';
    800 				break;
    801 			case 'r':
    802 				ch = '\r';
    803 				break;
    804 			case 't':
    805 				ch = '\t';
    806 				break;
    807 			case 'v':
    808 				ch = '\v';
    809 				break;
    810 			case 'q':
    811 				// GNU escape for a literal double quote, the only way into a bc string
    812 				ch = '"';
    813 				break;
    814 			case '\\':
    815 			case '"':
    816 				break;
    817 			default:
    818 				*bp++ = '\\';
    819 				break;
    820 			}
    821 		}
    822 #endif
    823 		*bp = ch;
    824 	}
    825 
    826 	if (bp == &yytext[BUFSIZ])
    827 		yyerror("too long string");
    828 	*bp = '\0';
    829 	yylval.str = estrdup(yytext);
    830 
    831 	return STRING;
    832 }
    833 
    834 static int
    835 follow(int next, int yes, int no)
    836 {
    837 	int ch;
    838 
    839 	ch = getc(filep);
    840 	if (ch == next)
    841 		return yes;
    842 	ungetc(ch, filep);
    843 	return no;
    844 }
    845 
    846 static int
    847 operand(int ch)
    848 {
    849 	int peekc;
    850 
    851 	switch (ch) {
    852 	case '\n':
    853 	case '{':
    854 	case '}':
    855 	case '[':
    856 	case ']':
    857 	case '(':
    858 	case ')':
    859 	case ',':
    860 	case ';':
    861 		return ch;
    862 	case '.':
    863 		peekc = ungetc(getc(filep), filep);
    864 		if (strchr(DIGITS, peekc))
    865 			return number(ch);
    866 		return DOT;
    867 	case '"':
    868 		return string(ch);
    869 	case '*':
    870 		yylval.str = "*";
    871 		return follow('=', EQOP, '*');
    872 	case '/':
    873 		yylval.str = "/";
    874 		return follow('=', EQOP, '/');
    875 	case '%':
    876 		yylval.str = "%";
    877 		return follow('=', EQOP, '%');
    878 	case '=':
    879 		return follow('=', EQ, '=');
    880 	case '+':
    881 	case '-':
    882 		yylval.str = (ch == '+') ? "+" : "-";
    883 		if (follow('=', EQOP, ch) != ch)
    884 			return EQOP;
    885 		return follow(ch, INCDEC, ch);
    886 	case '^':
    887 		yylval.str = "^";
    888 		return follow('=', EQOP, '^');
    889 	case '<':
    890 		return follow('=', LE, '<');
    891 	case '>':
    892 		return follow('=', GE, '>');
    893 	case '!':
    894 		if (getc(filep) == '=')
    895 			return NE;
    896 		/* fallthrough */
    897 	default:
    898 		yyerror("invalid operand");
    899 		return 0;
    900 	}
    901 }
    902 
    903 static void
    904 comment(void)
    905 {
    906 	int c;
    907 
    908 	for (;;) {
    909 		while ((c = getc(filep)) != '*') {
    910 			if (c == '\n')
    911 				lineno++;
    912 		}
    913 		if ((c = getc(filep)) == '/')
    914 			break;
    915 		ungetc(c, filep);
    916 	}
    917 }
    918 
    919 static int
    920 yylex(void)
    921 {
    922 	int peekc, ch;
    923 
    924 repeat:
    925 	skipspaces();
    926 
    927 	ch = getc(filep);
    928 	if (ch == EOF) {
    929 		return EOF;
    930 	} else if (!isascii(ch)) {
    931 		yyerror("invalid input character");
    932 	} else if (islower(ch)) {
    933 		return iden(ch);
    934 	} else if (strchr(DIGITS, ch)) {
    935 		return number(ch);
    936 	} else {
    937 		if (ch == '/') {
    938 			peekc = getc(filep);
    939 			if (peekc == '*') {
    940 				comment();
    941 				goto repeat;
    942 			}
    943 			ungetc(peekc, filep);
    944 		}
    945 		return operand(ch);
    946 	}
    947 
    948 	return 0;
    949 }
    950 
    951 static void
    952 spawn(void)
    953 {
    954 	int fds[2];
    955 	// dc needs the extended register syntax from ftn()/var()/ary() (see
    956 	// iden()) for any name that is not one letter, so pass -i whenever
    957 	// this build can emit it
    958 #if FEATURE_BC_MULTICHAR
    959 	char *par = "-i";
    960 #else
    961 	char *par = sflag ? "-i" : NULL;
    962 #endif
    963 	char errmsg[] = "bc:error execing dc\n";
    964 
    965 	// fd 0 becomes the read end of the code pipe below, but dc ? (bc
    966 	// read()) needs the original stdin. stash it on fd 3, which dc checks,
    967 	// or read() would consume the generated code. do it before pipe() so
    968 	// dup2 cant clobber one of its fds
    969 	dup2(0, 3);
    970 
    971 	if (pipe(fds) < 0)
    972 		eprintf("creating pipe:");
    973 
    974 	switch (fork()) {
    975 	case -1:
    976 		eprintf("forking dc:");
    977 		/* fallthrough */
    978 	case 0:
    979 		close(1);
    980 		dup(fds[1]);
    981 		close(fds[0]);
    982 		close(fds[1]);
    983 		break;
    984 	default:
    985 		close(0);
    986 		dup(fds[0]);
    987 		close(fds[0]);
    988 		close(fds[1]);
    989 		wexecvp_self(dcprog, (char *const[]){"dc", par, NULL});
    990 
    991 		/* it shouldnt happen */
    992 		write(3, errmsg, sizeof(errmsg)-1);
    993 		_Exit(2);
    994 	}
    995 }
    996 
    997 static void
    998 run(void)
    999 {
   1000 	if (setjmp(recover)) {
   1001 		if (ferror(filep))
   1002 			eprintf("%s:", filename);
   1003 		if (feof(filep))
   1004 			return;
   1005 	}
   1006 	yyparse();
   1007 }
   1008 
   1009 static void
   1010 bc(char *fname)
   1011 {
   1012 	lineno = 1;
   1013 	nested = 0;
   1014 
   1015 	macro(HOME);
   1016 	if (!fname) {
   1017 		filename = "<stdin>";
   1018 		filep = stdin;
   1019 	} else {
   1020 		filename = fname;
   1021 		if ((filep = fopen(fname, "r")) == NULL)
   1022 			eprintf("%s:", fname);
   1023 	}
   1024 
   1025 	run();
   1026 	fclose(filep);
   1027 }
   1028 
   1029 static void
   1030 usage(void)
   1031 {
   1032 #if FEATURE_BC_QUIET
   1033 	eprintf("usage: %s [-p dc][-cdlqs]\n", argv0);
   1034 #else
   1035 	eprintf("usage: %s [-p dc][-cdls]\n", argv0);
   1036 #endif
   1037 }
   1038 
   1039 int
   1040 main(int argc, char *argv[])
   1041 {
   1042 	ARGBEGIN {
   1043 	case 'p':
   1044 		dcprog = EARGF(usage());
   1045 		break;
   1046 	case 'c':
   1047 		cflag = 1;
   1048 		break;
   1049 	case 'd':
   1050 		dflag = 1;
   1051 		yydebug = 3;
   1052 		break;
   1053 	case 'l':
   1054 		lflag = 1;
   1055 		break;
   1056 #if FEATURE_BC_QUIET
   1057 	// for compat with sucky impls
   1058 	case 'q':
   1059 		break;
   1060 #endif
   1061 	case 's':
   1062 		sflag = 1;
   1063 		break;
   1064 	default:
   1065 		usage();
   1066 	} ARGEND
   1067 
   1068 	yytext  = malloc(BUFSIZ);
   1069 	buffcap = BUFSIZ;
   1070 	buff    = malloc(buffcap);
   1071 	if (!yytext || !buff)
   1072 		eprintf("out of memory\n");
   1073 	flowid = 128;
   1074 
   1075 	if (!cflag)
   1076 		spawn();
   1077 	if (lflag)
   1078 		bc(PREFIX "/share/misc/bc.library");
   1079 
   1080 	// stdin is the script only when no file was given. with a file plus
   1081 	// piped data (echo $HZ | bc -q file.bc) the data is for read()
   1082 	if (!*argv) {
   1083 		bc(NULL);
   1084 	} else {
   1085 		while (*argv)
   1086 			bc(*argv++);
   1087 	}
   1088 
   1089 	quit();
   1090 }