Lets say I have a string that holds a method invocation for some c-ish language:
var codeLine = 'method1(var1, var2, method2(var3, method3(var4, var5)),var6);';
What is the easiest way to count the number of parameters being passed into the top level function (method1
)?
In the example above, I would be looking for the result of 4.
I also need this solution to function properly if the method is not complete (imagine it's being typed):
method1(var1, var2, method2(var3, meth
Would return 3.
I understand there the 'proper' way to do this would be to parse the language using a tool like antlr, but I'm hoping there is a quick and easy solution for this.
If your curious, this is for a vscode extension that's providing signature help support
Update:
Took a stab at it...
function findTopLevelParamCount(s){
//trim top level function away
s = s.substr(s.indexOf('(')+1,s.lastIndexOf(')')-s.indexOf('(')-1);
console.log(s);
while(s.indexOf('(') >= 0){
s = s.substr(0,s.indexOf('(')) + (s.indexOf(')')==-1?'':s.substr(s.lastIndexOf(')')+1));
console.log(s);
}
return s.split(',').length;
}
var code = 'method1(var1, var2, method2(var3, method3(var4, var5)), var6);';
console.log(findTopLevelParamCount(code));
Doesn't work if the signature isn't complete. Also breaks with parethsis groupings like method1(var1, (var1-va2))
.