【发布时间】:2011-03-27 23:57:13
【问题描述】:
我正在尝试在 PHP 中为以下 EBNF 编写递归下降解析器:
EXP ::= < TERM > { ( + | - ) < TERM > }
TERM ::= < FACTOR > { ( * | / ) < FACTOR > }
FACTOR ::= ( < EXP > ) | < DIGIT >
DIGIT ::= 0 | 1 | 2 | 3
我关注了这个guide,我在一个类似的问题上看到了它的推荐。 (发帖前我搜索过)
在大多数情况下,我了解它的工作原理并理解语法。我认为问题出在我的语法之内。我是 PHP 新手,所以我一直在引用 W3Schools。我的代码目前出现以下错误:
Warning: Wrong parameter count for exp() .... on line 101
我曾尝试查找此错误,但运气不佳。我阅读了一些关于人们输入错误参数的帖子,但我没有为该函数设置任何参数。我在这里缺少关于 PHP 的一些东西吗?
下面是我的代码,我认为逻辑是正确的,因为我基于语法的解析树。 $input 将来自 HTML 页面上的表单框。当我发现 PHP4 没有内置 str_split 函数时,我还从另一篇文章中选择了它。
<html>
<body>
<?php
if(!function_exists("exp")){
function exp(){
term();
while($token == "+" | $token == "-"){
if($token == "+"){
match("+");
term();
}
if($token == "-"){
match("-");
term();
}
}
}//end exp
}
if(!function_exists("term")){
function term(){
factor();
while($token == "*" | $token == "/"){
if($token == "*"){
match("*");
factor();
}
if($token == "/"){
match("/");
factor();
}
}
}//end term
}
if(!function_exists("factor")){
function factor(){
if($token == "("){
match("(");
exp();
if($token == ")")
match(")");
}
else if($token == 0|1|2|3){
if($token == 0)
match(0);
if($token == 1)
match(1);
if($token == 2)
match(2);
if($token == 3)
match(3);
}
else
error();
}//end factor
}
if(!function_exists("match")){
function match($expected){
if($token == $expected)
nextToken();
else
error();
}//end match
}
if(!function_exists("next_Token")){
function nextToken(){
$next++;
$token = $tokenStr[$next];
if($token == "$");
legal();
}
}
if(!function_exists("error")){
function error(){
echo "Illegal token stream, try again";
}
}
if(!function_exists("legal")){
function legal(){
echo "Legal token stream, congrats!";
}
}
if(!function_exists('str_split')) {
function str_split($string, $split_length = 1) {
$array = explode("\r\n", chunk_split($string, $split_length));
array_pop($array);
return $array;
}
}
$tokenStr = str_split($input);
$next = 0;
$token = $tokenStr[0];
exp();
?>
</body>
</html>
所以基本上我想知道是什么导致了这个错误,为什么我在创建这个解析器方面是正确的。
感谢任何 cmets、建议、批评、水气球和西红柿。感谢您花时间阅读我的帖子。度过美好的一天/一夜。
【问题讨论】:
-
对不起,一个疯狂的猜测,但这不是与数学中的
exp()函数发生某种冲突:php.net/manual/en/function.exp.php 吗? -
谢谢,就是这样,但现在一切都正确编译,没有输出。我的猜测是它没有得到传入的输入。我的函数访问全局变量的方式有问题吗?
标签: php syntax recursion recursive-descent