view CbC-scripts/make_headers.py2 @ 26:b388631e4738

add make_headers script.
author kent <>
date Thu, 29 Oct 2009 18:19:02 +0900
children f9b1a53df341
line wrap: on
line source

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import re

reserved_words = [ "if", "for", "switch", "return", "while", "else", ]

#PATTERN = r"([a-zA-Z_]\w*)\s+([a-zA-Z_]\w*)\s*\(([^;]*)\)\s*\{"
#PATTERN = r"((?:[a-zA-Z_]\w*)\s+)+?([a-zA-Z_]\w*)\s*\(([^;]*)\)\s*\{"
PATTERN = r"([a-zA-Z_][\w\s]*\**)\s([a-zA-Z_]\w*)\s*\(([^/;]*)\)\s*\{"
# TODO: 関数パラメータ内にコメントがあると正しく動かない!
PROG = re.compile(PATTERN, re.S)

def truncate_comments(data):

def check_reserved_word(decl):
	""" return true if decl's type and name is not reserved word. """

	if decl["name"] in reserved_words or decl["type"] in reserved_words:
		return False
	return True

def read_decls(file):
	declarators = []

	# open the file and read all lines into a string.
		fo = open(file, 'r')
		lines = fo.readlines()
		data = "".join(lines)
	except IOError:
		print "cannot read file %s" % file

	# find all matched strings.
	# moiter is iterator of MatchObject.
	moiter = PROG.finditer(data)
	for mo in moiter:
		tmp = { "type":,
				"offset": mo.start() }
		if check_reserved_word(tmp):

	return declarators

def debug_print(decl):
	for (key,value) in decl.items():
		if isinstance(value, str):
			decl[key] = value.replace("\n"," ").replace("\t"," ")

	print "Type:\t%s" % decl["type"]
	print "Name:\t%s" % decl["name"]
	print "Params:\t%s" % decl["parms"]
	print "offset:\t%d" % decl["offset"]
	print ""
	#s = "%s %s ( %s );" % (decl["type"], decl["name"], decl["parms"])
	#print s, "/* offset: %d */" % decl["offset"]

def format_print(decl, file):
	for (key,value) in decl.items():
		if isinstance(value, str):
			decl[key] = value.replace("\n"," ").replace("\t"," ")

	print "/* defined in file %s at offset %d  */" % (file,decl["offset"])
	print "%s %s (%s);" % (decl["type"],decl["name"],decl["parms"])
	print ""

def main():
	for file in sys.argv[1:]:
		decls = read_decls(file)

		if decls==None or len(decls)==0:
			print "%s have no function definition!" % file
		for decl in decls:
			format_print(decl, file)
		#print decls[0]