python – 解析的部分评估
作者:互联网
我正在研究Python的宏系统(as discussed here),其中一个我一直在考虑的是测量单位.尽管可以在没有宏或通过静态宏的情况下实现度量单位(例如,提前定义所有单元),但我正在考虑允许在运行时动态扩展语法.
为此,我正在考虑在编译时对代码进行一种部分评估.如果给定表达式的解析失败,由于其语法不可用的宏,编译器将停止对函数/块的评估,并生成已经具有未知表达式的存根的代码.在运行时命中此存根时,将针对当前宏集重新编译该函数.如果此编译失败,将抛出解析错误,因为执行无法继续.如果编译成功,则新函数将替换旧函数并继续执行.
我看到的最大问题是,在运行受影响的代码之前,您无法找到解析错误.但是,这不会影响很多情况,例如:像[],{},()和“这样的组操作符仍然需要配对(我的标记器/列表解析器的要求),并且像类和函数这样的顶级语法不会受到影响,因为它们的“运行时”是实际加载时间,评估语法并生成其对象.
除了上面描述的实施难度和问题,这个想法有什么问题?
解决方法:
以下是一些可能的问题:
>如果出现问题,您可能会发现很难向用户提供有用的错误消息.这似乎很可能,因为任何编译时语法错误都可能只是语法扩展.
>表现受到打击.
我试图在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,macros,parsing,language-design 来源: https://codeday.me/bug/20190730/1585268.html