aboutsummaryrefslogtreecommitdiff
path: root/tools/Internals/headers/parse.py
blob: 227ce99367eeecfc009116d3180ebeb0689d0d84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#!/usr/bin/env python3
""" Parse a file on the C preprocessor view, with libcarrot extensions.

	The goal of this file is also to 'simplify' the preprocessor tree so
	that it is valid with K&R C: no '&&' or '||' in #if directives, and
	no `!=` too, only `==`.

	Returns a directive list. Each directive is a tuple where the first
	argument is the directive type, among:

	- None: raw text, not a preprocessor instruction.
	  The tuple looks like (None, ["first line", "second line", "wow yeah"]).

	- "include": include a file (in path, local, or using a variable).
	  The tuple looks like ("include", "local", "the/file.h"), where
	  "local" can be replaced by "path" or "expr".

	- "include_bits": include all bits file corresponding to a name.
	  The tuple looks like ("include_bits", dir/bitname.h").

	- "define": define a preprocessor constant or macro.
	  The tuple looks like ("define", "name", ("arg1", "arg2"), "value") with
	  arguments, or ("define", "name", None, "value") otherwise.

	- "undef": if exists, un-define a macro (with or without arguments).
	  The tuple looks like ("undef", "name").

	- "if": the condition. The first element is "if", the second element is
	  the condition tuple, the others except the last one are the elif
	  condition tuples, and the last element is the instructions list.
	  Each condition tuple is made of the expression to evaluate (non zero
	  means the condition is true) and the instructions.

	Check out "The C Programming Language" section 4.11 for more information.
"""

# ---
# Objects
# ---

class CppRaw:
	def __init__(self, content):
		self.content = content

	def addcontent(self, content):
		self.content.extend(content)

class CppDefine:
	def __init__(self, name, expr, args=None):
		self.name = name
		self.args = args
		self.expr = expr

class CppUndef:
	def __init__(self, name):
		self.name = name

class CppInclude:
	def __init__(self, name, typ):
		self.name = name
		self.typ  = typ

class CppIncludeBits:
	def __init__(self, typ, name):
		self.name = name
		self.typ  = typ

class CppIf:
	def __init__(self, cond, ins):
		self.conds = [(cond, ins)]
		self.eins  = []

	def addcond(self, cond, ins):
		self.conds.append((cond, ins))

	def setelse(self, ins):
		self.eins = []

class CppError:
	def __init__(self, message):
		self.message = message

# ---
# Parse content.
# ---

def __readline(src):
	""" Read one line. """

	lines = []
	while True:
		tmp = src.readline()
		if tmp == '':
			break

		tmp = tmp.splitlines()[0]
		hasnext = tmp and tmp[-1] == '\\'
		lines += [tmp[:-1].rstrip() if hasnext else tmp.rstrip()]
		if not hasnext:
			break

	return lines

def __get_source_content(path, syntax='c'):
	""" Get a source file content after the top comment. """

	if syntax == 'c':
		is_str = lambda x: x[:3] == '/* ' and \
			all(c == '*' for c in x[3:])
		is_end = lambda x: x[:3] == ' * ' and \
			all(c == '*' for c in x[3:-3]) and x[-3:] == ' */'
	else:
		is_str = lambda x: x[0] == '#' and \
			all(c == '*' for c in x[1:])
		is_end = isstr

	with open(path) as src:
		line = __readline(src)

		while True:
			if not line or (len(line) == 1 and not is_str(line[0])):
				break

			while True:
				line = __readline(src)
				if not line or (len(line) == 1 and is_end(line[0])):
					break

			line = __readline(src)

		lines = [line]
		while True:
			line = __readline(src)
			if not line: break
			lines.append(line)

		return lines

# ---
# Sub-parsing functions.
# ---

def __parse_define(raw):
	""" Get the define details out of the string, e.g. "CONSTANT some constant"
		or "MY_MACRO(and_some, fancy_parameters) and_some - fancy_parameters".
		Returns either (macro, None, value) or (macro, args, value). """

	raw = '\n'.join(raw)

	first = raw.split()[0]
	if first.find('(') >= 0:
		# Is a macro with arguments!
		name = first.split('(')[0]
		rest = raw[len(name) + 1:]
		rpar = rest.find(')')
		if rpar < 0:
			raise Exception("Missing ')' in macro parameter list.")

		# Get the argument list.
		alst = rest[:rpar]
		if alst.find('(') >= 0:
			raise Exception("'(' cannot appear in macro list.")
		args = ()
		for arg in map(str.strip, alst.split(',')):
			for c in (c for c in arg if c.isspace()):
				raise Exception("Macro params. should be spl. using commas.")
			args = args + (arg,)

		# Get the expression to evaluate, return.
		rest = rest[rpar + 1:].lstrip()
		return (name, rest.split('\n'), args)

	rest = raw[len(first) + 1:].lstrip()
	return (first, rest.split('\n'))

def __parse_name(raw):
	""" Get a macro name out of a raw string. """

	ret = '\n'.join(raw).strip()
	# TODO: check that the name is good (ANSI, stuff).
	return ret

def __parse_header_ref(raw):
	""" Get the header reference, such as "header.h" (for local references),
		<header.h> (for path references) or VARIABLE_NAME (for variables). """

	raw = '\n'.join(raw).strip()
	if raw[0] == '<' and raw[-1] == '>':
		return ('path', raw[1:-1].strip())
	if raw[0] == '"' and raw[-1] == '"':
		return ('local', raw[1:-1].strip())
	return ('var', __parse_name(raw))

def __get_inst(raw):
	""" Get the instruction name and its parameters from a line group. """

	full = '\n'.join(raw).lstrip()

	# Check if is a preprocessor directive.
	if not full or full[0] != '#':
		return False

	# Get the preprocessor directive.
	tmp = full[1:].split()
	if not tmp: return '===SKIP==='
	inst = tmp[0]

	# Get the rest.
	rest = full[1:].lstrip()[len(inst):].lstrip()
	return (inst, rest.split('\n'))

# ---
# Main parsing function.
# ---

def __parse_header_rec(lines):
	""" The recursive function. """

	ins = []
	while lines:
		# Get the instruction and arguments.
		line = lines.pop()
		result = __get_inst(line)
		if not result:
			if not ins or type(ins[-1]) != CppRaw:
				ins.append(CppRaw(line))
			else:
				ins[-1].addcontent(line)
			continue
		if result == '===SKIP===':
			continue
		inst, rest = result

		# Check using it:
		# include, define, undef, if, elif, else, ifdef, ifndef
		#
		# Extensions: elifdef, elifndef, error
		if   inst == 'include':
			ins.append(CppInclude(*__parse_header_ref(rest)))
		elif inst == 'error':
			ins.append(CppError(rest)) # FIXME: string?
		elif inst == 'include_bits':
			ins.append(CppIncludeBits(*__parse_header_ref(rest)))
		elif inst == 'define':
			ins.append(CppDefine(*__parse_define(rest)))
		elif inst == 'undef':
			ins.append(CppUndef(__parse_name(rest)))
		elif inst == 'if' or inst == 'ifdef' or inst == 'ifndef':
			if   inst == 'if':
				ini_check = rest
			elif inst == 'ifdef':
				ini_check =  'defined(%s)' % __parse_name(rest)
			elif inst == 'ifndef':
				ini_check = '!defined(%s)' % __parse_name(rest)
			obj = CppIf(ini_check, __parse_header_rec(lines))

			while True:
				if not lines:
					raise Exception("#endif expected!")
				inst, rest = __get_inst(lines.pop())
				if   inst == 'else' or inst == 'endif':
					break

				sub = __parse_header_rec(lines)
				if   inst == 'elif':
					check = rest
				elif inst == 'elifdef':
					check =  'defined(%s)' % __parse_name(rest)
				elif inst == 'elifndef':
					check = '!defined(%s)' % __parse_name(rest)
				obj.addcond(check, __parse_header_rec(lines))

			if inst == 'else':
				obj.setelse(__parse_header_rec(lines))
				if not lines:
					raise Exception("#endif expected!")
				inst, rest = __get_inst(lines.pop())
				if inst != 'endif':
					raise Exception("#endif expected!")
			ins.append(obj)
		elif inst == 'elif' or inst == 'elifdef' or inst == 'elifndef' \
		  or inst == 'else' or inst == 'endif':
			lines.append(line) # reinsert the line so that it is re-read.
			break
		else:
			# Invalid instruction!
			raise Exception("Unknown preprocessor directive #%s"%inst)

	return ins

def parse_header(path):
	""" Parse the header. """

	lines = __get_source_content(path)
	lines.reverse()
	return __parse_header_rec(lines)

# End of file.