的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文件才能使用(解析工具包中包含的文件)。你想要那個回報嗎? –