Question

I would like to know if there are already good algorithms to detect function declaration, function content, its opening brace and closing one. For development, debug and testing for bugs, it could be nice in some cases where you need to add a lot of code in most functions.

Example source code:

Test.onLoad=function(event){
    Test.initialize();
};

Result:

  • Function name: Test.onLoad
  • Content: Test.initialize();
  • Opening brace found at line: 1.
  • Closing brace found at line 3.

We could for example, with the information above, easily add a line at the beginning of all functions and at the end of them, to Log some parameters:

Test.onLoad=function(event){
    Log("LogInit","function:Test.onLoad","openbraceline:1","content: Test.initialize();");
    Test.initialize();
    Log("LogEnd ","function:Test.onLoad","endbraceline :5","content: Test.initialize();");
};

I know that this functionality could be also made with a simple global log and with a call stack, but there are still a lot of examples where this could be very usefull.


Making a simple algorithm to detect and match braces and get the function information could be easy but there are a lot of exceptions where it could be really complicated, and thats why Im asking if there are already good known ways of detecting it.
I dont mind if the examples algorithms or tips are in any language, just wanted to see the best ways of doing it.

Notepad++ is a good example because it has a plugin which detects a lot of different source code languages and parses the code with colors for each part and matches braces.

Was it helpful?

Solution

Using a real parser is the only solution that will work in all cases.

This seems to be about Javascript, so my suggestion is to use Rhino, which is very easy to use, but the tool would be a java tool in the end, of course.

If the solution needs to be in Javascript, too, then you can take a look at this question about parsers in javascript

OTHER TIPS

If you want it perfect you will need a real parser for your language. If not you can design a simplified CFG and write a parser for that (Many syntax highlighters I've seen work like that.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top