You need to enable JavaScript to run this app. Bison使用C++ variant替代%union的配置报错与Scanner传值方法问询
优惠活动
大模型
产品
解决方案
定价
更多

Bison使用C++ variant替代%union的配置报错与Scanner传值方法问询

手写Scanner与Bison解析器的C++语义值适配问题

当前已实现的运行逻辑

目前已开发完成手写Scanner+Bison解析器组合的词法语法分析流程,可正确解析简化测试语句:

var x : integer

配套的Bison语法源文件当前配置如下:

%require "3.2"
%define api.pure full


%code{
#include <stdio.h>
#include <string.h>
#include "Scanner.h"
#include<iostream>
}



%code{
    int yylex(YYSTYPE *lvalp);
    #include<iostream>
    #include<string>
Scanner scanner;
void yyerror(const char *error);
}


%union {
int n;
double d;
char s[1000];
}

%token VAR COL ITYPE
%token IDENTIFIER
%token INTEGER
%token EOL

%type <s> type PrimitiveType IDENTIFIER
%type <s> INTEGER    

%%
program:
| program EOL
| program SimpleDeclaration {  }
;

SimpleDeclaration: VariableDeclaration
;

VariableDeclaration: VAR IDENTIFIER COL type {std::cout<<"defined variable " << $2 << " with type " << $4 << std::endl; }

type: IDENTIFIER
| PrimitiveType
;

PrimitiveType: ITYPE { strcpy($$, "int"); }
;

%%
int main()
{
    scanner.set_file("inp.txt");
    return yyparse();
}

void yyerror(const char *error)
{
    std::cout << "syntax error" << std::endl;
}

int yylex(YYSTYPE *lvalp)
{
    return scanner.get_next_token(lvalp);
}

当前程序的运行逻辑为:

  • scanner.get_next_token(lvalp)返回INTEGER这类词法token,在scanner.cpp中引入Bison生成的parser.tab.hpp,直接使用token对应的枚举值
  • 函数返回token前,会向lvalp写入对应语义值:比如通过strcpy(lvalp->s, nextTokenString.c_str())写入字符串、通过lvalp->n = toInt(nextTokenString)写入整数
  • 程序当前运行可正确输出:defined variable x with type int

实际遇到的阻塞问题

  • 希望在语义值存储中使用STL容器、智能指针等C++高级特性,不再依赖传统%union定义语义类型
  • 参考文档指引尝试启用C++ variant替代union时,添加%language "c++"与%define api.value.type variant配置后触发报错:parser.ypp:3.1-21: error: %define variable 'api.pure' is not used
  • Bison官方纯调用模式说明页未覆盖无union场景下,不同token对应不同语义类型时,如何通过lvalp传递语义值的实现说明

待明确的实现目标与疑问

核心目标

在不使用%union的前提下,实现手写Scanner向Parser返回token并附带对应语义值的流程,全程可自由使用C++语言高级特性。

待解答的细节疑问

  • Bison官方C++ variant示例中提到的make_Number这类语义值构造函数,是Bison内置实现还是工具自动生成的?
  • 手写next_token流程中,如何为%token定义的符号传递语义值,使其能正确映射到文法规则中的$系列变量?

内容的提问来源于stack exchange,提问作者Mohamad Ziad Alkabakibi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.25 13:06:06