HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Searching for unused functions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
functionsunusedforsearching

Problem

So I came up with a problem In C. Our compiler is pre c99 and wasn't identifying functions that are never called. So I ended up writing this script and decided to post it up to be critiqued and to help people who might be in the same predicament. The script works great for me and finished the job that I needed it to do. I just felt that it could be done better.

```
from sys import exit
import re
import os ,fnmatch
#"(static BOOL|BOOL|static void|void)\s+([A-Z a-z]+)(\(.*?\)\;)"
pattern = "(static BOOL|BOOL|static void|void|static BYTE|BYTE|static int|int)\s+([A-Z a-z]+)(\(.*?\)\;)"

compiled = re.compile(pattern)
commentend = re.compile("\*/")
commentbegin = re.compile("/\.") #|\}/s/\. extra pattern
count = 0
directory =" "

def menu():#menu function
global directory
print "what would you like to do"
print "1. Enter directory of .c and .h files you want searched"
print "2. Display possibly unused functions" #not used
print "Any other key exit program"

selection = raw_input("> ")
if selection == '1':#this menu starts the search process
print "you selected search"
print "what is the file name"
directory = raw_input("> ")
openfiles()
elif selection == '2':#this selection is not currently used
print "displaying matching functions"
print count
else:
exit(0)

def openfiles(): #gets a list of file names and then passes the name to search for function to open
for root,dirs,files in os.walk(directory):
for pat in ['.c','.h']:
for current_file in fnmatch.filter(files,pat):
searchforfunction(current_file)

def searchforfunction(file_name):
global directory
print file_name
with open(os.path.join(directory,file_name) ,"r" ,1) as f:
for line in f:
matchfun(line)

def matchfun(line): #This searches for a function looking for specific definition then checks how many times the function occurs
global count

Solution

Two major points:

  • The parsing is very fragile and only works when the code is laid out in a certain way. You should look for a proper parser and leverage that.



  • It is rather inefficient to scan all the files every time you encounter a function declaration. You could use dictionaries to keep track of functions so one pass over the files would suffice.

Context

StackExchange Code Review Q#31159, answer score: 2

Revisions (0)

No revisions yet.