%code requires {
/* pull in types to populate YYSTYPE: */
#include "src/parse/ast.h"
namespace re2c {
    struct AstNode;
}
}

%{

#include <stdio.h>
#include <stdlib.h>

#include "src/parse/ast.h"
#include "src/util/attribute.h"
#include <stdint.h>
#include "lib/lex.h"

#pragma GCC diagnostic push
#include "src/util/nowarn_in_bison.h"

using namespace re2c;
%}

%define api.pure full
%define api.prefix {re2c_lib_}
%lex-param {const uint8_t*& pattern}
%lex-param {re2c::Ast& ast}
%parse-param {const uint8_t*& pattern}
%parse-param {re2c::Ast& ast}

%start regexp

%union {
    const re2c::AstNode* regexp;
    re2c::AstBounds bounds;
};

%{
extern "C" {
    static int yylex(YYSTYPE* yylval, const uint8_t*& pattern, Ast& ast);
    static void yyerror(const uint8_t* pattern, Ast&, const char* msg) RE2C_ATTR((noreturn));
}

%}

%token TOKEN_COUNT
%token TOKEN_ERROR
%token TOKEN_REGEXP

%type <regexp> TOKEN_REGEXP regexp expr term factor primary
%type <bounds> TOKEN_COUNT

%%

regexp: expr { regexp = $$; };

expr
: term
| expr '|' term { $$ = ast.alt($1, $3); }
;

term
: factor
| factor term { $$ = ast.cat($1, $2); } // in POSIX concatenation is right-associative
;

factor
: primary
| primary '*'         { $$ = ast.iter($1, 0, Ast::MANY); }
| primary '+'         { $$ = ast.iter($1, 1, Ast::MANY); }
| primary '?'         { $$ = ast.iter($1, 0, 1); }
| primary TOKEN_COUNT { $$ = ast.iter($1, $2.min, $2.max); }
;

primary
: TOKEN_REGEXP
| '(' ')'      { $$ = ast.cap(ast.nil(NOWHERE), CAPTURE); }
| '(' expr ')' { $$ = ast.cap($2, CAPTURE); }
;

%%

#pragma GCC diagnostic pop

extern "C" {
    static void yyerror(const uint8_t* pattern, Ast&, const char* msg) {
        fprintf(stderr, "%s (on regexp %s)", msg, pattern);
        exit(1);
    }

    static int yylex(YYSTYPE* yylval, const uint8_t*& pattern, Ast& ast) {
        return lex(yylval, pattern, ast);
    }
}

namespace re2c {

const AstNode* parse(const char* pattern, Ast& ast) {
    const uint8_t *p = reinterpret_cast<const uint8_t*>(pattern);
    yyparse(p, ast);
    return regexp;
}

} // namespace re2c
