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?

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'):

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

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.


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


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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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