我目前正在手动构建解析器。这是一个LL(1)解析器。目前,它是一个很好的识别器:它的函数parse(List tokens)决定tokens是否属于该语言。
现在,我想为该输入构建相应的AST。然而,我知道如何以递归下降的方式实现它(已经完成)。也就是说,在这个挑战中,我使用经典算法的堆栈来实现我的堆栈:
next <- first token of the input
stack <- START_SYMBOL
do {
top <- stack.pop()
if (top is a terminal and top == next) {
next <- next token of the input
} else if (top is a non terminal and PARSING_TABLE[top, next] exists) {
stack.push(PARSING_TABLE[top, next]);
} else {
return invalid input;
}
} while (stack is not empty);
return valid input;
其中 PARSING_TABLE 是 LL(1) 表。然而,我想知道如何在这种配置下实现构建 AST 的部分。我不是要求完整的实现,而是需要实现的思路。
谢谢!