#include <ctype.h>
#include <limits.h>
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#include "lptypes.h"
#include "lpcap.h"
#include "lpcode.h"
#include "lpprint.h"
#include "lptree.h"
#include "lpcset.h"
/* number of siblings for each tree */
const byte numsiblings[] = {
0, 0, 0, /* char, set, any */
0, 0, 0, /* true, false, utf-range */
1, /* acc */
2, 2, /* seq, choice */
1, 1, /* not, and */
0, 0, 2, 1, 1, /* call, opencall, rule, prerule, grammar */
1, /* behind */
1, 1 /* capture, runtime capture */
};
static TTree *newgrammar (lua_State *L, int arg);
/*
** returns a reasonable name for value at index 'idx' on the stack
*/
static const char *val2str (lua_State *L, int idx) {
const char *k = lua_tostring(L, idx);
if (k != NULL)
return lua_pushfstring(L, "%s", k);
else
return lua_pushfstring(L, "(a %s)", luaL_typename(L, idx));
}
/*
** Fix a TOpenCall into a TCall node, using table 'postable' to
** translate a key to its rule address in the tree. Raises an
** error if key does not exist.
*/
static void fixonecall (lua_State *L, int postable, TTree *g, TTree *t) {
int n;
lua_rawgeti(L, -1, t->key); /* get rule's name */
lua_gettable(L, postable); /* query name in position table */
n = lua_tonumber(L, -1); /* get (absolute) position */
lua_pop(L, 1); /* remove position */
if (n == 0) { /* no position? */
lua_rawgeti(L, -1, t->key); /* get rule's name again */
luaL_error(L, "rule '%s' undefined in given grammar", val2str(L, -1));
}
t->tag = TCall;
t->u.ps = n - (t - g); /* position relative to node */
assert(sib2(t)->tag == TRule);
sib2(t)->key = t->key; /* fix rule's key */
}
/*
** Transform left associative constructions into right
** associative ones, for sequence and choice; that is:
** (t11 + t12) + t2 => t11 + (t12 + t2)
** (t11 * t12) * t2 => t11 * (t12 * t2)
** (that is, Op (Op t11 t12) t2 => Op t11 (Op t12 t2))
*/
static void correctassociativity (TTree *tree) {
TTree *t1 = sib1(tree);
assert(tree->tag == TChoice || tree->tag == TSeq);
while (t1->tag == tree->tag) {
int n1size = tree->u.ps - 1; /* t1 == Op t11 t12 */
int n11size = t1->u.ps - 1;
int n12size = n1size - n11size - 1;
memmove(sib1(tree), sib1(t1), n11size * sizeof(TTree)); /* move t11 */
tree->u.ps = n11size + 1;
sib2(tree)->tag = tree->tag;
sib2(tree)->u.ps = n12size + 1;
}
}
/*
** Make final adjustments in a tree. Fix open calls in tree 't',
** making them refer to their respective rules or raising appropriate
** errors (if not inside a grammar). Correct associativity of associative
** constructions (making them right associative). Assume that tree's
** ktable is at the top of the stack (for error messages).
*/
static void finalfix (lua_State *L, int postable, TTree *g, TTree *t) {
tailcall:
switch (t->tag) {
case TGrammar: /* subgrammars were already fixed */
return;
case TOpenCall: {
if (g != NULL) /* inside a grammar? */
fixonecall(L, postable, g, t);
else {
|