python - 解析的部分评估

标签 python parsing macros language-design

我正在为 Python ( as discussed here ) 开发一个宏系统,我一直在考虑的事情之一是度量单位。尽管度量单位可以在没有宏的情况下或通过静态宏实现(例如,提前定义所有单位),但我正在考虑允许在运行时动态扩展语法的想法。

为此,我正在考虑在编译时对代码使用一种部分评估。如果给定表达式的解析失败,由于其语法的宏不可用,编译器会停止对函数/ block 的评估,并生成它已有的代码,其中包含未知表达式所在的 stub 。在运行时命中此 stub 时,将针对当前宏集重新编译该函数。如果此编译失败,则会抛出解析错误,因为无法继续执行。如果编译成功,则新函数替换旧函数并继续执行。

我看到的最大问题是,在受影响的代码运行之前,您无法找到解析错误。但是,这不会影响很多情况,例如[]、{}、() 和 `` 等组运算符仍然需要配对(我的分词器/列表解析器的要求),并且类和函数等顶级语法不会受到影响,因为它们的“运行时”是真正的加载时间,其中评估语法并生成它们的对象。

除了实现难度和我上面描述的问题,这个想法还有什么问题?

最佳答案

这里有几个可能的问题:

  • 您可能会发现很难在出现问题时向用户提供有用的错误消息。这似乎很可能,因为任何编译时语法错误都可能只是语法扩展。
  • 性能下降。

我试图找到一些关于 Perl 6 中动态解析的优点、缺点和/或实现的讨论,但找不到任何合适的内容。但是,您可能会发现 Nicklaus Wirth(Pascal 和其他语言的设计者)的这句话很有趣:

The phantasies of computer scientists in the 1960s knew no bounds. Spurned by the success of automatic syntax analysis and parser generation, some proposed the idea of the flexible, or at least extensible language. The notion was that a program would be preceded by syntactic rules which would then guide the general parser while parsing the subsequent program. A step further: The syntax rules would not only precede the program, but they could be interspersed anywhere throughout the text. For example, if someone wished to use a particularly fancy private form of for statement, he could do so elegantly, even specifying different variants for the same concept in different sections of the same program. The concept that languages serve to communicate between humans had been completely blended out, as apparently everyone could now define his own language on the fly. The high hopes, however, were soon damped by the difficulties encountered when trying to specify, what these private constructions should mean. As a consequence, the intreaguing idea of extensible languages faded away rather quickly.

编辑:这是 Perl 6 的 Synopsis 6: Subroutines ,不幸的是在标记形式中,因为我找不到更新的格式化版本;在“宏”中搜索。不幸的是,它不是有趣,但您可能会发现一些相关的东西,例如 Perl 6 的一次性解析规则,或抽象语法树的语法。 Perl 6 采用的方法是,宏是一个函数,在解析其参数并返回 AST 或字符串后立即执行; Perl 6 继续解析,就好像源实际上包含返回值一样。提到了错误消息的生成,但它们看起来好像如果宏返回 AST,您就可以了。

关于python - 解析的部分评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/474275/

相关文章:

python - 使用 sklearn RandomForestRegressor 时我的数据帧的 x 值是多少?

python - 我怎样才能让我的模型接受 2 个张量作为输入。我尝试过使用合并层,但我没有完全让它工作

python - 用另一张图片替换黑色背景

python - pandas 数据框中的高级滚动平均值(适用条件)

php - 如何在 php 中解析固定宽度的列文本?

c++ - 在 C++ 中使用 CImg 相乘和相加图像

c++ - 如何在二进制文件中设置内置版本号?

java - 解析一个非常复杂的嵌套 json,其结构在 JAVA 中总是在变化

c++ - 如何在 C++ 中将字符串解析为 int?

c++ - 隐藏文件时记录 C++ 宏