在 python 中重命名“def”(和其他关键字)[关闭]

2023-12-11

我正在尝试为自定义语言编写一个“解释器”。

该语言与 python 非常相似,但也有一些区别,例如:

Python:

def subRoutine():
    print("hello")

Custom:

sub subRoutine()
    print("hello")

解决这个问题的最佳方法是什么? 我应该修改 python 源代码并重新编译吗?我可以编写一个允许我在如此低级别修改内容的库吗?

Cheers


我会从这个文件,请记住:

更改此文件中指定的语法很可能需要在解析器模块 (../Modules/parsermodule.c) 中进行相应的更改。

At line 27:

funcdef: 'def' NAME parameters ['->' test] ':' suite

然而,语法不应该因为简单的替换而改变def,但 stdlib 的整个 Python 代码将受到此更改的严重影响。


我自己测试过,使用这个源 tarball,并替换'def' by 'createfunc' in the Grammar文件。 但是,在 CPython 编译过程中,会出现以下错误:

Fatal Python error: Py_Initialize: Unable to get the locale encoding
  File "/udd/lbourneu/Documents/projects/cpython/Python-3.4.4/Lib/encodings    /__init__.py", line 42
    def normalize_encoding(encoding):
                     ^
SyntaxError: invalid syntax

您必须更换任何def通过新语句来编译Python代码。

注意:使用find . -type f -name "*" -exec sed -i 's/def /createfunc /g' {} +是不足够的:

/usr/bin/mkdir -p Include
python3.4 ./Parser/asdl_c.py -h Include ./Parser/Python.asdl
  File "./Parser/asdl_c.py", line 14
    createfunc get_c_type(name):
                    ^
SyntaxError: invalid syntax

命令python3.4 ./Parser/asdl_c.py -h Include ./Parser/Python.asdl and 这条评论显示问题:你需要一个python来编译python,并且两者都需要了解相同的源代码。 介绍的技巧链接文章就是添加一个关键字而不是替换它。

稍后,您可以编译使用第二个Python的第三个Python(它理解两者)def and sub)进行编译,其语法中 def 关键字已被新关键字完全替换。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 python 中重命名“def”(和其他关键字)[关闭] 的相关文章

随机推荐