标签: abstract-syntax-tree

Haskell中的构造函数

这是家庭作业的摘录."Prog此数据类型应该只有一个构造函数,并用于表示窗体的程序:

read vin1 ; read vin2 ; < some statements > write vout2 ;
Run Code Online (Sandbox Code Playgroud)

这个构造函数也可以命名为Prog,它接受一个字符串作为两个输入和一个输出变量的名称."

将expProg定义为Prog类型,并将其作为上面左侧程序的抽象语法表示.这应该做如下:

expProg = Prog "x" "y" <some statements> "z"
Run Code Online (Sandbox Code Playgroud)

我是Haskell的新手,对此感到困惑.

我做了这样的构造函数.然而,这似乎不对.

data Prog = Prog String String String 
  deriving (Show,Eq)
Run Code Online (Sandbox Code Playgroud)

谁能解释一下这里发生了什么?我不明白如何制作这个构造函数.这是我为语句做的数据类型:

 data Stmt = Assing String Expr
      | WhileLoop Expr Stmt
      | Ifthen Expr Stmt
      | IfthenElse Expr Stmt Stmt
      | Composition [Stmt]
Run Code Online (Sandbox Code Playgroud)

haskell abstract-syntax-tree

0
推荐指数
1
解决办法
110
查看次数

设计像C这样的编译器

我正在开发一个类似C的编译器,我想知道编译器如何与系统包含.

编译器读完整个代码,并在完成读取当前代码后,将所有包含在一个列表和解析器中的包含存储起来?

// file main.c
#include <stdio.h> // store in one list

// continue the parse ...
int main()
{
    return 0;
}
// now, read the includes
// after finish the includes parse, gen code of sources

// just a sample
// file stdio.h
#include <types.h> // store in list
#include <bios.h>  // store in list

void printf(...)
{
}

void scanf(...)
{
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我已经开发了一个系统(只测试)来读取包含,并停止解析,阅读包含...(这是一个恶心的代码,但是,工作......)(样本的链接) - > https: //gist.github.com/4399601

顺便说一句,阅读包含的最佳方法是什么...并使用包含文件?

c compiler-construction syntax abstract-syntax-tree

0
推荐指数
1
解决办法
620
查看次数

ast.literal_eval 不工作(列表的python 字符串到列表)

我正在尝试将列表的以下字符串转换回列表。

[('zX7XjZ1Vwai5UbqNDDJ1NQ', 570512, [155])]
Run Code Online (Sandbox Code Playgroud)

我已经尝试了这两种方法eval()ast.literal_eval但是由于某种原因,当我打印转换后的字符串的类型时,它仍然是一个字符串(但删除了引号)

我也试过使用 json.loads()

似乎无论我多么努力,我都无法将这个列表字符串转换为 Python 列表!

python string eval list abstract-syntax-tree

0
推荐指数
1
解决办法
3808
查看次数

如何使用ast列出函数的参数?

我正在使用ast模块来解析Python模块中的文档字符串,以将我们的文档转换为docs格式.我正在使用以下内容将函数名称和文档字符串放入我的其余代码可以很好地使用的dicts列表中.我正在寻找能够获得函数参数的东西:

good_file = (file for file in os.listdir() if file[-3:] == '.py' and file != '__init__.py')

functions = []

for file in good_file:
     with open(file, 'r') as f:
         module = ast.parse(f.read())

     for node in module.body:
         if isinstance(node, ast.FunctionDef):
         entry = {"docs": ast.get_docstring(node), "fn_name": node.name, "params": ???}

         functions.append(entry)
Run Code Online (Sandbox Code Playgroud)

我正在寻找可以用来将函数的参数填入dict的东西.谢谢!

python abstract-syntax-tree

0
推荐指数
1
解决办法
977
查看次数

从字符串解析python嵌套列表

所以我将文件解析为python列表,我遇到了这样的嵌套列表:

{   1   4{  2a  0.0 }{  3   0.0 }{  4c  0.0 }{  5   0.0 }   }
Run Code Online (Sandbox Code Playgroud)

我想把它解释为一个列表,但是嵌套了,所以我希望它成为python列表,如下所示:

[1,4,[2a,0.0],[3,0.0],[4c,0.0],[5,0.0]]
Run Code Online (Sandbox Code Playgroud)

我设法使用以下内容执行正确的字符串:

l = """{    1   4{  2   0.0 }{  3   0.0 }{  4   0.0 }{  5   0.0 }   }"""
l = l.replace("{\t",",[").replace("\t}","]").replace("{","[").replace("}","]").replace("\t",",")[1:]
Run Code Online (Sandbox Code Playgroud)

我也可以申请' l.strip("\t")以便它是一个列表,但不适用于嵌套,否则它将被展平,这是我不想要的.

我尝试过ast.literal_eval(l),但它在字符串上失败,例如2a

python parsing list abstract-syntax-tree

0
推荐指数
1
解决办法
449
查看次数

如何模式匹配案例类的父特征(或类或对象)?

我试图在单个case子句中匹配所有二元运算符,但以下代码给出了错误:

object BinOp is not a case class, nor does it have a valid unapply/unapplySeq member
Note: def unapply(a: AST.this.Expr, b: AST.this.Expr): Option[(AST.this.Expr, AST.this.Expr)] exists in object BinOp, but it cannot be used as an extractor as it has more than one (non-implicit) parameter.
Run Code Online (Sandbox Code Playgroud)

遍历树的核心代码:

tree match {
    case ... other ... cases
    case BinOp(a, b) => traverse(a), traverse(b)
}
Run Code Online (Sandbox Code Playgroud)

AST 类如下:

sealed trait Expr

case class Num(value: java.lang.Number) extends Expr

sealed trait BinOp extends Expr {
  val …
Run Code Online (Sandbox Code Playgroud)

scala pattern-matching abstract-syntax-tree case-class

0
推荐指数
1
解决办法
80
查看次数

使用 Python AST 确定字符串是否已硬编码到打印调用中

我正在尝试编写一个函数,该函数将使用 AST 来确定某个字符串是否已被硬编码到打印函数调用中。例如,如果这是整个 Python 文件:

print("hard coded")
Run Code Online (Sandbox Code Playgroud)

我得到的树如下:

with open(filename, 'r') as f:
    tree = ast.parse(f.read())

nodes = [node for node in ast.walk(tree)]
Run Code Online (Sandbox Code Playgroud)

现在nodes包含[<_ast.Module object at 0x7fa250286150>, <_ast.Expr object at 0x7fa250286050>, <_ast.Call object at 0x7fa2502642d0>, <_ast.Name object at 0x7fa228014610>, <_ast.Str object at 0x7fa228014710>, <_ast.Load object at 0x7fa2280080d0>]

通过测试 attrs 我可以发现nodes[2]有一个.func.idand nodes[2].func.id == 'print',所以这是我的打印命令。但是我如何找到传递给这个打印命令的参数呢?硬编码字符串位于ast.Str列表索引 4 处出现的对象中,但我需要专门确定该字符串已传递给打印,而不仅仅是该字符串出现在文件中。

python abstract-syntax-tree

0
推荐指数
1
解决办法
1468
查看次数

如何获取 python 文件中所有“if”、“else”和“elif”位置的行号

示例:假设我们有一个包含以下代码片段的 .py 文件。我们如何读取并提取 if-elif-else 的位置

If fisrtconditon:#line 1
    If sub-condition:#line2
       print(line no 3)
elif secnd_condn:#line 4
     Xyz..#line5
     Xyz..#line6
elif third condition:line7
     ...line 8
else:#line 9
    Some content #line10***
Run Code Online (Sandbox Code Playgroud)

输出:

[1,4,7,9]
Run Code Online (Sandbox Code Playgroud)

python abstract-syntax-tree

0
推荐指数
1
解决办法
410
查看次数

如何使用 C++ 解析简单的类似 pango 的标记,获得类似树的节点结构?

我试图将 Pango 风格的标记解析为树状结构,叶子是文本元素,分支是带有属性的标签元素。例如:

<b>This is bold</b>, <i>italic and <span color="red">red text</span></i> !
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经得到了下面的 C++ 代码(没有类定义,我认为它们是无关紧要的),如果省略上面的部分,它可以正常工作<b></b>- 它只能解析每个级别的一个标签,但它在每个级别的多个标签上失败:

        bool parseStartTag(const std::string& s, size_t start, size_t end, std::string& tag_name, std::map<std::string, std::string>& attrs) {
            size_t tag_name_end = s.find_first_of(" \t\n", start);
            if (tag_name_end == std::string::npos or tag_name_end >= end) {
                tag_name = s.substr(start, end - start);
                return true;
            } else {
                tag_name = s.substr(start, tag_name_end - start);
            }
            start = tag_name_end;

            char quote = '\0';
            std::string attr_name = "";
            std::string attr_value = ""; …
Run Code Online (Sandbox Code Playgroud)

c++ markup parsing abstract-syntax-tree xml-parsing

0
推荐指数
1
解决办法
109
查看次数

IndentationError 在 `ast.parse` 和 `ast.walk` 的一个函数中,该函数是类中的一个方法

我想我知道IndentationError 中IndentationError描述的类似的常见原因:例如,unindent 不匹配任何外部缩进级别。这不适用于这里。

另外,我知道,textwrap.dedent但感觉这里不是正确的方法?


如果我有一个“正规”的功能,我可以做ast.parseast.walk这样的:

import ast
import inspect

def a():
    pass

code = inspect.getsource(a)
nodes = ast.walk(ast.parse(code))
for node in nodes:
    ...
Run Code Online (Sandbox Code Playgroud)

但是,如果函数是类中的方法,例如:

class B:
    def c(self):
        pass

code = inspect.getsource(B.c)
nodes = ast.walk(ast.parse(code))
Run Code Online (Sandbox Code Playgroud)

我得到:

IndentationError: unexpected indent
Run Code Online (Sandbox Code Playgroud)

我想这是有道理的,因为B.c 缩进了一级。那么我ast.parseast.walk这里怎么办呢?

python parsing indentation abstract-syntax-tree static-code-analysis

-1
推荐指数
1
解决办法
684
查看次数

Oberon语法在哪里不是LL(1)?

7.2.Oberon语法在哪里不是LL(1),也就是说,哪个是必要的多个符号的前瞻?以满足LL(1)属性的方式更改语法以下是Oberon语法:

ident = letter {letter | digit}.
integer = digit {digit}.
selector = {"." ident | "[" expression "]"}.
number = integer.
factor = ident selector | number | "(" expression ")" | "~" factor.
term = factor {("*" | "DIV" | "MOD" | "&") factor}.
SimpleExpression = ["+"|"-"] term {("+"|"-" | "OR") term}.
expression = SimpleExpression
[("=" | "#" | "<" | "<=" | ">" | ">=") SimpleExpression].
assignment = ident selector ":=" expression.
ActualParameters = "(" [expression {"," …
Run Code Online (Sandbox Code Playgroud)

algorithm parsing abstract-syntax-tree

-2
推荐指数
1
解决办法
477
查看次数

ast.literal_eval 错误。ValueError:格式错误的节点或字符串:&lt;ast.Name 对象位于 0x0000024A165CF7F0&gt;

我从游戏中获取数据。有时我可以使用literal_eval,有时则不能。有时是因为我在从字节解码到 str 时遇到问题,但这次我没有看到。在此输入图像描述

python abstract-syntax-tree

-3
推荐指数
1
解决办法
7664
查看次数

AST - 限制包含 python 代码的用户输入以防止读取文件

我正在使用 netcat 和 python 创建一个服务器,它允许用户连接并运行少于 100 行的任意 python 代码。目的是防止用户读取服务器上的文件。为了实现这个目标,我正在使用 ast。用户可以输入他们的代码:

code = ""
cntr = 0
while cntr < 100:
      line = sys.stdin.readline()
      code += line
      cntr = cntr + 1
Run Code Online (Sandbox Code Playgroud)

然后,将 code 变量传递给编译:

astobj = compile(code, "server.py", 'exec', flags=ast.PyCF_ONLY_AST)
Run Code Online (Sandbox Code Playgroud)

使用以下代码来防止用户读取敏感文件是否安全有效?

def check(comp):
  for c in ast.walk(comp):
    match type(c):
      case (ast.Call|ast.Import|ast.ImportFrom):
        return False
  return True

if check(astobj):
   exec(compile(code, "server.py", 'exec'))
Run Code Online (Sandbox Code Playgroud)

python security validation abstract-syntax-tree python-3.x

-3
推荐指数
1
解决办法
543
查看次数