Algorithm 如何在AST中查找标识符的用法?
给定以下AST定义和示例代码,根据标识符在树中的位置,找到其所有用法的最佳算法是什么Algorithm 如何在AST中查找标识符的用法?,algorithm,search,compiler-construction,f#,abstract-syntax-tree,Algorithm,Search,Compiler Construction,F#,Abstract Syntax Tree,给定以下AST定义和示例代码,根据标识符在树中的位置,找到其所有用法的最佳算法是什么 AST Definition type Literal = Char of char // character literal | String of string // string literal | Integer of int // integer literal | Float of float //
AST Definition
type Literal
= Char of char // character literal
| String of string // string literal
| Integer of int // integer literal
| Float of float // floating point literal
| Double of double
| Unit
type SrcCol = { startColumn : int; endColumn : int }
type SrcLine = { startLine : int; endLine : int }
type SrcLoc = { srcFilename : string; srcLine : SrcLine; srcColumn : SrcCol }
type Pat =
| PVar of 'a
| PApp of Pat * Pat
| PLit of Literal
| PWithTy of Pat * Type
type Exp
= Var of 'a // variable
| Lam of Pat list * Exp // lambda abstraction
| App of Exp * Exp // application
| Let of Pat * Exp * Exp // local definition
| Lit of Literal // literal
| WithTy of Exp * Type
Sample Code:
let f x = let g x = x
g x
AST instance of Sample Code
[Let
(PApp
(PVar
("f",
{srcFilename =
"test.fs";
srcLine = {startLine = 1;
endLine = 1;};
srcColumn = {startColumn = 4;
endColumn = 5;};}),
PVar
("x",
{srcFilename =
"test.fs";
srcLine = {startLine = 1;
endLine = 1;};
srcColumn = {startColumn = 6;
endColumn = 7;};})),
Let
(PApp
(PVar
("g",
{srcFilename =
"test.fs";
srcLine = {startLine = 1;
endLine = 1;};
srcColumn = {startColumn = 14;
endColumn = 15;};}),
PVar
("x",
{srcFilename =
"test.fs";
srcLine = {startLine = 1;
endLine = 1;};
srcColumn = {startColumn = 16;
endColumn = 17;};})),
Var
("x",
{srcFilename =
"test.fs";
srcLine = {startLine = 1;
endLine = 1;};
srcColumn = {startColumn = 20;
endColumn = 21;};}),
App
(Var
("g",
{srcFilename =
"test.fs";
srcLine = {startLine = 2;
endLine = 2;};
srcColumn = {startColumn = 10;
endColumn = 11;};}),
Var
("x",
{srcFilename =
"test.fs";
srcLine = {startLine = 2;
endLine = 2;};
srcColumn = {startColumn = 12;
endColumn = 13;};}))),Lit Unit)]
在“创建了标识”的节点的子树中,DFS如何?基本上,需要使用所需属性的筛选器对树节点进行任何类型的枚举。深度优先搜索(如另一个答案中所建议的)是枚举节点的一种方法 然而,对于特定树节点中的特定标识符,人们通常想知道它代表什么“声明的实体”?否则,您会找到所有引用,但它们指向不同的实体,这通常是没有帮助的
这需要为所讨论的应用程序语言构建符号表,然后在标识符节点和符号表条目之间构建映射。一个简单的枚举器无法完成构建符号表的任务。看看我在周末入侵的实现: 似乎有效:)Visual Studio Gallery上的FSharpRefactor 0.1(预览版)发行版 干杯;)