Skip to content

Instantly share code, notes, and snippets.

@calebreister
Created August 10, 2014 02:28
Show Gist options
  • Save calebreister/7879f930ca0c94b987f5 to your computer and use it in GitHub Desktop.
Save calebreister/7879f930ca0c94b987f5 to your computer and use it in GitHub Desktop.
This script parses a C or C++ header and generates an implementation file based on the function prototypes found within. It is designed to take one class or namespace at a time, so the scope resolution is based off of the header file's name.
#!/usr/bin/env python3
#This program parses C/C++ header files and outputs a corresponding
#implementation file. It uses a regular expression to isolate function
#prototypes and converts them to implementations.
#This program is designed to take a single class or namespace as input.
import sys
import os
import re
def main():
try:
header = open(sys.argv[1], 'r')
except IndexError:
header = open(input('Enter the path to a header file: '), 'r')
os.chdir(os.path.dirname(header.name))
headerName = re.sub('\.\w+$', '', os.path.basename(header.name))
headerContent = header.read()
scopeResolve = input('Do you want the function names to be prefixed with a scope [y/n]? ')
if re.search('(y|Y)', scopeResolve):
className = ''
else:
className = headerName
del scopeResolve
source = open(headerName + '.cc', 'w')
source.write('#include "' + headerName + '.hh"\n')
source.write('using namespace std;\n\n')
source.write(parse(headerContent, className))
header.close()
source.close()
def parse(header, scope):
if scope != '':
scope += '::'
prototypeMatch = re.compile('[^\s]([\w=+-/*%<>:, ]+)[^\s]\(.*\)([\w,: ]*)?;')
headingMatch = re.compile('(\w+\()')
out = ''
for match in prototypeMatch.finditer(header):
#Make a new string holding the prototype
code = header[match.start() : match.end()]
#Insert scope resolution
code = headingMatch.sub(scope + r'\1', code)
#Replace the semicolon
code = re.sub(r';', ' {\n\n}\n\n', code)
out += code
return out
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment