%{
#include <stdio.h>
//#define YYDEBUG 1

int lineno=1;
int errors=0;
%}

%union semrec
{
    int value;
    char *name;
}
%start specification
%token <intval> CONSTANT
%token <id> IDENTIFIER
%token VOID CHAR SHORT INT UNSIGNED
%token STRUCT UNION ENUM TYPEDEF
%token INTERFACE
%%

type_specifier:
    CHAR
  | SHORT
  | INT
  | enum_specifier
  | struct_or_union_specifier
  | IDENTIFIER {}
  | VOID
;

declarator:
    pointer direct_declarator
  | direct_declarator
;

direct_declarator:
    IDENTIFIER {}
  | direct_declarator '[' CONSTANT ']'
;

pointer:
    '*'
  | '*' pointer
;

enum_specifier:
    ENUM '{' enum_list '}'
  | ENUM IDENTIFIER '{' enum_list '}'
  | ENUM IDENTIFIER
;

enum_list:
    enumerator
  | enum_list ',' enumerator
;

enumerator:
    IDENTIFIER {}
  | IDENTIFIER '=' CONSTANT {}
;

struct_or_union_specifier:
    struct_or_union IDENTIFIER '{' struct_declaration_list '}'
  | struct_or_union '{' struct_declaration_list '}'
  | struct_or_union IDENTIFIER
;

struct_or_union:
    STRUCT
  | UNION
;

struct_declaration_list:
    struct_declaration
  | struct_declaration_list struct_declaration
;

struct_declaration:
    type_specifier  struct_declarator_list ';'
;

struct_declarator_list:
    struct_declarator
  | struct_declarator_list ',' struct_declarator
;

struct_declarator:
    declarator
  | ':' CONSTANT
  | declarator ':' CONSTANT
;

declaration:
    declaration_specifiers ';'
  | declaration_specifiers declarator_list ';'
;

declaration_specifiers:
    TYPEDEF type_specifier
  | type_specifier
;

declarator_list:
    declarator
  | declarator_list
;

parameter_declaration:
    declaration_specifiers declarator
  | declaration_specifiers
;

parameter_list:
    parameter_declaration
  | parameter_list ',' parameter_declaration
;

procedure_definition:
    type_specifier IDENTIFIER '(' parameter_list ')' ';'
;

interface_body:
    procedure_definition 
  | interface_body procedure_definition 
;

interface:
    INTERFACE CONSTANT '{' interface_body '}'
;

external_declaration:
    declaration 
  | interface
  | ';'
;

specification:
    /* empty */
  | specification external_declaration
;
%%

void Usage(char *prog)
{
    fprintf(stderr, "Usage: %s file\n", prog);
}

int main(int argc, char *argv[])
{
    extern FILE *yyin;
    char command[256];

    if (argc != 2) {
        Usage(argv[0]);
        return -1;
    }

    snprintf(command, sizeof(command), "cpp %s", argv[1]);
    if ((yyin = popen(command, "r")) == NULL) {
        perror(command);
        return -1;
    }

    #if YYDEBUG
    yydebug=1;
    #endif

    yyparse();

    pclose(yyin);

    if (errors) {
        fprintf(stderr, "%d errors\n", errors);
        return -1;
    }

    return 0;
}

int yyerror(char *s)
{
    extern char *yytext;
    fprintf(stderr, "ERROR: %s at line %d (near: '%s')\n", s, lineno, yytext);
    ++errors;
}
