2012-09-18 20 views
1

我想用ParseKit分析一些javascript代码。我用JavaScript语法获得了框架设置,但我无法真正理解用于分析代码的路线。事情是,我最后想要例如获取所有全局声明的var的数组(在函数外定义的var)。但我真的不明白我能得到那样的结果!在堆栈溢出中,我一直在阅读很多问题,并且可能会看到我可能应该使用汇编器的堆栈和目标,但事实是函数回调在到达函数块结束时被调用,所以所有的var定义之前都会被回调。我如何知道当我在一个函数内部获得一个回调函数时,它的内部?ParseKit javascript分析

var i = 0; 
function test(){ 
    var u = 0; 
} 

这里我想找到我例如,不是你。但回调是

#1 Found var i 
#2 Found var u 
#3 Found func test 

乔纳斯

回答

2

ParseKit在这里开发。

首先,结账this answer to another, somewhat-related ParseKit question。那里有很多相关的信息(在那里有其他答案)。

然后,对于您的特定示例,关键是每当function开始时设置一个标志,并在标志结束时清除该标志。所以无论何时匹配var decl,只需检查标志。如果标志已设置,则忽略var decl。如果标志没有设置,则存储它。

这是非常重要的,我提到的国旗存储在PKAssembly对象这是汇编回调函数的参数。您不能将该标志存储为ivar或全局变量。这是行不通的(详情请参阅之前的链接答案)。

下面是设置标志和匹配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. 
    } 
} 
+1

非常感谢!这就说得通了。感谢您为解析套件付出了如此多的努力,并帮助像我这样的人在这里堆栈!顺便说一下,我必须稍微编辑一下JavaScript.grammar文件才能使用(解析工具包中包含的文件)。你想要那个回报吗? –