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