views:

63

answers:

1

Is there a way to parse the argument values passed to a JavaScript function in python?

I want to be able to automatically document JavaScript function calls in order to make sure they have the right arguments passed to them.

For example, in:

function mymethod(fruit, vegetable, drink) {
    // dummy function
}

function drink(drink) {
    this.drink = drink
}
var myveg = 'tomato'

mymethod('grape', myveg, new drink('apple juice'))

The function call would be rewritten as:

mymethod(
    /*fruit*/ 'grape', /*vegetable*/ myveg, 
    /*drink*/ new drink('apple juice')
)

So I really want to be able to split the arguments into ["'grape'", "myveg", "new drink('apple juice')"] removing any previous auto-inserted comments in the process, preferably allowing subfunction calls as arguments.

If all else fails, I'll make it so that the arguments are as a comment before the method call (which would be much easier to parse) but I thought I'd ask first as it would make mistakes look more obvious.

Thank you very much in advance.

+1  A: 

You'll need a full JavaScript parser unless you know in advance that your JavaScript code follows some conventions you know in advance. Regular expressions are not up to the task, because they are not good for matching nested structures like parentheses.

Python has many parser generator tools: Python parsing tools. I don't know if any of them have JavaScript parsers available.

Ned Batchelder
I kind of expected it wasn't possible with regexps, but oh well. I might use `JsDoc` or use the simpler method in my question as I think using a JavaScript parser like `ANTLR` (or building using `pyparsing`) seems more complicated than it's worth for this task. Thanks though!
David Morrissey