Reputation: 11258
Does emacs have a function to count the no. of functions in .c/.h C src file?
I would like to be able to count a (large) no. of functions in a .c file and compare this to the no. of functions in the associated unit-test .c file to establish whether every function has a unit-test
ideally there is something built-in to do this as opposed to requiring some sort of reg-exp?
Upvotes: 1
Views: 94
Reputation: 4029
You can use semantic's tag generation to achieve this.
Semantic is a very powerful and underused feature of Emacs. Semantic can parse your .c and .h files and generate tags that you can look through to find your answer. I have written up examples for you:
First, ensure you have the semantic
library loaded.
(defun c--count-things-in-buffer (thing buffer)
"return the count of THINGs in BUFFER.
THING may be: 'function, 'variable, or 'type"
(with-current-buffer buffer
;; get the buffers tags, they will be generated if not already
;; then remove the ones that are not 'function tags
;; return the count of what is left
(length (remove-if-not (lambda (tag) (equal thing (second tag)))
(semantic-fetch-tags)))))
(defun c-count-functions-in-buffer (buffer)
"Count and message the number of function declarations in BUFFER"
(interactive "b")
(message "%s has %d functions"
buffer
(c--count-things-in-buffer 'function buffer)))
(defun c-count-variables-in-buffer (buffer)
"Count and message the number of variable declarations in BUFFER"
(interactive "b")
(message "%s has %d variables"
buffer
(c--count-things-in-buffer 'variable buffer)))
(defun c-count-types-in-buffer (buffer)
"Count and message the number of type declarations in BUFFER"
(interactive "b")
(message "%s has %d types"
buffer
(c--count-things-in-buffer 'type buffer)))
Try evaluating this in your scratch buffer then switch to your .c file and do M-x
c-count-functions-in-buffer
The information brought back from semantic-fetch-tags
has everything you need to solve your unit test problems.
Let's say you have a function called Foobar and your unit test are written like: Test_Foobar. You could get the tags for the .c file and the tags for the test file and do a check for every function in the c file there exists a tag in the test file that matches Test_. This would likely be better than simply counting the total number of functions.
Run this code in your scratch buffer with C-j:
(with-current-buffer "what-ever-your-c-buffer-is.c" (semantic-fetch-tags))
Here you'll be able to see all the great info that comes back that you can use for this.
Upvotes: 2