119 lines
2.2 KiB
C
119 lines
2.2 KiB
C
#include <stdint.h>
|
|
#include <stddef.h>
|
|
#include "rifle/parser.h"
|
|
#include "rifle/token.h"
|
|
#include "rifle/trace.h"
|
|
#include "rifle/lexer.h"
|
|
#include "rifle/state.h"
|
|
|
|
/* Symbolic token */
|
|
#define symtok(tok) \
|
|
"[" tok "]"
|
|
|
|
/* Quoted token */
|
|
#define qtok(tok) \
|
|
"'" tok "'"
|
|
|
|
/* Convert token to string */
|
|
#define tokstr1(tt) \
|
|
toktab[(tt)]
|
|
|
|
/* Convert token to string */
|
|
#define tokstr(tok) \
|
|
tokstr1((tok)->type)
|
|
|
|
/* Unexpected end of file */
|
|
#define ueof(state) \
|
|
trace_error( \
|
|
(state), \
|
|
"unexpected end of file\n" \
|
|
);
|
|
|
|
/*
|
|
* Table used to convert token constants into human
|
|
* readable strings
|
|
*/
|
|
static const char *toktab[] = {
|
|
[TT_NONE] = symtok("none"),
|
|
[TT_IDENT] = symtok("ident"),
|
|
[TT_PLUS] = qtok("+"),
|
|
[TT_MINUS] = qtok("-"),
|
|
[TT_STAR] = qtok("*"),
|
|
[TT_SLASH] = qtok("/"),
|
|
[TT_COLON] = qtok(":"),
|
|
[TT_LPAREN] = qtok("("),
|
|
[TT_RPAREN] = qtok(")"),
|
|
[TT_F] = qtok(".f"),
|
|
[TT_EXTERN] = qtok(".extern"),
|
|
[TT_DEFINE] = qtok("#define")
|
|
};
|
|
|
|
/*
|
|
* Parse-side token scan function
|
|
*
|
|
* @state: Compiler state
|
|
* @tok: Last token
|
|
*
|
|
* Returns zero on success
|
|
*/
|
|
static int
|
|
parse_scan(struct rifle_state *state, struct token *tok)
|
|
{
|
|
struct token *popped;
|
|
|
|
if (state == NULL || tok == NULL) {
|
|
return -1;
|
|
}
|
|
|
|
switch (state->pass_num) {
|
|
case 0:
|
|
if (lexer_scan(state, tok) < 0) {
|
|
return -1;
|
|
}
|
|
|
|
break;
|
|
case 1:
|
|
if ((popped = tokbuf_pop(&state->tokbuf)) == NULL) {
|
|
return -1;
|
|
}
|
|
|
|
*tok = *popped;
|
|
break;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
static int
|
|
parse_preprocess(struct rifle_state *state)
|
|
{
|
|
struct token tok;
|
|
|
|
while (parse_scan(state, &tok) == 0) {
|
|
trace_debug("got token %s\n", tokstr(&tok));
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
int
|
|
parser_parse(struct rifle_state *state)
|
|
{
|
|
if (state == NULL) {
|
|
return 0;
|
|
}
|
|
|
|
switch (state->pass_num) {
|
|
case 0:
|
|
/* Pre-processor */
|
|
if (parse_preprocess(state) < 0) {
|
|
return -1;
|
|
}
|
|
|
|
break;
|
|
}
|
|
|
|
++state->pass_num;
|
|
return 0;
|
|
}
|