Domanda

Are there any libraries out there that I can pass my .c files through and will count the visible number of, of example, "if" statements?

We don't have to worry about "if" statement in other files called by the current file, just count of the current file.

I can do a simple grep or regex but wanted to check if there is something better (but still simple)

È stato utile?

Soluzione

If you want to be sure it's done right, I'd probably make use of clang and walk the ast. A URL to get you started:

http://clang.llvm.org/docs/IntroductionToTheClangAST.html

Altri suggerimenti

First off, there is no way to use regular expressions or grep to give you the correct answer you are looking for. There are lots of ways that you would find those strings, but they could be buried in any amount of escape characters, quotations, comments, etc.

As some commenters have stated, you will need to use a parser/lexer that understands the C language. You want something simple, you said, so you won't be writing this yourself :)

This seems like it might be usable for you:

http://wiki.tcl.tk/3891

From the page:

lexes a string containing C source into a list of tokens

That will probably get you what you want, but even then it's not going to be trivial.

What everyone has said so far is correct; it seems a lot easier to just grep the shit out of your file. The performance hit of this is neglagible compared to the alternative which is to go get the gcc source code (or whichever compiler you're using), and then go through the parsing code and hook in what you want to do while it parses the syntax tree. This seems like a pain in the ass, especially when all you're worried about is the conditional statements. If you actually care about the branches, you could actually just take a look at the object code and count the number of if statements in the assembly, which would correctly tell you the number of branches (rather than just relying on how many times you typed a conditional, which will not translate exactly to the branching of the program).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top