Книга: UNIX — универсальная среда программирования

3.5.3 hoc.y

3.5.3 hoc.y
%{
#include "hoc.h"
#define code2(c1,c2) code(c1); code(c2)
#define code3(c1,c2,c3) code(c1); code(c2); code(c3)
%}
%union {
 Symbol *sym; /* symbol table pointer */
 Inst *inst; /* machine instruction */
}
%token <sym> NUMBER VAR BLTIN UNDEF
%right '='
%left '+' '-'
%left '*' '/'
%left UNARYMINUS
%right '^' /* exponentiation */
%%
list: /* nothing */
 | list 'n'
 | list asgn 'n' { code2(pop, STOP); return 1; }
 | list expr 'n' { code2(print, STOP); return 1; }
 | list error 'n' { yyerrok; }
 ;
asgn: VAR '=' expr { code3(varpush,(Inst)$1.assign); }
 ;
expr: NUMBER { code2(constpush, (Inst)$1); }
 | VAR { code3(varpush, (Inst)$1, eval); }
 | asgn
 | BLTIN '(' expr ')' { code2(bltin, (Inst)$1->u.ptr); }
 | '(' expr ')'
 | expr '+' expr { code(add); }
 | expr '-' expr { code(sub); }
 | expr '*' expr { code(mul); }
 | expr '/' expr { code(div); }
 | expr '^' expr { code(power); }
 | '-' expr %prec UNARYMINUS { code(negate); }
 ;
%%
/* end of grammar */
#include <stdio.h>
#include <ctype.h>
char *progname;
int lineno = 1;
#include <signal.h>
#include <setjmp.h>
jmp_buf begin;
main(argc, argv) /* hoc4 */
 char *argv[];
{
 int fpecatch();
 progname = argv[0];
 init();
 setjmp(begin);
 signal(SIGFPE, fpecatch);
 for (initcode(); yyparse(); initcode())
  execute(prog);
 return 0;
}
static int c; /* global for use by warning() */
yylex() /* hoc4 */
{
 while ((c=getchar()) == ' ' || с == 't')
  ;
 if (c == EOF)
  return 0;
 if (c == '.' || isdigit(c)) { /* number */
  double d;
  ungetc(c, stdin);
  scanf ("%lf", &d);
  yylval.sym = install("", NUMBER, d);
  return NUMBER;
 }
 if (isalpha(c)) {
  Symbol *s;
  char sbuf[100], *p = sbuf;
  do {
   *p++ = c;
  } while ((c=getchar()) != EOF && isalnum(c));
  ungetc(c, stdin);
  *p = '';
  if ((s=lookup(sbuf)) == 0)
   s = install(sbuf, UNDEF, 0.0);
  yylval.sym = s;
  return s->type == UNDEF ? VAR : s->type;
 }
 if (c == 'n')
 lineno++;
 return c;
}
yyerror(s)
 char *s;
{
 warning(s, (char *)0);
}
execerror(s, t) /* recover from run-time error */
 char *s, *t;
{
 warning(s, t);
 longjmp(begin, 0);
}
fpecatch() /* catch floating point exceptions */
{
 execerror("floating point exception", (char*)0);
}
warning(s, t)
 char *s, *t;
{
 fprintf(stderr, "%s: %s", progname, s);
 if (t && *t)
  fprintf(stderr, " %s", t);
 fprintf(stderr, " near line %dn", lineno);
 while (c != 'n' && с != EOF)
  с = getchar(); /* flush rest of input line */
}

Оглавление книги


Генерация: 0.160. Запросов К БД/Cache: 0 / 2
поделиться
Вверх Вниз