帮助解析S-Expression

Help parsing S-Expression

本文关键字:S-Expression 帮助      更新时间:2023-10-16

我正在尝试制作一个在translate (rect 10 10 10 10) 50 50中读取的简单绘图程序。我想做的是将其拆分,使50 50translate一起使用,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手工编写的代码更快。

免责声明:我没有测试上面的代码,所以小错误是可能的。