⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 scantools.py

📁 reduced python source for embedded apps
💻 PY
📖 第 1 页 / 共 2 页
字号:
"""\Tools for scanning header files in search of function prototypes.Often, the function prototypes in header files contain enough informationto automatically generate (or reverse-engineer) interface specificationsfrom them.  The conventions used are very vendor specific, but once you'vefigured out what they are they are often a great help, and it sure beatsmanually entering the interface specifications.  (These are needed to generatethe glue used to access the functions from Python.)In order to make this class useful, almost every component can be overridden.The defaults are (currently) tuned to scanning Apple Macintosh header files,although most Mac specific details are contained in header-specific subclasses."""import regeximport regsubimport stringimport sysimport osimport fnmatchfrom types import *try:	import MacOSexcept ImportError:	MacOS = Nonefrom bgenlocations import CREATOR, INCLUDEDIRError = "scantools.Error"class Scanner:	def __init__(self, input = None, output = None, defsoutput = None):		self.initsilent()		self.initblacklists()		self.initrepairinstructions()		self.initpaths()		self.initfiles()		self.initpatterns()		self.compilepatterns()		self.initosspecifics()		self.initusedtypes()		if output:			self.setoutput(output, defsoutput)		if input:			self.setinput(input)		def initusedtypes(self):		self.usedtypes = {}		def typeused(self, type, mode):		if not self.usedtypes.has_key(type):			self.usedtypes[type] = {}		self.usedtypes[type][mode] = None		def reportusedtypes(self):		types = self.usedtypes.keys()		types.sort()		for type in types:			modes = self.usedtypes[type].keys()			modes.sort()			print type, string.join(modes)				def gentypetest(self, file):		fp = open(file, "w")		fp.write("types=[\n")		types = self.usedtypes.keys()		types.sort()		for type in types:			fp.write("\t'%s',\n"%type)		fp.write("]\n")		fp.write("""missing=0for t in types:	try:		tt = eval(t)	except NameError:		print "** Missing type:", t		missing = 1if missing: raise "Missing Types"""")		fp.close()	def initsilent(self):		self.silent = 0	def error(self, format, *args):		if self.silent >= 0:			print format%args	def report(self, format, *args):		if not self.silent:			print format%args	def writeinitialdefs(self):		pass			def initblacklists(self):		self.blacklistnames = self.makeblacklistnames()		self.blacklisttypes = ["unknown", "-"] + self.makeblacklisttypes()	def makeblacklistnames(self):		return []	def makeblacklisttypes(self):		return []	def initrepairinstructions(self):		self.repairinstructions = self.makerepairinstructions()	def makerepairinstructions(self):		"""Parse the repair file into repair instructions.				The file format is simple:		1) use \ to split a long logical line in multiple physical lines		2) everything after the first # on a line is ignored (as comment)		3) empty lines are ignored		4) remaining lines must have exactly 3 colon-separated fields:		   functionpattern : argumentspattern : argumentsreplacement		5) all patterns use shell style pattern matching		6) an empty functionpattern means the same as *		7) the other two fields are each comma-separated lists of triples		8) a triple is a space-separated list of 1-3 words		9) a triple with less than 3 words is padded at the end with "*" words		10) when used as a pattern, a triple matches the type, name, and mode		    of an argument, respectively		11) when used as a replacement, the words of a triple specify		    replacements for the corresponding words of the argument,		    with "*" as a word by itself meaning leave the original word		    (no other uses of "*" is allowed)		12) the replacement need not have the same number of triples		    as the pattern		"""		f = self.openrepairfile()		if not f: return []		print "Reading repair file", `f.name`, "..."		list = []		lineno = 0		while 1:			line = f.readline()			if not line: break			lineno = lineno + 1			startlineno = lineno			while line[-2:] == '\\\n':				line = line[:-2] + ' ' + f.readline()				lineno = lineno + 1			i = string.find(line, '#')			if i >= 0: line = line[:i]			words = map(string.strip, string.splitfields(line, ':'))			if words == ['']: continue			if len(words) <> 3:				print "Line", startlineno,				print ": bad line (not 3 colon-separated fields)"				print `line`				continue			[fpat, pat, rep] = words			if not fpat: fpat = "*"			if not pat:				print "Line", startlineno,				print "Empty pattern"				print `line`				continue			patparts = map(string.strip, string.splitfields(pat, ','))			repparts = map(string.strip, string.splitfields(rep, ','))			patterns = []			for p in patparts:				if not p:					print "Line", startlineno,					print "Empty pattern part"					print `line`					continue				pattern = string.split(p)				if len(pattern) > 3:					print "Line", startlineno,					print "Pattern part has > 3 words"					print `line`					pattern = pattern[:3]				else:					while len(pattern) < 3:						pattern.append("*")				patterns.append(pattern)			replacements = []			for p in repparts:				if not p:					print "Line", startlineno,					print "Empty replacement part"					print `line`					continue				replacement = string.split(p)				if len(replacement) > 3:					print "Line", startlineno,					print "Pattern part has > 3 words"					print `line`					replacement = replacement[:3]				else:					while len(replacement) < 3:						replacement.append("*")				replacements.append(replacement)			list.append((fpat, patterns, replacements))		return list		def openrepairfile(self, filename = "REPAIR"):		try:			return open(filename, "r")		except IOError, msg:			print `filename`, ":", msg			print "Cannot open repair file -- assume no repair needed"			return None	def initfiles(self):		self.specmine = 0		self.defsmine = 0		self.scanmine = 0		self.specfile = sys.stdout		self.defsfile = None		self.scanfile = sys.stdin		self.lineno = 0		self.line = ""	def initpaths(self):		self.includepath = [':', INCLUDEDIR]	def initpatterns(self):#		self.head_pat = "^extern pascal[ \t]+" # XXX Mac specific!		self.head_pat = "^EXTERN_API[^_]"		self.tail_pat = "[;={}]"#		self.type_pat = "pascal[ \t\n]+\(<type>[a-zA-Z0-9_ \t]*[a-zA-Z0-9_]\)[ \t\n]+"		self.type_pat = "EXTERN_API" + \						"[ \t\n]*([ \t\n]*" + \						"\(<type>[a-zA-Z0-9_* \t]*[a-zA-Z0-9_*]\)" + \						"[ \t\n]*)[ \t\n]*"		self.name_pat = "\(<name>[a-zA-Z0-9_]+\)[ \t\n]*"		self.args_pat = "(\(<args>\([^(;=)]+\|([^(;=)]*)\)*\))"		self.whole_pat = self.type_pat + self.name_pat + self.args_pat#		self.sym_pat = "^[ \t]*\(<name>[a-zA-Z0-9_]+\)[ \t]*=" + \#		               "[ \t]*\(<defn>[-0-9'\"(][^\t\n,;}]*\),?"		self.sym_pat = "^[ \t]*\(<name>[a-zA-Z0-9_]+\)[ \t]*=" + \		               "[ \t]*\(<defn>[-0-9_a-zA-Z'\"(][^\t\n,;}]*\),?"		self.asplit_pat = "^\(<type>.*[^a-zA-Z0-9_]\)\(<name>[a-zA-Z0-9_]+\)$"		self.comment1_pat = "\(<rest>.*\)//.*"		# note that the next pattern only removes comments that are wholly within one line		self.comment2_pat = "\(<rest>.*\)/\*.*\*/"	def compilepatterns(self):		for name in dir(self):			if name[-4:] == "_pat":				pat = getattr(self, name)				prog = regex.symcomp(pat)				setattr(self, name[:-4], prog)	def initosspecifics(self):		if MacOS:			self.filetype = 'TEXT'			self.filecreator = CREATOR		else:			self.filetype = self.filecreator = None	def setfiletype(self, filename):		if MacOS and (self.filecreator or self.filetype):			creator, type = MacOS.GetCreatorAndType(filename)			if self.filecreator: creator = self.filecreator			if self.filetype: type = self.filetype			MacOS.SetCreatorAndType(filename, creator, type)	def close(self):		self.closefiles()	def closefiles(self):		self.closespec()		self.closedefs()		self.closescan()	def closespec(self):		tmp = self.specmine and self.specfile		self.specfile = None		if tmp: tmp.close()	def closedefs(self):		tmp = self.defsmine and self.defsfile		self.defsfile = None		if tmp: tmp.close()	def closescan(self):

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -