使用有趣的类型(如 std::string)来保存一些令牌类型
Using interesting types like std::string to hold some token types
我有一个用flex和bison编写的很棒的解析器,它成功地用老式语言解析了一个曲折的混淆程序(没有一个移位/移位或移位/减少冲突)。下一步,构建 AST。
现在,我想使用出色的 C++11 资源管理非 POD 类型(如 std::string
)将代币从 flex 传递到野牛。问题是,YYSTYPE
是一个union
。
假设我可能会通过std::string
或int
来获取代币。我可以使用boost::variant
或手工制作的版本,但是有没有办法告诉野牛和弹性不要使用工会?
我最近遇到了完全相同的问题。我通过以下方式解决了它:我在联合中使用了 char*(或者更好的是,我用于提高类型安全性的结构),但一旦我将字符串分配给我的数据结构,就会转换为 std::string。
所以我有(代码显着缩短)
struct parserType
{
double number;
char* string;
int stringLength;
// ...
};
并在解析器.y 文件中
%define api.value.type {struct parserType}
%token <string> STRING
// and maybe...
%type <string> LatitudeFile
%type <string> LongitudeFile
%type <string> HeightFile
// A simple non-terminal:
LatitudeFile:
/* Empty */
{
$$ = NULL;
}
| LATITUDE '=' STRING
{
$$ = ($3);
}
;
// A structure building rule:
| KEYWORD LatitudeFile LongitudeFile HeightFile GridBaseDatum
{
ss = new DataObject();
ss->rs.latShiftFile = ToStdString($2);
ss->rs.lonShiftFile = ToStdString($3);
ss->rs.heightShiftFile = ToStdString($4);
ss->rs.gridBaseDatum = ToStdString($5);
$$ = ss;
}
跟
std::string ToStdString(char* ptr)
{
std::string ret = (ptr != NULL) ? std::string(ptr + 1, (strlen(ptr) - 2)) : std::string("");
delete[] ptr; // Delete memory allocated by lexer.
return ret;
}
在词法分析器中具有以下内容:
{STRING} {
char* buf = new char[yyleng+1];
memset(buf, 0, yyleng+1);
strncpy_s(buf, yyleng +1 , yytext, _TRUNCATE);
yylval->string = buf;
yylval->stringLength = yyleng;
return STRING;
}
这可能不是最优雅的解决方案,但到目前为止,它似乎完美无缺。如果有人知道如何规避"std::string不能成为工会的一部分"问题,那可能会得到更好的解决方案。
相关文章:
- 使用char类型将decimal转换为string,将string转换为decimal
- 与'operator='不匹配(操作数类型'String'且"void")
- 如何使用 uint64_t 键类型从 std::map<int, std::string> 返回值?
- 可以从std::string继承以提供类型一致性吗
- 运算符'<'不能应用于类型 'string' 和 'string' 的操作数
- 错误:无法传递非平凡类型"std::string"的对象和更多错误
- C++:将模板类型 char 转换为 std::string
- 我正在将一个 std::string 传递给一个 boost 函数,该函数对该类型进行常量引用,但该值发生了变化
- 将"std::string {aka std::basic_string}"赋值中的不兼容类型<char>
- 错误:"cast"未命名类型void setCastDescription(std::string
- 错误:为"运算符 std::string {aka std::__cxx11::basic_string}"指定的返回类型<char>
- 包括<字符串>,使用不完整的类型"std::string"
- 附加类型安全的子类std::string
- 错误:请求从"Mstream"转换为非标量类型"std::string {aka std::basic_string<char>}"
- Arduino trim() 和 replace() 方法返回从 'void' 到非标量类型'String'请求的转换
- C++ 重载:[错误] 与'operator='不匹配(操作数类型为 'String' 和"字符串")
- C++ 在列表和列表之间选择返回类型<<string>std::p air<string,string>>
- 非 POD 元素类型 'string'(又名 '<char>basic_string')c++ 的可变长度数组
- 从文件中读取数据类型string, int double.将每一行数据放入对象向量中
- OS X 错误非 pod 元素类型 'string' 的可变长度数组