如何使用Struct使用Tree创建Expression Parser

如何解决如何使用Struct使用Tree创建Expression Parser

我有一个我不明白的问题。我想创建一个表达式解析器。因此,首先,我为该解析器创建了一棵树。就是这样。

enum {
    integer,plus,minus,multi,divis,string,character
};

struct Tree {
    int operation;
    struct Tree *left;
    struct Tree *right;
    char *value;
};

struct Tree *make_node(int operation,struct Tree *left,struct Tree *right,char *value) {
    struct Tree *n;
    
    n = (struct Tree *)malloc(sizeof(struct Tree));
    
    if(n == NULL) {
        printf("Unable to malloc \'make_node()\'\n");
    }
    
    n -> operation = operation;
    n -> left = left;
    n -> right = right;
    n -> value = value;
    
    return n;
}

// Print ostorder
int print_post_order_data(struct Tree *n) {
    if(n == NULL) {
        return 0;
    }
    
    print_post_order_data(n -> left);   
    print_post_order_data(n -> right);
    
    printf("Operation => %d \t Value => %s\n",n -> operation,n -> value);
}

int main(void) {
    struct Tree *m;
    
    // Expression is ( 2 + 3 * 5 - 8 / 3 )
    m = make_node(plus,NULL,NULL);
    m -> left = make_node(minus,NULL);
    m -> right = make_node(integer,"2");
    m -> left -> left = make_node(multi,NULL);
    m -> left -> right = make_node(divis,NULL);
    m -> left -> left -> left = make_node(integer,"3");
    m -> left -> left -> right = make_node(integer,"5");
    m -> left -> right -> left = make_node(integer,"8");
    m -> left -> right -> right = make_node(integer,"3");

    print_post_order_data(n);

    return 0;
}

您可以看到我已经为表达手动创建了树。表达式为 2 + 3 * 5-8/3

假设该程序可以将 2 标识为数字,将 + 标识为加号,等等。我如何为此编写解析器。也就是说,要创建如上所述的节点?能告诉我这个的代码代码吗?

下面是更多信息

e.g. => 1 + 2 * 3

The tree is,+
               / \
              /   \
             *     1
            / \
           /   \
          2     3

1 + 2 * 3 => 1 + ( 2 * 3 )

So manually I can create tree like this.

    struct Tree *n;
    n = make_node(plus,NULL);
    n -> left = make_node(multi,NULL);
    n -> right = make_node(integer,"1");
    n -> left -> left = make_node(integer,"2");
    n -> left -> right = make_node(integer,"3");

我试图创建一个这样的解析器。

addictive_expression() {
    multiplicative_expression()

    while(1) {
        multiplicative_expression()

        ....
    }
}


multiplicative_expression() {
    primary_expression()

    while(+ || * || /) {
        primary_expression()

        ....
    }
}

primary_expression() {
    switch(current token) {
        case integer:
             ....
             ....
    }
}

尽管我试图通过这种方式来实现,但是我很难弄清楚如何将树连接到它。

编辑1

  1. 我想创建一个解析器而不使用Bison等工具。
  2. 已完成所需的词法分析器

编辑2:

// This is the Source of Struct Tree
struct TREE {
        int operation;
        struct TREE *left;
        struct TREE *right;
        char *value;
} Tree;

struct TREE *create_new_node(int operation,struct TREE *left,struct TREE *right,char value[MAX_LENG]) {
        struct TREE *n;

        n = (struct TREE *) malloc (sizeof(struct TREE));

        if(n == NULL) {
                fatal("Unable to Malloc New Structure TREE in \'create_new_node()\' Function in tree.c File");
        }

        n -> operation = operation;
        n -> left = left;
        n -> right = right;
        n -> value = value;

        return n;
}

// This is the Source of Parser
int expression(void) {
        next_token(); // This Function will get the next Token

        addictive_expression();
}

int addictive_expression(void) {
        int token_type;

        multiplicative_expression();

        token_type = Token.current_token; // Token.current_token is the Current Token
        if(token_type == END_FILE) {
                return 0;
        }

        while(1) {
                next_token();

                multiplicative_expression();
                
                token_type = Token.current_token;
                if(token_type == END_FILE) { // End File is a Enum
                        return 0;
                }
        }

        return 0;
}

int multiplicative_expression(void) {
        int token_type;

        primary_expression();

        token_type = Token.current_token;
        if(token_type == END_FILE) {
                return 0;
        }

        // O_MLTI,O_DIVS. O_MUDL are the tokens ( Enum )
        while(token_type == O_MLTI || token_type == O_DIVS || token_type == O_MUDL) {
                next_token();

                primary_expression();

                token_type = Token.current_token;
                if(token_type == END_FILE) {
                        return 0;
                }
        }

        return 0;
}

int primary_expression(void) {
        switch(Token.current_token) {
                case INTEGER:
                        next_token();
                        break;
                
                case O_PLUS:
                case O_MNUS:
                case O_MLTI:
                case O_DIVS:
                case O_MUDL:
                        next_token();
                        break;
                
                default:
                        error_d("Syntax Error in Primary Expression",Token.current_token); // Custom Error Message
                        break;
        }

        return 0;
}

/*
    struct Tree *m;

    m = make_node(plus,"3");
*/

我很难弄清楚如何将树连接到它。您能为我提供解决方案吗?

解决方法

语法的非终结符由返回自己的子表达式的函数实现,在您的情况下,该子表达式由struct Tree *表示。

这允许在递归调用时构造树。

所以基本上您的addictive_expression应该看起来像这样:

static struct Tree *addictive_expression() {
    struct Tree *expr = multiplicative_expression();
    while (token->type == OPERATOR && (token->op == PLUS || token->op == MINUS)) {
        Operator op = token->op;
        token = next_token();
        struct Tree *expr2 = multiplicative_expression();
        switch (op) {
            case PLUS:
                expr = create_new_node(OPERATOR,PLUS,expr,expr2,NULL);
                break;
            case MINUS:
                expr = create_new_node(OPERATOR,MINUS,NULL);
                break;
        }
    }
    return expr;
}

它如何工作:

它调用multiplicative_expression,后者依次调用其他函数以获取表达式。在递归降序分析的简单形式中,每个优先级都有一个单独的函数。由于PLUS和MINUS是左关联运算符,因此将它们循环处理。如果存在相同优先级的连续操作,则在创建新节点时会将上一个节点设置为左表达式。

为了更好地理解,我在其中添加了带有PLUS和MINUS大小写的switch语句,但是如您所见,您可以将其简化为:

static struct Tree *multiplicative_expression() {
    struct Tree *expr = value_expression();
    while (token->type == OPERATOR && (token->op == MULT || token->op == DIV)) {
        Operator op = token->op;
        token = next_token();
        struct Tree *expr2 = value_expression();
        expr = create_new_node(OPERATOR,op,NULL);
    }
    return expr;
}

这里只是运算符用于创建新节点。

数据结构

注意:类型和运算符是分开的。

typedef enum  {
    NONE,END,NUMERIC,OPERATOR
} Type;

typedef enum {
    INVALID,MULT,DIV
} Operator;

typedef struct {
    Type type;
    Operator op;
    char *value;
} Token;

然后,树结构为:

struct Tree {
    Type type;
    Operator op;
    struct Tree *left;
    struct Tree *right;
    char *value;
};

完整示例

一个小而完整的示例(函数名称基于问题中的示例代码片段)可能看起来像这样,具有两个优先级:

  • */
  • +-
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "parser.h"
#include "lexer.h"

static Token *token;

static void fatal(char *msg) {
    fprintf(stderr,"%s\n",msg);
    exit(1);
}

static struct Tree *create_new_node(Type type,Operator operation,struct Tree *left,struct Tree *right,char *value) {
    struct Tree *n = (struct Tree*) malloc(sizeof(struct Tree));
    if (n == NULL) {
        fatal("Unable to Malloc New Structure Tree in \'create_new_node()\' Function in tree.c File");
    }
    n->type = type;
    n->op = operation;
    n->left = left;
    n->right = right;
    n->value = value;
    return n;
}


static struct Tree *value_expression() {
    if (token->type == NUMERIC) {
        struct Tree *result = create_new_node(NUMERIC,NONE,NULL,strdup(token->value));
        token = next_token();
        return result;
    }
    fatal("can't determine value for token");
}

static struct Tree *multiplicative_expression() {
    struct Tree *expr = value_expression();
    while (token->type == OPERATOR && (token->op == MULT || token->op == DIV)) {
        Operator op = token->op;
        token = next_token();
        struct Tree *expr2 = value_expression();
        expr = create_new_node(OPERATOR,NULL);
    }
    return expr;
}

static struct Tree *addictive_expression() {
    struct Tree *expr = multiplicative_expression();
    while (token->type == OPERATOR && (token->op == PLUS || token->op == MINUS)) {
        Operator op = token->op;
        token = next_token();
        struct Tree *expr2 = multiplicative_expression();
        expr = create_new_node(OPERATOR,NULL);
    }
    return expr;
}

struct Tree *expression() {
    token = next_token();
    struct Tree *expr = addictive_expression();
    putback_token(token);
    return expr;
}

树输出

#include <stdio.h>
#include <stdlib.h>
#include "lexer.h"
#include "parser.h"

void test_parser();

int main(void) {
    test_parser();
    return 0;
}

void print_expr(struct Tree *expr,int level) {
    for(int i = 0; i < level; i++) {
        printf("  |  ");
    }
    switch(expr->type) {
        case OPERATOR:
            switch(expr->op) {
                case INVALID:
                    fprintf(stderr,"invalid op\n");
                    exit(1);
                case PLUS:
                    printf("+\n");
                    print_expr(expr->left,level + 1);
                    print_expr(expr->right,level + 1);
                    printf("\n");
                    break;
                case MINUS:
                    printf("-\n");
                    print_expr(expr->left,level + 1);
                    printf("\n");
                    break;
                case MULT:
                    printf("*\n");
                    print_expr(expr->left,level + 1);
                    printf("\n");
                    break;
                case DIV:
                    printf("/\n");
                    print_expr(expr->left,level + 1);
                    printf("\n");
                    break;
            }
            break;
        case NUMERIC:
            printf("%s\n",expr->value);
            break;
        case NONE:
            fprintf(stderr,"unexpected NONE\n");
            exit(1);
        case END:
            fprintf(stderr,"unexpected END\n");
            exit(1);
    }
}

void test_parser() {
    setup_lexer("../input.txt");
    struct Tree *expr = expression();
    print_expr(expr,0);
}

结果

对于输入2 + 3 * 5 - 8 / 3,上面的小型测试程序将以下内容输出到调试控制台:

-
  |  +
  |    |  2
  |    |  *
  |    |    |  3
  |    |    |  5


  |  /
  |    |  8
  |    |  3

看起来像正确的语法树!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-