我想用ParseKit来分析一些javascript代码。我使用javascript语法设置了框架,但我真的不知道该采用哪种方法来分析代码。问题是,我想在最后得到一个包含所有全局声明的var的数组(所以var是在函数外部定义的)。但我真的看不出我如何才能得到这样的结果!我在这里读了很多关于堆栈溢出的问题,可以看到我可能应该以某种方式使用汇编程序的堆栈和目标,但问题是函数回调是在它到达函数块结束时调用的,所以所有的var定义都是在之前被回调的。当我在一个函数中的一个变量上得到一个回调时,我怎么知道它在里面呢?
var i = 0;
function test(){
var u = 0;
}例如,我想在这里找到i,而不是u。
#1 Found var i
#2 Found var u
#3 Found func test乔纳斯
发布于 2012-09-19 01:02:40
这里是ParseKit的开发者。
首先,检查this answer to another, somewhat-related ParseKit question。那里有很多相关的信息(在链接的其他答案中也有)。
然后,对于您的特定示例,关键是在function开始时设置一个标志,并在结束时清除该标志。因此,每当var decl匹配时,只需检查标志即可。如果设置了该标志,则忽略var decl。如果该标志未设置,则将其存储。
我提到的标志必须存储在PKAssembly对象上,这是汇编器回调函数的参数,这一点非常重要。您不能将该标志存储为ivar或global var。这是行不通的(有关原因,请参阅之前的链接答案)。
下面是一些用于设置标志和匹配var decls的回调示例。它们应该能让你对我所说的有一个概念:
// matched when function begins
- (void)parser:(PKParser *)p didMatchFunctionKeyword:(PKAssembly *)a {
[a push:[NSNull null]]; // set a flag
}
// matched when a function ends
- (void)parser:(PKParser *)p didMatchFunctionCloseCurly:(PKAssembly *)a {
NSArray *discarded = [a objectsAbove:[NSNull null]];
id obj = [a pop]; // clear the flag
NSAssert(obj == [NSNull null], @"null should be on the top of the stack");
}
// matched when a var is declared
- (void)parser:(PKParser *)p didMatchVarDecl:(PKAssembly *)a {
id obj = [a pop];
if (obj == [NSNull null]) { // check for flag
[a push:obj]; // we're in a function. put the flag back and bail.
} else {
PKToken *fence = [PKToken tokenWithTokenType:PKTokenTypeWord stringValue:@"var" floatValue:0.0];
NSArray *toks = [a objectsAbove:fence]; // get all the tokens for the var decl
// now do whatever you want with the var decl tokens here.
}
}https://stackoverflow.com/questions/12478175
复制相似问题