帮助解析S-Expression
Help parsing S-Expression
本文关键字:S-Expression 帮助 更新时间:2023-10-16
我正在尝试制作一个在translate (rect 10 10 10 10) 50 50
中读取的简单绘图程序。我想做的是将其拆分,使50 50
与translate
一起使用,rect
保留所有10
s。
这是PostScript填充。我听说过哈希表和堆栈,但我不知道如何使用它们。其他的我都做了(例如所有形状的计算)。我只是不明白如何解析这些行,以便得到指向正确变量的数字。
您的示例看起来像Lisp s表达式,所以请尝试搜索"s表达式解析器"。出现了一些点击。
如果你想"全力以赴",你可以将你的shape例程实现为C++类,使用SWIG将它们公开给GNUGuile,并用Scheme编写你的应用程序。不过,这可能不是你想的。:-)
这可能有点过时,但它很简单,没有什么比这更快的了。
void scanWhite(char*& p){
while(*p==' ') p++;
}
bool seeInt(char*& p, int& num){
scanWhite(p);
char* p1 = p;
bool bNegative = false;
if (*p=='-'){bNegative = true; p++;)
if (!isdigit(*p){p = p1; return false;}
num = 0;
while(isdigit(*p)){
num *= 10;
num += (*p - '0');
p++;
}
if (bNegative) num = - num;
return true;
}
bool seeWord(char*& p, char* word){
scanWhite(p);
int len = strlen(word);
if (strncmp(p, word, len)==0 && !isalphanumeric(p[len])){
p += len;
return true;
}
else return false;
}
bool seeChar(char*& p, char c){
scanWhite(p);
if (*p != c) return false;
p++;
return true;
}
bool parseTranslateRect(char*& p
, int& x0, int& y0, int& x1, int& y1
, int& dx, int& dy
)
{
if (!seeChar(p, '(')) return false;
if (!seeWord(p, "translate")) return false;
if (!seeChar(p, '(')) return false;
if (!seeWord(p, "rect")) return false;
if (!seeInt(p, &x0)) return false;
if (!seeInt(p, &y0)) return false;
if (!seeInt(p, &x1)) return false;
if (!seeInt(p, &y1)) return false;
if (!seeChar(p, ')')) return false;
if (!seeInt(p, &dx)) return false;
if (!seeInt(p, &dy)) return false;
if (!seeChar(p, ')')) return false;
return true;
}
如果你有很多"(translate(rect…)"的副本,只需反复调用解析例程,直到它返回false
以下是如何使用AXE库编写这个C++解析器:
Rect r;
auto rect = "(rect "
& r_decimal(r.left) & space
& r_decimal(r.top) & space
& r_decimal(r.right) & space
& r_decimal(r.bottom) & space
& ')';
Point t;
auto translate = "translate " & rect
& space & r_decimal(t.x)
& space & r_decimal(t.y);
// test it
std::string str("translate (rect 10 10 10 10) 50 50");
auto match = translate(str.begin(), str.end());
这将解析PS文件中的单个翻译语句。如果您需要解析所有的translate语句,而不想为postscript格式编写一个完整的解析器,那么可以使用*r_find(translate)
规则跳过您不关心的输入。r_find(R)
规则搜索输入,直到找到规则R
为止。现在,这很容易,而且它还将生成非常快的代码,可能比用"if"-s和"else"-s手工编写的代码更快。
免责声明:我没有测试上面的代码,所以小错误是可能的。
相关文章:
- 需要帮助设置在C++中使用的Potrace
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 在指针的帮助下,文本文件中单词的频率
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 如何在Qbutton的帮助下更改Q对话框的宽度
- 需要帮助将结构数组传递给函数
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 为什么static_assert错误:即使我传递常量"expression must have a constant value"?
- C++ "error: invalid use of void expression"
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 有人可以帮助我处理正则表达式吗?
- C++调用具有 *this 属性的单个帮助程序函数
- C++:需要帮助了解运算符重载错误
- 需要以下代码的帮助,下面的代码有什么问题
- "Warning: Comma within array index expression"但逗号分隔函数参数
- CS1 项目帮助C++
- 用于检查值是否为其任何参数的帮助程序函数
- 需要有关此 if 语句的帮助
- 类型限定宏帮助程序
- 帮助解析S-Expression