Yacc and Bison Parser Grammar Definitions
1. Basic Structure and Token Definitions
typedef struct s_attr { int value; char *code; } t_attr;
#define YYSTYPE t_attr%token N ID INTEGER STRING MAIN WHILE%token AND OR IGUAL DISTINTO MENORIGUAL MAYORIGUAL
Operator Precedence
%right '='%left OR%left AND%left IGUAL DISTINTO%left '<' '>' MENORIGUAL MAYORIGUAL%left '+' '-'%left '*' '/' '%'%left UNARY_SIGN
2. Grammar Rules and Semantic Actions
Variable and Main Function Parsing
a: dg dm
dg: /* */ | dg INTEGER lv ';' { p("%s\n", $3.c); }
lv: ID { sp(t, "(setq %s 0)", $1.c); $$.c = gc(t); }| ID '=' N { sp(t, "(setq %s %d)", ... )| lv ',' ID { sp(t, "%s (setq %s 0)", ... )| lv ',' ID '=' N { sp(t, "%s (setq %s %d)", ... )
dm: MAIN '(' ')' '{' ap '}' { p("(defun main ()\n %s\n)\n", $5.c); }
Control Flow and Expressions
ap: /* */ { $$.c = gc(""); }| ap sentencia ';' { sp(t, "%s\n %s", $1.c, $2.c); $$.c = gc(t); }| ap WHILE '(' e ')' '{' ap '}' { sp(t, "%s\n (loop while %s do\n %s)", $1.c, $4.c, $7.c); $$.c = gc(t); }
3. Advanced Functionality and AST Generation
This section covers complex structures including IF, FOR, SWITCH, and ARRAY handling, as well as Abstract Syntax Tree (AST) generation patterns for different compiler targets.
Function and Loop Logic
fun: ID { strcpy(current_scope, $1.c); local_sym_count = 0; } '(' param ')' '{' cf '}' { sp(t, "(defun %s (%s)\n %s\n)", $1.c, $4.c, $7.c); ... }
Case and Array Handling
lc: CASE N':' cf BREAK ';' { sp(t, "(%d\n %s)", $2.V, $4.c); $$.c = gc(t); }| ID '[' N']' { av($1.c); sp(t, "(setq %s (make-array %d))", gvn($1.c), $3.V); $$.c = gc(t); }
