c++ - 如何在 Bison 解析器上返回多个标记?

标签 c++ parsing lex lexer

我的语法是这样的

decl:

   attributes;  {/*create an object here with the attributes $$?*/ }


attributes:



  |

  att1 attributes {$$ = $1;}

  |

  att2 attributes {$$ = $1;}

  |

  attn attributes {$$ = $1;};

我想获取用户输入的所有属性,有些是可选的,顺序无所谓,类型不同

最佳答案

您需要在您的$$ 变量中返回一个结构;根据需要分配给其成员。这是我手头的一些代码的示例:

struct value_list {
    char *value;
    struct value_list *next;
};

# ...

valuelist:  TOK_VALUE
    {
        struct value_list *new = calloc(1, sizeof(struct value_list));
        if (!new)
            yyerror(_("Memory allocation error."));
        PDEBUG("Matched: value (%s)\n", $1);

        new->value = $1;
        new->next = NULL;
        $$ = new;
    }

valuelist:  valuelist TOK_VALUE
    {
        struct value_list *new = calloc(1, sizeof(struct value_list));
        if (!new)
            yyerror(_("Memory allocation error."));
        PDEBUG("Matched: value (%s)\n", $1);

        new->value = $2;
        new->next = $1;
        $$ = new;
    }

来自同一解析器的另一个示例,它比上述更简单的规则更努力地根据条目自定义 struct;缺点是这变得相当复杂,但优点是这是对单个对象属性的更好演示:

/* from a header file */
struct codomain {
    char *namespace;
    char *name;             /* codomain name */
    char *attachment;
    struct alt_name *altnames;
    void *xmatch;
    size_t xmatch_size;
    int xmatch_len;
    /* ... and it goes on like this ... */
}

# from the grammar:

profile_base: TOK_ID opt_id flags TOK_OPEN rules TOK_CLOSE
    {
        struct codomain *cod = $5;

        if (!cod) {
            yyerror(_("Memory allocation error."));
        }

        cod->name = $1;
        cod->attachment = $2;
        if ($2 && $2[0] != '/')
            /* we don't support variables as part of the profile
             * name or attachment atm
             */
            yyerror(_("Profile attachment must begin with a '/'."));
        cod->flags = $3;
        if (force_complain)
            cod->flags.complain = 1;

        post_process_nt_entries(cod);
        PDEBUG("%s: flags='%s%s'\n",
               $3,
               cod->flags.complain ? "complain, " : "",
               cod->flags.audit ? "audit" : "");

        $$ = cod;

    };

关于c++ - 如何在 Bison 解析器上返回多个标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7923858/

相关文章:

c++ - 如何使用 QDeclarative 将 QMap 公开给 QML

linux - 在 expect 输出中搜索单词

yacc - 多个 flex/bison 解析器

c++ - Lex/Yacc 解析器解析列中包含标题和值的文件

android - 使用动态数组和对象处理 gson

c - 在以下 lex/yacc 文件中接收段错误(核心转储)。他们怎么了?

c++ - 隐式转换和复制构造函数

c++ - 堆栈及其实现

c++ - 如何在 Visual Studio 2015 中构建 log4cxx

java - java中的XML解析: ignore tags as value