PHP中EBNF的递归下降解析器

See*_*hor 6 php syntax recursion recursive-descent

我试图在PHP中为以下EBNF编写一个递归下降解析器:

EXP ::= < TERM > { ( + | - ) < TERM > }
TERM ::= < FACTOR > { ( * | / ) < FACTOR > }
FACTOR ::= ( < EXP > ) | < DIGIT >
DIGIT ::= 0 | 1 | 2 | 3
Run Code Online (Sandbox Code Playgroud)

我按照这个指南,我看到推荐的类似问题.(我发布之前搜索过)

在大多数情况下,我了解它是如何工作的,我理解语法.我认为问题在于我的语法.我是PHP的新手,所以我一直在引用W3Schools.我目前使用我的代码收到以下错误:

Warning: Wrong parameter count for exp() .... on line 101
Run Code Online (Sandbox Code Playgroud)

我试图查找这个错误并没有太多运气.我读了一些关于传入错误参数的人的帖子,但我没有为该函数设置任何参数.我有什么关于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>
Run Code Online (Sandbox Code Playgroud)

所以基本上我想知道是什么导致了这个错误以及为什么我在创建这个解析器方面走在正确的轨道上.

我感谢任何评论,建议,批评,水气球和西红柿.感谢您抽出宝贵时间阅读我的帖子.有一个美好的一天/晚上.

mar*_*rio 6

exp()是一个内置的PHP函数.您无法在该名称下定义它.

你应该没有理由if(!function_exists('在普通的PHP应用程序中使用这个习惯用法.(当包含脚本冲突或在不同位置声明相同的函数时,它通常更多地用作解决方法.)


我注意到的另一个语法问题是你使用按位OR.逻辑OR应该是||或只是or.

while($token == "*" | $token == "/"){
Run Code Online (Sandbox Code Playgroud)