Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Basically trying to create a dict of all declared variables and functions along with their types of a .c source file. Does anyone think I missed anything?

#!usr/python
import string
import re
from types import *
from pprint import pprint

varDict = {}

def find_substring(needle, haystack):
    index = haystack.find(needle)
    if index == -1:
        return False
    if index != 0 and haystack[index-1] not in string.whitespace:
        return False
    L = index + len(needle)
    if L < len(haystack) and haystack[L] not in string.whitespace:
        return False
    return True

f = open('example.c')
varTypeList = []

for varType in open('typesfile.txt'):
        varTypeList.append(varType[:-1])

for line in f:
        for varType in varTypeList:
                if find_substring(varType,line):
                        var = re.search('\s*[\*_a-zA-Z]+[\*_a-zA-Z0-9]?', line.split(varType)[1])
                        if type(var) is not NoneType:
                                varDict[var.group(0)] = varType
pprint(varDict)
share|improve this question

3 Answers

up vote 3 down vote accepted

I think this code is fundamentally broken. What about comments and the preprocessor? And just by eyeballing the code I doubt very much that it parses declarations remotely correctly.

This is the wrong approach. string.find will only take you so far. You need to parse the code to get reliable information. The easiest way to do this is to use a library, such as libclang.

share|improve this answer

This library looks like a great option for solving your problem in Python: http://code.google.com/p/python-ctags/

share|improve this answer

The code in find_substring() can be accomplished in one line in regular expressions.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.