| 1 |
|
| 2 |
|
| 3 |
'''Preprocess a C source file. |
| 4 |
|
| 5 |
Limitations: |
| 6 |
|
| 7 |
* Whitespace is not preserved. |
| 8 |
* # and ## operators not handled. |
| 9 |
|
| 10 |
Reference is C99: |
| 11 |
* http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1124.pdf |
| 12 |
* Also understands Objective-C #import directive |
| 13 |
* Also understands GNU #include_next |
| 14 |
|
| 15 |
''' |
| 16 |
import operator |
| 17 |
import os.path |
| 18 |
import cPickle |
| 19 |
import re |
| 20 |
import sys |
| 21 |
|
| 22 |
import lex |
| 23 |
from lex import TOKEN |
| 24 |
import yacc |
| 25 |
|
| 26 |
tokens = ( |
| 27 |
'HEADER_NAME', 'IDENTIFIER', 'PP_NUMBER', 'CHARACTER_CONSTANT', |
| 28 |
'STRING_LITERAL', 'OTHER', |
| 29 |
|
| 30 |
'PTR_OP', 'INC_OP', 'DEC_OP', 'LEFT_OP', 'RIGHT_OP', 'LE_OP', 'GE_OP', |
| 31 |
'EQ_OP', 'NE_OP', 'AND_OP', 'OR_OP', 'MUL_ASSIGN', 'DIV_ASSIGN', |
| 32 |
'MOD_ASSIGN', 'ADD_ASSIGN', 'SUB_ASSIGN', 'LEFT_ASSIGN', 'RIGHT_ASSIGN', |
| 33 |
'AND_ASSIGN', 'XOR_ASSIGN', 'OR_ASSIGN', 'HASH_HASH', 'PERIOD', |
| 34 |
'ELLIPSIS', |
| 35 |
|
| 36 |
'IF', 'IFDEF', 'IFNDEF', 'ELIF', 'ELSE', 'ENDIF', 'INCLUDE', |
| 37 |
'INCLUDE_NEXT', 'DEFINE', 'UNDEF', 'LINE', 'ERROR', 'PRAGMA', 'DEFINED', |
| 38 |
'IMPORT', |
| 39 |
|
| 40 |
'NEWLINE', 'LPAREN' |
| 41 |
) |
| 42 |
|
| 43 |
subs = { |
| 44 |
'D': '[0-9]', |
| 45 |
'L': '[a-zA-Z_]', |
| 46 |
'H': '[a-fA-F0-9]', |
| 47 |
'E': '[Ee][+-]?{D}+', |
| 48 |
'FS': '[FflL]', |
| 49 |
'IS': '[uUlL]*', |
| 50 |
} |
| 51 |
|
| 52 |
sub_pattern = re.compile('{([^}]*)}') |
| 53 |
def sub_repl_match(m): |
| 54 |
return subs[m.groups()[0]] |
| 55 |
def sub(s): |
| 56 |
return sub_pattern.sub(sub_repl_match, s) |
| 57 |
CHARACTER_CONSTANT = sub(r"L?'(\\.|[^\\'])+'") |
| 58 |
STRING_LITERAL = sub(r'L?"(\\.|[^\\"])*"') |
| 59 |
IDENTIFIER = sub('{L}({L}|{D})*') |
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
class StringLiteral(str): |
| 69 |
def __new__(cls, value): |
| 70 |
assert value[0] == '"' and value[-1] == '"' |
| 71 |
|
| 72 |
value = value[1:-1].decode('string_escape') |
| 73 |
return str.__new__(cls, value) |
| 74 |
|
| 75 |
class SystemHeaderName(str): |
| 76 |
def __new__(cls, value): |
| 77 |
assert value[0] == '<' and value[-1] == '>' |
| 78 |
return str.__new__(cls, value[1:-1]) |
| 79 |
|
| 80 |
def __repr__(self): |
| 81 |
return '<%s>' % (str(self)) |
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
punctuators = { |
| 89 |
|
| 90 |
r'>>=': (r'>>=', 'RIGHT_ASSIGN'), |
| 91 |
r'<<=': (r'<<=', 'LEFT_ASSIGN'), |
| 92 |
r'+=': (r'\+=', 'ADD_ASSIGN'), |
| 93 |
r'-=': (r'-=', 'SUB_ASSIGN'), |
| 94 |
r'*=': (r'\*=', 'MUL_ASSIGN'), |
| 95 |
r'/=': (r'/=', 'DIV_ASSIGN'), |
| 96 |
r'%=': (r'%=', 'MOD_ASSIGN'), |
| 97 |
r'&=': (r'&=', 'AND_ASSIGN'), |
| 98 |
r'^=': (r'\^=', 'XOR_ASSIGN'), |
| 99 |
r'|=': (r'\|=', 'OR_ASSIGN'), |
| 100 |
r'>>': (r'>>', 'RIGHT_OP'), |
| 101 |
r'<<': (r'<<', 'LEFT_OP'), |
| 102 |
r'++': (r'\+\+', 'INC_OP'), |
| 103 |
r'--': (r'--', 'DEC_OP'), |
| 104 |
r'->': (r'->', 'PTR_OP'), |
| 105 |
r'&&': (r'&&', 'AND_OP'), |
| 106 |
r'||': (r'\|\|', 'OR_OP'), |
| 107 |
r'<=': (r'<=', 'LE_OP'), |
| 108 |
r'>=': (r'>=', 'GE_OP'), |
| 109 |
r'==': (r'==', 'EQ_OP'), |
| 110 |
r'!=': (r'!=', 'NE_OP'), |
| 111 |
r'<:': (r'<:', '['), |
| 112 |
r':>': (r':>', ']'), |
| 113 |
r'<%': (r'<%', '{'), |
| 114 |
r'%>': (r'%>', '}'), |
| 115 |
r'%:%:': (r'%:%:', 'HASH_HASH'), |
| 116 |
r';': (r';', ';'), |
| 117 |
r'{': (r'{', '{'), |
| 118 |
r'}': (r'}', '}'), |
| 119 |
r',': (r',', ','), |
| 120 |
r':': (r':', ':'), |
| 121 |
r'=': (r'=', '='), |
| 122 |
r')': (r'\)', ')'), |
| 123 |
r'[': (r'\[', '['), |
| 124 |
r']': (r']', ']'), |
| 125 |
r'.': (r'\.', 'PERIOD'), |
| 126 |
r'&': (r'&', '&'), |
| 127 |
r'!': (r'!', '!'), |
| 128 |
r'~': (r'~', '~'), |
| 129 |
r'-': (r'-', '-'), |
| 130 |
r'+': (r'\+', '+'), |
| 131 |
r'*': (r'\*', '*'), |
| 132 |
r'/': (r'/', '/'), |
| 133 |
r'%': (r'%', '%'), |
| 134 |
r'<': (r'<', '<'), |
| 135 |
r'>': (r'>', '>'), |
| 136 |
r'^': (r'\^', '^'), |
| 137 |
r'|': (r'\|', '|'), |
| 138 |
r'?': (r'\?', '?'), |
| 139 |
r'#': (r'\#', '#'), |
| 140 |
} |
| 141 |
|
| 142 |
def punctuator_regex(punctuators): |
| 143 |
punctuator_regexes = [v[0] for v in punctuators.values()] |
| 144 |
punctuator_regexes.sort(key=len, reverse=True) |
| 145 |
return '(%s)' % '|'.join(punctuator_regexes) |
| 146 |
|
| 147 |
def t_clinecomment(t): |
| 148 |
r'//[^\n]*' |
| 149 |
t.lexer.lineno += 1 |
| 150 |
|
| 151 |
def t_cr(t): |
| 152 |
r'\r' |
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
def t_ccomment(t): |
| 158 |
r'/\*(.|\n)*?\*/' |
| 159 |
t.lexer.lineno += t.value.count('\n') |
| 160 |
|
| 161 |
def t_header_name(t): |
| 162 |
r'<([\/]?[^\/\*\n>])*[\/]?>(?=[ \t\f\v\r\n])' |
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
t.type = 'HEADER_NAME' |
| 172 |
t.value = SystemHeaderName(t.value) |
| 173 |
return t |
| 174 |
|
| 175 |
def t_directive(t): |
| 176 |
r'\#[ \t]*(ifdef|ifndef|if|elif|else|endif|define|undef|include_next|include|import|line|error|pragma)' |
| 177 |
if t.lexer.lasttoken in ('NEWLINE', None): |
| 178 |
t.type = t.value[1:].lstrip().upper() |
| 179 |
else: |
| 180 |
|
| 181 |
t.type = '#' |
| 182 |
t.lexer.nexttoken = ('IDENTIFIER', t.value[1:].lstrip()) |
| 183 |
return t |
| 184 |
|
| 185 |
@TOKEN(r'(' + IDENTIFIER + r')?\.\.\.') |
| 186 |
def t_ellipsis(t): |
| 187 |
"""In GNU C ellipsis can be prepended with a variable name, so not simply punctuation.""" |
| 188 |
t.type = 'ELLIPSIS' |
| 189 |
return t |
| 190 |
|
| 191 |
@TOKEN(punctuator_regex(punctuators)) |
| 192 |
def t_punctuator(t): |
| 193 |
t.type = punctuators[t.value][1] |
| 194 |
return t |
| 195 |
|
| 196 |
@TOKEN(CHARACTER_CONSTANT) |
| 197 |
def t_character_constant(t): |
| 198 |
t.type = 'CHARACTER_CONSTANT' |
| 199 |
return t |
| 200 |
|
| 201 |
@TOKEN(IDENTIFIER) |
| 202 |
def t_identifier(t): |
| 203 |
if t.value == 'defined': |
| 204 |
t.type = 'DEFINED' |
| 205 |
else: |
| 206 |
t.type = 'IDENTIFIER' |
| 207 |
return t |
| 208 |
|
| 209 |
|
| 210 |
@TOKEN(sub(r'({D}|\.{D})({D}|{L}|e[+-]|E[+-]|p[+-]|P[+-]|\.)*')) |
| 211 |
def t_pp_number(t): |
| 212 |
t.type = 'PP_NUMBER' |
| 213 |
return t |
| 214 |
|
| 215 |
@TOKEN(STRING_LITERAL) |
| 216 |
def t_string_literal(t): |
| 217 |
t.type = 'STRING_LITERAL' |
| 218 |
t.value = StringLiteral(t.value) |
| 219 |
return t |
| 220 |
|
| 221 |
def t_lparen(t): |
| 222 |
r'\(' |
| 223 |
if t.lexpos == 0 or t.lexer.lexdata[t.lexpos-1] not in (' \t\f\v\n'): |
| 224 |
t.type = 'LPAREN' |
| 225 |
else: |
| 226 |
t.type = '(' |
| 227 |
return t |
| 228 |
|
| 229 |
def t_continuation(t): |
| 230 |
r'\\\n' |
| 231 |
t.lexer.lineno += 1 |
| 232 |
return None |
| 233 |
|
| 234 |
def t_newline(t): |
| 235 |
r'\n' |
| 236 |
t.lexer.lineno += 1 |
| 237 |
t.type = 'NEWLINE' |
| 238 |
return t |
| 239 |
|
| 240 |
def t_error(t): |
| 241 |
t.type = 'OTHER' |
| 242 |
return t |
| 243 |
|
| 244 |
t_ignore = ' \t\v\f' |
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
class EvaluationContext(object): |
| 251 |
'''Interface for evaluating expression nodes. |
| 252 |
''' |
| 253 |
def is_defined(self, identifier): |
| 254 |
return False |
| 255 |
|
| 256 |
class ExpressionNode(object): |
| 257 |
def evaluate(self, context): |
| 258 |
return 0 |
| 259 |
|
| 260 |
def __str__(self): |
| 261 |
return '' |
| 262 |
|
| 263 |
class ConstantExpressionNode(ExpressionNode): |
| 264 |
def __init__(self, value): |
| 265 |
self.value = value |
| 266 |
|
| 267 |
def evaluate(self, context): |
| 268 |
return self.value |
| 269 |
|
| 270 |
def __str__(self): |
| 271 |
return str(self.value) |
| 272 |
|
| 273 |
class UnaryExpressionNode(ExpressionNode): |
| 274 |
def __init__(self, op, op_str, child): |
| 275 |
self.op = op |
| 276 |
self.op_str = op_str |
| 277 |
self.child = child |
| 278 |
|
| 279 |
def evaluate(self, context): |
| 280 |
return self.op(self.child.evaluate(context)) |
| 281 |
|
| 282 |
def __str__(self): |
| 283 |
return '(%s %s)' % (self.op_str, self.child) |
| 284 |
|
| 285 |
class BinaryExpressionNode(ExpressionNode): |
| 286 |
def __init__(self, op, op_str, left, right): |
| 287 |
self.op = op |
| 288 |
self.op_str = op_str |
| 289 |
self.left = left |
| 290 |
self.right = right |
| 291 |
|
| 292 |
def evaluate(self, context): |
| 293 |
return self.op(self.left.evaluate(context), |
| 294 |
self.right.evaluate(context)) |
| 295 |
|
| 296 |
def __str__(self): |
| 297 |
return '(%s %s %s)' % (self.left, self.op_str, self.right) |
| 298 |
|
| 299 |
class LogicalAndExpressionNode(ExpressionNode): |
| 300 |
def __init__(self, left, right): |
| 301 |
self.left = left |
| 302 |
self.right = right |
| 303 |
|
| 304 |
def evaluate(self, context): |
| 305 |
return self.left.evaluate(context) and self.right.evaluate(context) |
| 306 |
|
| 307 |
def __str__(self): |
| 308 |
return '(%s && %s)' % (self.left, self.right) |
| 309 |
|
| 310 |
class LogicalOrExpressionNode(ExpressionNode): |
| 311 |
def __init__(self, left, right): |
| 312 |
self.left = left |
| 313 |
self.right = right |
| 314 |
|
| 315 |
def evaluate(self, context): |
| 316 |
return self.left.evaluate(context) or self.right.evaluate(context) |
| 317 |
|
| 318 |
def __str__(self): |
| 319 |
return '(%s || %s)' % (self.left, self.right) |
| 320 |
|
| 321 |
class ConditionalExpressionNode(ExpressionNode): |
| 322 |
def __init__(self, condition, left, right): |
| 323 |
self.condition = condition |
| 324 |
self.left = left |
| 325 |
self.right = right |
| 326 |
|
| 327 |
def evaluate(self, context): |
| 328 |
if self.condition.evaluate(context): |
| 329 |
return self.left.evaluate(context) |
| 330 |
else: |
| 331 |
return self.right.evaluate(context) |
| 332 |
|
| 333 |
def __str__(self): |
| 334 |
return '(%s ? %s : %s)' % (self.condition, self.left, self.right) |
| 335 |
|
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
class PreprocessorLexer(lex.Lexer): |
| 341 |
def __init__(self): |
| 342 |
lex.Lexer.__init__(self) |
| 343 |
self.filename = '<input>' |
| 344 |
|
| 345 |
def input(self, data, filename=None): |
| 346 |
if filename: |
| 347 |
self.filename = filename |
| 348 |
self.lasttoken = None |
| 349 |
self.input_stack = [] |
| 350 |
|
| 351 |
lex.Lexer.input(self, data) |
| 352 |
|
| 353 |
def push_input(self, data, filename): |
| 354 |
self.input_stack.append( |
| 355 |
(self.lexdata, self.lexpos, self.filename, self.lineno)) |
| 356 |
self.lexdata = data |
| 357 |
self.lexpos = 0 |
| 358 |
self.lineno = 1 |
| 359 |
self.filename = filename |
| 360 |
self.lexlen = len(self.lexdata) |
| 361 |
|
| 362 |
def pop_input(self): |
| 363 |
self.lexdata, self.lexpos, self.filename, self.lineno = \ |
| 364 |
self.input_stack.pop() |
| 365 |
self.lexlen = len(self.lexdata) |
| 366 |
|
| 367 |
def token(self): |
| 368 |
result = lex.Lexer.token(self) |
| 369 |
while result is None and self.input_stack: |
| 370 |
self.pop_input() |
| 371 |
result = lex.Lexer.token(self) |
| 372 |
|
| 373 |
if result: |
| 374 |
self.lasttoken = result.type |
| 375 |
result.filename = self.filename |
| 376 |
else: |
| 377 |
self.lasttoken = None |
| 378 |
|
| 379 |
return result |
| 380 |
|
| 381 |
class TokenListLexer(object): |
| 382 |
def __init__(self, tokens): |
| 383 |
self.tokens = tokens |
| 384 |
self.pos = 0 |
| 385 |
|
| 386 |
def token(self): |
| 387 |
if self.pos < len(self.tokens): |
| 388 |
t = self.tokens[self.pos] |
| 389 |
self.pos += 1 |
| 390 |
return t |
| 391 |
else: |
| 392 |
return None |
| 393 |
|
| 394 |
def symbol_to_token(sym): |
| 395 |
if isinstance(sym, yacc.YaccSymbol): |
| 396 |
return sym.value |
| 397 |
elif isinstance(sym, lex.LexToken): |
| 398 |
return sym |
| 399 |
else: |
| 400 |
assert False, 'Not a symbol: %r' % sym |
| 401 |
|
| 402 |
def create_token(type, value, production=None): |
| 403 |
'''Create a token of type and value, at the position where 'production' |
| 404 |
was reduced. Don't specify production if the token is built-in''' |
| 405 |
t = lex.LexToken() |
| 406 |
t.type = type |
| 407 |
t.value = value |
| 408 |
t.lexpos = -1 |
| 409 |
if production: |
| 410 |
t.lineno = production.slice[1].lineno |
| 411 |
t.filename = production.slice[1].filename |
| 412 |
else: |
| 413 |
t.lineno = -1 |
| 414 |
t.filename = '<builtin>' |
| 415 |
return t |
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
class Grammar(object): |
| 422 |
prototype = None |
| 423 |
name = 'grammar' |
| 424 |
|
| 425 |
@classmethod |
| 426 |
def get_prototype(cls): |
| 427 |
if not cls.prototype: |
| 428 |
instance = cls() |
| 429 |
tabmodule = '%stab' % cls.name |
| 430 |
cls.prototype = yacc.yacc(module=instance, tabmodule=tabmodule) |
| 431 |
return cls.prototype |
| 432 |
|
| 433 |
class PreprocessorGrammar(Grammar): |
| 434 |
tokens = tokens |
| 435 |
name = 'pp' |
| 436 |
|
| 437 |
def p_preprocessing_file(self, p): |
| 438 |
'''preprocessing_file : group_opt |
| 439 |
''' |
| 440 |
|
| 441 |
def p_group_opt(self, p): |
| 442 |
'''group_opt : group |
| 443 |
| |
| 444 |
''' |
| 445 |
|
| 446 |
def p_group(self, p): |
| 447 |
'''group : group_part |
| 448 |
| group group_part |
| 449 |
''' |
| 450 |
|
| 451 |
def p_group_part(self, p): |
| 452 |
'''group_part : if_section |
| 453 |
| control_line |
| 454 |
| text_line |
| 455 |
''' |
| 456 |
|
| 457 |
def p_if_section(self, p): |
| 458 |
'''if_section : if_group elif_groups_opt else_group_opt endif_line |
| 459 |
''' |
| 460 |
|
| 461 |
def p_if_group(self, p): |
| 462 |
'''if_group : if_line group_opt |
| 463 |
''' |
| 464 |
|
| 465 |
def p_if_line(self, p): |
| 466 |
'''if_line : IF replaced_constant_expression NEWLINE |
| 467 |
| IFDEF IDENTIFIER NEWLINE |
| 468 |
| IFNDEF IDENTIFIER NEWLINE |
| 469 |
''' |
| 470 |
if p.parser.enable_declaratives(): |
| 471 |
type = p.slice[1].type |
| 472 |
if type == 'IF': |
| 473 |
if p[2]: |
| 474 |
result = p[2].evaluate(p.parser.namespace) |
| 475 |
else: |
| 476 |
|
| 477 |
result = False |
| 478 |
elif type == 'IFDEF': |
| 479 |
result = p.parser.namespace.is_defined(p[2]) |
| 480 |
elif type == 'IFNDEF': |
| 481 |
result = not p.parser.namespace.is_defined(p[2]) |
| 482 |
p.parser.write((create_token('PP_IFNDEF', p[2], p),)) |
| 483 |
else: |
| 484 |
result = False |
| 485 |
|
| 486 |
p.parser.condition_if(result) |
| 487 |
|
| 488 |
def p_elif_groups_opt(self, p): |
| 489 |
'''elif_groups_opt : elif_groups |
| 490 |
| |
| 491 |
''' |
| 492 |
|
| 493 |
def p_elif_groups(self, p): |
| 494 |
'''elif_groups : elif_group |
| 495 |
| elif_groups elif_group |
| 496 |
''' |
| 497 |
|
| 498 |
def p_elif_group(self, p): |
| 499 |
'''elif_group : elif_line group_opt |
| 500 |
''' |
| 501 |
|
| 502 |
def p_elif_line(self, p): |
| 503 |
'''elif_line : ELIF replaced_elif_constant_expression NEWLINE |
| 504 |
''' |
| 505 |
result = p[2].evaluate(p.parser.namespace) |
| 506 |
p.parser.condition_elif(result) |
| 507 |
|
| 508 |
def p_else_group_opt(self, p): |
| 509 |
'''else_group_opt : else_group |
| 510 |
| |
| 511 |
''' |
| 512 |
|
| 513 |
def p_else_group(self, p): |
| 514 |
'''else_group : else_line group_opt |
| 515 |
''' |
| 516 |
|
| 517 |
def p_else_line(self, p): |
| 518 |
'''else_line : ELSE NEWLINE |
| 519 |
''' |
| 520 |
p.parser.condition_else() |
| 521 |
|
| 522 |
def p_endif_line(self, p): |
| 523 |
'''endif_line : ENDIF pp_tokens_opt NEWLINE |
| 524 |
''' |
| 525 |
|
| 526 |
p.parser.condition_endif() |
| 527 |
|
| 528 |
def p_control_line(self, p): |
| 529 |
'''control_line : include_line NEWLINE |
| 530 |
| define_object |
| 531 |
| define_function |
| 532 |
| undef_line |
| 533 |
| LINE pp_tokens NEWLINE |
| 534 |
| error_line |
| 535 |
| PRAGMA pp_tokens_opt NEWLINE |
| 536 |
''' |
| 537 |
|
| 538 |
def p_include_line(self, p): |
| 539 |
'''include_line : INCLUDE pp_tokens |
| 540 |
| INCLUDE_NEXT pp_tokens |
| 541 |
| IMPORT pp_tokens |
| 542 |
''' |
| 543 |
if p.parser.enable_declaratives(): |
| 544 |
tokens = p[2] |
| 545 |
tokens = p.parser.namespace.apply_macros(tokens) |
| 546 |
if len(tokens) > 0: |
| 547 |
if p.slice[1].type == 'INCLUDE': |
| 548 |
if tokens[0].type == 'STRING_LITERAL': |
| 549 |
p.parser.include(tokens[0].value) |
| 550 |
return |
| 551 |
elif tokens[0].type == 'HEADER_NAME': |
| 552 |
p.parser.include_system(tokens[0].value) |
| 553 |
return |
| 554 |
elif p.slice[1].type == 'INCLUDE_NEXT': |
| 555 |
p.parser.include_next(tokens[0].value, p.slice[1].filename) |
| 556 |
return |
| 557 |
else: |
| 558 |
if tokens[0].type == 'STRING_LITERAL': |
| 559 |
p.parser.import_(tokens[0].value) |
| 560 |
return |
| 561 |
elif tokens[0].type == 'HEADER_NAME': |
| 562 |
p.parser.import_system(tokens[0].value) |
| 563 |
return |
| 564 |
|
| 565 |
|
| 566 |
print('Invalid #include', file=sys.stderr) |
| 567 |
|
| 568 |
def p_define_object(self, p): |
| 569 |
'''define_object : DEFINE IDENTIFIER replacement_list NEWLINE |
| 570 |
''' |
| 571 |
if p.parser.enable_declaratives(): |
| 572 |
p.parser.namespace.define_object(p[2], p[3]) |
| 573 |
|
| 574 |
|
| 575 |
tokens = p.parser.namespace.apply_macros(p[3]) |
| 576 |
lexer = TokenListLexer(tokens) |
| 577 |
expr_parser = StrictConstantExpressionParser(lexer, |
| 578 |
p.parser.namespace) |
| 579 |
value = expr_parser.parse(debug=False) |
| 580 |
if value is not None: |
| 581 |
value = value.evaluate(p.parser.namespace) |
| 582 |
p.parser.write( |
| 583 |
(create_token('PP_DEFINE_CONSTANT', (p[2], value), p),)) |
| 584 |
else: |
| 585 |
|
| 586 |
value = ' '.join([str(t.value) for t in p[3]]) |
| 587 |
p.parser.write((create_token('PP_DEFINE', (p[2], value), p),)) |
| 588 |
|
| 589 |
def p_define_function(self, p): |
| 590 |
'''define_function : DEFINE IDENTIFIER LPAREN define_function_params ')' pp_tokens_opt NEWLINE |
| 591 |
''' |
| 592 |
if p.parser.enable_declaratives(): |
| 593 |
p.parser.namespace.define_function(p[2], p[4], p[6]) |
| 594 |
|
| 595 |
def p_define_function_params(self, p): |
| 596 |
'''define_function_params : identifier_list_opt |
| 597 |
| ELLIPSIS |
| 598 |
| identifier_list ',' ELLIPSIS |
| 599 |
''' |
| 600 |
if len(p) == 2: |
| 601 |
if p[1] == 'ELLIPSIS': |
| 602 |
p[0] = ('...',) |
| 603 |
else: |
| 604 |
p[0] = p[1] |
| 605 |
else: |
| 606 |
p[0] = p[1] + ('...',) |
| 607 |
|
| 608 |
def p_undef_line(self, p): |
| 609 |
'''undef_line : UNDEF IDENTIFIER NEWLINE |
| 610 |
''' |
| 611 |
if p.parser.enable_declaratives(): |
| 612 |
p.parser.namespace.undef(p[2]) |
| 613 |
|
| 614 |
def p_error_line(self, p): |
| 615 |
'''error_line : ERROR pp_tokens_opt NEWLINE |
| 616 |
''' |
| 617 |
if p.parser.enable_declaratives(): |
| 618 |
p.parser.error(' '.join([t.value for t in p[2]]), |
| 619 |
p.slice[1].filename, p.slice[1].lineno) |
| 620 |
|
| 621 |
def p_text_line(self, p): |
| 622 |
'''text_line : pp_tokens_opt NEWLINE |
| 623 |
''' |
| 624 |
if p.parser.enable_declaratives(): |
| 625 |
tokens = p[1] |
| 626 |
tokens = p.parser.namespace.apply_macros(tokens) |
| 627 |
p.parser.write(tokens) |
| 628 |
|
| 629 |
def p_replacement_list(self, p): |
| 630 |
'''replacement_list : |
| 631 |
| preprocessing_token_no_lparen |
| 632 |
| preprocessing_token_no_lparen pp_tokens |
| 633 |
''' |
| 634 |
if len(p) == 3: |
| 635 |
p[0] = (p[1],) + p[2] |
| 636 |
elif len(p) == 2: |
| 637 |
p[0] = (p[1],) |
| 638 |
else: |
| 639 |
p[0] = () |
| 640 |
|
| 641 |
def p_identifier_list_opt(self, p): |
| 642 |
'''identifier_list_opt : identifier_list |
| 643 |
| |
| 644 |
''' |
| 645 |
if len(p) == 2: |
| 646 |
p[0] = p[1] |
| 647 |
else: |
| 648 |
p[0] = () |
| 649 |
|
| 650 |
def p_identifier_list(self, p): |
| 651 |
'''identifier_list : IDENTIFIER |
| 652 |
| identifier_list ',' IDENTIFIER |
| 653 |
''' |
| 654 |
if len(p) > 2: |
| 655 |
p[0] = p[1] + (p[3],) |
| 656 |
else: |
| 657 |
p[0] = (p[1],) |
| 658 |
|
| 659 |
def p_replaced_constant_expression(self, p): |
| 660 |
'''replaced_constant_expression : pp_tokens''' |
| 661 |
if p.parser.enable_conditionals(): |
| 662 |
tokens = p[1] |
| 663 |
tokens = p.parser.namespace.apply_macros(tokens) |
| 664 |
lexer = TokenListLexer(tokens) |
| 665 |
parser = ConstantExpressionParser(lexer, p.parser.namespace) |
| 666 |
p[0] = parser.parse(debug=True) |
| 667 |
else: |
| 668 |
p[0] = ConstantExpressionNode(0) |
| 669 |
|
| 670 |
def p_replaced_elif_constant_expression(self, p): |
| 671 |
'''replaced_elif_constant_expression : pp_tokens''' |
| 672 |
if p.parser.enable_elif_conditionals(): |
| 673 |
tokens = p[1] |
| 674 |
tokens = p.parser.namespace.apply_macros(tokens) |
| 675 |
lexer = TokenListLexer(tokens) |
| 676 |
parser = ConstantExpressionParser(lexer, p.parser.namespace) |
| 677 |
p[0] = parser.parse(debug=True) |
| 678 |
else: |
| 679 |
p[0] = ConstantExpressionNode(0) |
| 680 |
|
| 681 |
|
| 682 |
def p_pp_tokens_opt(self, p): |
| 683 |
'''pp_tokens_opt : pp_tokens |
| 684 |
| |
| 685 |
''' |
| 686 |
if len(p) == 2: |
| 687 |
p[0] = p[1] |
| 688 |
else: |
| 689 |
p[0] = () |
| 690 |
|
| 691 |
def p_pp_tokens(self, p): |
| 692 |
'''pp_tokens : preprocessing_token |
| 693 |
| pp_tokens preprocessing_token |
| 694 |
''' |
| 695 |
if len(p) == 2: |
| 696 |
p[0] = (p[1],) |
| 697 |
else: |
| 698 |
p[0] = p[1] + (p[2],) |
| 699 |
|
| 700 |
def p_preprocessing_token_no_lparen(self, p): |
| 701 |
'''preprocessing_token_no_lparen : HEADER_NAME |
| 702 |
| IDENTIFIER |
| 703 |
| PP_NUMBER |
| 704 |
| CHARACTER_CONSTANT |
| 705 |
| STRING_LITERAL |
| 706 |
| punctuator |
| 707 |
| DEFINED |
| 708 |
| OTHER |
| 709 |
''' |
| 710 |
p[0] = symbol_to_token(p.slice[1]) |
| 711 |
|
| 712 |
def p_preprocessing_token(self, p): |
| 713 |
'''preprocessing_token : preprocessing_token_no_lparen |
| 714 |
| LPAREN |
| 715 |
''' |
| 716 |
p[0] = symbol_to_token(p.slice[1]) |
| 717 |
|
| 718 |
def p_punctuator(self, p): |
| 719 |
'''punctuator : ELLIPSIS |
| 720 |
| RIGHT_ASSIGN |
| 721 |
| LEFT_ASSIGN |
| 722 |
| ADD_ASSIGN |
| 723 |
| SUB_ASSIGN |
| 724 |
| MUL_ASSIGN |
| 725 |
| DIV_ASSIGN |
| 726 |
| MOD_ASSIGN |
| 727 |
| AND_ASSIGN |
| 728 |
| XOR_ASSIGN |
| 729 |
| OR_ASSIGN |
| 730 |
| RIGHT_OP |
| 731 |
| LEFT_OP |
| 732 |
| INC_OP |
| 733 |
| DEC_OP |
| 734 |
| PTR_OP |
| 735 |
| AND_OP |
| 736 |
| OR_OP |
| 737 |
| LE_OP |
| 738 |
| GE_OP |
| 739 |
| EQ_OP |
| 740 |
| NE_OP |
| 741 |
| HASH_HASH |
| 742 |
| ';' |
| 743 |
| '{' |
| 744 |
| '}' |
| 745 |
| ',' |
| 746 |
| ':' |
| 747 |
| '=' |
| 748 |
| '(' |
| 749 |
| ')' |
| 750 |
| '[' |
| 751 |
| ']' |
| 752 |
| PERIOD |
| 753 |
| '&' |
| 754 |
| '!' |
| 755 |
| '~' |
| 756 |
| '-' |
| 757 |
| '+' |
| 758 |
| '*' |
| 759 |
| '/' |
| 760 |
| '%' |
| 761 |
| '<' |
| 762 |
| '>' |
| 763 |
| '^' |
| 764 |
| '|' |
| 765 |
| '?' |
| 766 |
| '#' |
| 767 |
''' |
| 768 |
p[0] = symbol_to_token(p.slice[1]) |
| 769 |
|
| 770 |
def p_error(self, t): |
| 771 |
if not t: |
| 772 |
|
| 773 |
print('Syntax error at end of file.', file=sys.stderr) |
| 774 |
else: |
| 775 |
|
| 776 |
print('%s:%d Syntax error at %r' % \ |
| 777 |
(t.lexer.filename, t.lexer.lineno, t.value), file=sys.stderr) |
| 778 |
|
| 779 |
|
| 780 |
|
| 781 |
|
| 782 |
|
| 783 |
|
| 784 |
class ConstantExpressionParseException(Exception): |
| 785 |
pass |
| 786 |
|
| 787 |
class ConstantExpressionGrammar(Grammar): |
| 788 |
name = 'expr' |
| 789 |
tokens = tokens |
| 790 |
|
| 791 |
def p_constant_expression(self, p): |
| 792 |
'''constant_expression : conditional_expression |
| 793 |
''' |
| 794 |
p[0] = p[1] |
| 795 |
p.parser.result = p[0] |
| 796 |
|
| 797 |
def p_character_constant(self, p): |
| 798 |
'''character_constant : CHARACTER_CONSTANT |
| 799 |
''' |
| 800 |
try: |
| 801 |
value = ord(eval(p[1].lstrip('L'))) |
| 802 |
except Exception: |
| 803 |
value = 0 |
| 804 |
p[0] = ConstantExpressionNode(value) |
| 805 |
|
| 806 |
def p_constant(self, p): |
| 807 |
'''constant : PP_NUMBER |
| 808 |
''' |
| 809 |
value = p[1].rstrip('LlUu') |
| 810 |
try: |
| 811 |
if value[:2] == '0x': |
| 812 |
value = int(value[2:], 16) |
| 813 |
elif value[0] == '0': |
| 814 |
value = int(value, 8) |
| 815 |
else: |
| 816 |
value = int(value) |
| 817 |
except ValueError: |
| 818 |
value = value.rstrip('eEfF') |
| 819 |
try: |
| 820 |
value = float(value) |
| 821 |
except ValueError: |
| 822 |
value = 0 |
| 823 |
p[0] = ConstantExpressionNode(value) |
| 824 |
|
| 825 |
def p_identifier(self, p): |
| 826 |
'''identifier : IDENTIFIER |
| 827 |
''' |
| 828 |
p[0] = ConstantExpressionNode(0) |
| 829 |
|
| 830 |
def p_primary_expression(self, p): |
| 831 |
'''primary_expression : constant |
| 832 |
| character_constant |
| 833 |
| identifier |
| 834 |
| '(' expression ')' |
| 835 |
| LPAREN expression ')' |
| 836 |
''' |
| 837 |
if p[1] == '(': |
| 838 |
p[0] = p[2] |
| 839 |
else: |
| 840 |
p[0] = p[1] |
| 841 |
|
| 842 |
def p_postfix_expression(self, p): |
| 843 |
'''postfix_expression : primary_expression |
| 844 |
''' |
| 845 |
p[0] = p[1] |
| 846 |
|
| 847 |
def p_unary_expression(self, p): |
| 848 |
'''unary_expression : postfix_expression |
| 849 |
| unary_operator cast_expression |
| 850 |
''' |
| 851 |
if len(p) == 2: |
| 852 |
p[0] = p[1] |
| 853 |
elif type(p[1]) == tuple: |
| 854 |
|
| 855 |
p[0] = UnaryExpressionNode(p[1][0], p[1][1], p[2]) |
| 856 |
else: |
| 857 |
|
| 858 |
p[0] = None |
| 859 |
|
| 860 |
def p_unary_operator(self, p): |
| 861 |
'''unary_operator : '+' |
| 862 |
| '-' |
| 863 |
| '~' |
| 864 |
| '!' |
| 865 |
''' |
| 866 |
|
| 867 |
p[0] = ({ |
| 868 |
'+': operator.pos, |
| 869 |
'-': operator.neg, |
| 870 |
'~': operator.inv, |
| 871 |
'!': operator.not_}[p[1]], p[1]) |
| 872 |
|
| 873 |
def p_cast_expression(self, p): |
| 874 |
'''cast_expression : unary_expression |
| 875 |
''' |
| 876 |
p[0] = p[len(p) - 1] |
| 877 |
|
| 878 |
def p_multiplicative_expression(self, p): |
| 879 |
'''multiplicative_expression : cast_expression |
| 880 |
| multiplicative_expression '*' cast_expression |
| 881 |
| multiplicative_expression '/' cast_expression |
| 882 |
| multiplicative_expression '%' cast_expression |
| 883 |
''' |
| 884 |
if len(p) == 2: |
| 885 |
p[0] = p[1] |
| 886 |
else: |
| 887 |
p[0] = BinaryExpressionNode({ |
| 888 |
'*': operator.mul, |
| 889 |
'/': operator.div, |
| 890 |
'%': operator.mod}[p[2]], p[2], p[1], p[3]) |
| 891 |
|
| 892 |
def p_additive_expression(self, p): |
| 893 |
'''additive_expression : multiplicative_expression |
| 894 |
| additive_expression '+' multiplicative_expression |
| 895 |
| additive_expression '-' multiplicative_expression |
| 896 |
''' |
| 897 |
if len(p) == 2: |
| 898 |
p[0] = p[1] |
| 899 |
else: |
| 900 |
p[0] = BinaryExpressionNode({ |
| 901 |
'+': operator.add, |
| 902 |
'-': operator.sub}[p[2]], p[2], p[1], p[3]) |
| 903 |
|
| 904 |
def p_shift_expression(self, p): |
| 905 |
'''shift_expression : additive_expression |
| 906 |
| shift_expression LEFT_OP additive_expression |
| 907 |
| shift_expression RIGHT_OP additive_expression |
| 908 |
''' |
| 909 |
if len(p) == 2: |
| 910 |
p[0] = p[1] |
| 911 |
else: |
| 912 |
p[0] = BinaryExpressionNode({ |
| 913 |
'<<': operator.lshift, |
| 914 |
'>>': operator.rshift}[p[2]], p[2], p[1], p[3]) |
| 915 |
|
| 916 |
def p_relational_expression(self, p): |
| 917 |
'''relational_expression : shift_expression |
| 918 |
| relational_expression '<' shift_expression |
| 919 |
| relational_expression '>' shift_expression |
| 920 |
| relational_expression LE_OP shift_expression |
| 921 |
| relational_expression GE_OP shift_expression |
| 922 |
''' |
| 923 |
if len(p) == 2: |
| 924 |
p[0] = p[1] |
| 925 |
else: |
| 926 |
p[0] = BinaryExpressionNode({ |
| 927 |
'>': operator.gt, |
| 928 |
'<': operator.lt, |
| 929 |
'<=': operator.le, |
| 930 |
'>=': operator.ge}[p[2]], p[2], p[1], p[3]) |
| 931 |
|
| 932 |
def p_equality_expression(self, p): |
| 933 |
'''equality_expression : relational_expression |
| 934 |
| equality_expression EQ_OP relational_expression |
| 935 |
| equality_expression NE_OP relational_expression |
| 936 |
''' |
| 937 |
if len(p) == 2: |
| 938 |
p[0] = p[1] |
| 939 |
else: |
| 940 |
p[0] = BinaryExpressionNode({ |
| 941 |
'==': operator.eq, |
| 942 |
'!=': operator.ne}[p[2]], p[2], p[1], p[3]) |
| 943 |
|
| 944 |
def p_and_expression(self, p): |
| 945 |
'''and_expression : equality_expression |
| 946 |
| and_expression '&' equality_expression |
| 947 |
''' |
| 948 |
if len(p) == 2: |
| 949 |
p[0] = p[1] |
| 950 |
else: |
| 951 |
p[0] = BinaryExpressionNode(operator.and_, '&', p[1], p[3]) |
| 952 |
|
| 953 |
def p_exclusive_or_expression(self, p): |
| 954 |
'''exclusive_or_expression : and_expression |
| 955 |
| exclusive_or_expression '^' and_expression |
| 956 |
''' |
| 957 |
if len(p) == 2: |
| 958 |
p[0] = p[1] |
| 959 |
else: |
| 960 |
p[0] = BinaryExpressionNode(operator.xor, '^', p[1], p[3]) |
| 961 |
|
| 962 |
def p_inclusive_or_expression(self, p): |
| 963 |
'''inclusive_or_expression : exclusive_or_expression |
| 964 |
| inclusive_or_expression '|' exclusive_or_expression |
| 965 |
''' |
| 966 |
if len(p) == 2: |
| 967 |
p[0] = p[1] |
| 968 |
else: |
| 969 |
p[0] = BinaryExpressionNode(operator.or_, '|', p[1], p[3]) |
| 970 |
|
| 971 |
def p_logical_and_expression(self, p): |
| 972 |
'''logical_and_expression : inclusive_or_expression |
| 973 |
| logical_and_expression AND_OP inclusive_or_expression |
| 974 |
''' |
| 975 |
if len(p) == 2: |
| 976 |
p[0] = p[1] |
| 977 |
else: |
| 978 |
p[0] = LogicalAndExpressionNode(p[1], p[3]) |
| 979 |
|
| 980 |
def p_logical_or_expression(self, p): |
| 981 |
'''logical_or_expression : logical_and_expression |
| 982 |
| logical_or_expression OR_OP logical_and_expression |
| 983 |
''' |
| 984 |
if len(p) == 2: |
| 985 |
p[0] = p[1] |
| 986 |
else: |
| 987 |
p[0] = LogicalOrExpressionNode(p[1], p[3]) |
| 988 |
|
| 989 |
|
| 990 |
def p_conditional_expression(self, p): |
| 991 |
'''conditional_expression : logical_or_expression |
| 992 |
| logical_or_expression '?' expression ':' conditional_expression |
| 993 |
''' |
| 994 |
if len(p) == 2: |
| 995 |
p[0] = p[1] |
| 996 |
else: |
| 997 |
p[0] = ConditionalExpressionNode(p[1], p[3], p[5]) |
| 998 |
|
| 999 |
def p_assignment_expression(self, p): |
| 1000 |
'''assignment_expression : conditional_expression |
| 1001 |
| unary_expression assignment_operator assignment_expression |
| 1002 |
''' |
| 1003 |
|
| 1004 |
if len(p) == 2: |
| 1005 |
p[0] = p[1] |
| 1006 |
|
| 1007 |
def p_assignment_operator(self, p): |
| 1008 |
'''assignment_operator : '=' |
| 1009 |
| MUL_ASSIGN |
| 1010 |
| DIV_ASSIGN |
| 1011 |
| MOD_ASSIGN |
| 1012 |
| ADD_ASSIGN |
| 1013 |
| SUB_ASSIGN |
| 1014 |
| LEFT_ASSIGN |
| 1015 |
| RIGHT_ASSIGN |
| 1016 |
| AND_ASSIGN |
| 1017 |
| XOR_ASSIGN |
| 1018 |
| OR_ASSIGN |
| 1019 |
''' |
| 1020 |
|
| 1021 |
def p_expression(self, p): |
| 1022 |
'''expression : assignment_expression |
| 1023 |
| expression ',' assignment_expression |
| 1024 |
''' |
| 1025 |
|
| 1026 |
if len(p) == 2: |
| 1027 |
p[0] = p[1] |
| 1028 |
|
| 1029 |
def p_error(self, t): |
| 1030 |
raise ConstantExpressionParseException() |
| 1031 |
|
| 1032 |
class StrictConstantExpressionGrammar(ConstantExpressionGrammar): |
| 1033 |
name = 'strict_expr' |
| 1034 |
tokens = tokens |
| 1035 |
|
| 1036 |
def p_identifier(self, p): |
| 1037 |
'''identifier : IDENTIFIER |
| 1038 |
''' |
| 1039 |
raise ConstantExpressionParseException() |
| 1040 |
|
| 1041 |
class ExecutionState(object): |
| 1042 |
def __init__(self, parent_enabled, enabled): |
| 1043 |
self.enabled = parent_enabled and enabled |
| 1044 |
self.context_enabled = enabled |
| 1045 |
self.parent_enabled = parent_enabled |
| 1046 |
|
| 1047 |
def enable(self, result): |
| 1048 |
if result: |
| 1049 |
self.enabled = self.parent_enabled and not self.context_enabled |
| 1050 |
self.context_enabled = True |
| 1051 |
else: |
| 1052 |
self.enabled = False |
| 1053 |
|
| 1054 |
class PreprocessorParser(yacc.Parser): |
| 1055 |
def __init__(self, gcc_search_path=True): |
| 1056 |
yacc.Parser.__init__(self) |
| 1057 |
self.lexer = lex.lex(cls=PreprocessorLexer) |
| 1058 |
PreprocessorGrammar.get_prototype().init_parser(self) |
| 1059 |
|
| 1060 |
|
| 1061 |
self.system_headers = {} |
| 1062 |
|
| 1063 |
|
| 1064 |
self.include_path = ['/usr/local/include', '/usr/include'] |
| 1065 |
if sys.platform == 'darwin': |
| 1066 |
self.framework_path = ['/System/Library/Frameworks', |
| 1067 |
'/Library/Frameworks'] |
| 1068 |
else: |
| 1069 |
self.framework_path = [] |
| 1070 |
|
| 1071 |
if gcc_search_path: |
| 1072 |
self.add_gcc_search_path() |
| 1073 |
self.add_cpp_search_path() |
| 1074 |
|
| 1075 |
self.lexer.filename = '' |
| 1076 |
|
| 1077 |
self.defines = {} |
| 1078 |
self.namespace = PreprocessorNamespace() |
| 1079 |
|
| 1080 |
def define(self, name, value): |
| 1081 |
self.defines[name] = value |
| 1082 |
|
| 1083 |
def add_gcc_search_path(self): |
| 1084 |
from subprocess import Popen, PIPE |
| 1085 |
path = Popen('gcc -print-file-name=include', |
| 1086 |
shell=True, stdout=PIPE).communicate()[0].strip() |
| 1087 |
if path: |
| 1088 |
self.include_path.append(path) |
| 1089 |
|
| 1090 |
def add_cpp_search_path(self): |
| 1091 |
from subprocess import Popen, PIPE |
| 1092 |
try: |
| 1093 |
open('test.h', 'a').close() |
| 1094 |
output = Popen('cpp -v test.h', shell=True, stderr=PIPE).communicate()[1] |
| 1095 |
finally: |
| 1096 |
os.remove('test.h') |
| 1097 |
if output: |
| 1098 |
output = output.split('\n') |
| 1099 |
while output and not '#include <...>' in output[0]: |
| 1100 |
print(('Skipping:', output[0])) |
| 1101 |
del output[0] |
| 1102 |
if output: |
| 1103 |
del output[0] |
| 1104 |
while output and not 'End of search list' in output[0]: |
| 1105 |
self.include_path.append(output[0].strip()) |
| 1106 |
print(('Adding:', output[0].strip())) |
| 1107 |
del output[0] |
| 1108 |
|
| 1109 |
def parse(self, filename=None, data=None, namespace=None, debug=False): |
| 1110 |
self.output = [] |
| 1111 |
if not namespace: |
| 1112 |
namespace = self.namespace |
| 1113 |
for name, value in self.defines.items(): |
| 1114 |
namespace.define_object(name, (create_token('IDENTIFIER', value),)) |
| 1115 |
self.namespace = namespace |
| 1116 |
self.imported_headers = set() |
| 1117 |
self.condition_stack = [ExecutionState(True, True)] |
| 1118 |
if filename: |
| 1119 |
if not data: |
| 1120 |
data = open(filename, 'r').read() |
| 1121 |
self.lexer.input(data, filename) |
| 1122 |
elif data: |
| 1123 |
self.lexer.input(data, '<input>') |
| 1124 |
|
| 1125 |
return yacc.Parser.parse(self, debug=debug) |
| 1126 |
|
| 1127 |
def push_file(self, filename, data=None): |
| 1128 |
print(filename, file=sys.stderr) |
| 1129 |
if not data: |
| 1130 |
data = open(filename).read() |
| 1131 |
self.lexer.push_input(data, filename) |
| 1132 |
|
| 1133 |
def include(self, header): |
| 1134 |
path = self.get_header_path(header) |
| 1135 |
if path: |
| 1136 |
self.push_file(path) |
| 1137 |
else: |
| 1138 |
print('"%s" not found' % header, file=sys.stderr) |
| 1139 |
|
| 1140 |
def include_system(self, header): |
| 1141 |
if header in self.system_headers: |
| 1142 |
self.push_file(header, self.system_headers[header]) |
| 1143 |
return |
| 1144 |
|
| 1145 |
path = self.get_system_header_path(header) |
| 1146 |
if path: |
| 1147 |
self.push_file(path) |
| 1148 |
else: |
| 1149 |
print('"%s" not found' % header, file=sys.stderr) |
| 1150 |
|
| 1151 |
def include_next(self, header, reference): |
| 1152 |
|
| 1153 |
next = False |
| 1154 |
for path in self.include_path: |
| 1155 |
p = os.path.join(path, header) |
| 1156 |
if os.path.exists(p): |
| 1157 |
if next: |
| 1158 |
self.push_file(p) |
| 1159 |
return |
| 1160 |
elif p == reference: |
| 1161 |
next = True |
| 1162 |
print('%s: cannot include_next from %s' % \ |
| 1163 |
(header, reference), file=sys.stderr) |
| 1164 |
|
| 1165 |
def import_(self, header): |
| 1166 |
path = self.get_header_path(header) |
| 1167 |
if path: |
| 1168 |
if path not in self.imported_headers: |
| 1169 |
self.imported_headers.add(path) |
| 1170 |
self.push_file(path) |
| 1171 |
else: |
| 1172 |
print('"%s" not found' % header, file=sys.stderr) |
| 1173 |
|
| 1174 |
def import_system(self, header): |
| 1175 |
if header in self.system_headers: |
| 1176 |
if path not in self.imported_headers: |
| 1177 |
self.imported_headers.add(path) |
| 1178 |
self.push_file(header, self.system_headers[header]) |
| 1179 |
return |
| 1180 |
path = self.get_system_header_path(header) |
| 1181 |
if path: |
| 1182 |
if path not in self.imported_headers: |
| 1183 |
self.imported_headers.add(path) |
| 1184 |
self.push_file(path) |
| 1185 |
else: |
| 1186 |
print('"%s" not found' % header, file=sys.stderr) |
| 1187 |
|
| 1188 |
def get_header_path(self, header): |
| 1189 |
p = os.path.join(os.path.dirname(self.lexer.filename), header) |
| 1190 |
if os.path.exists(p): |
| 1191 |
self.push_file(p) |
| 1192 |
return p |
| 1193 |
elif sys.platform == 'darwin': |
| 1194 |
p = self.get_framework_header_path(header) |
| 1195 |
if not p: |
| 1196 |
p = self.get_system_header_path(header) |
| 1197 |
return p |
| 1198 |
|
| 1199 |
def get_system_header_path(self, header): |
| 1200 |
for path in self.include_path: |
| 1201 |
p = os.path.join(path, header) |
| 1202 |
if os.path.exists(p): |
| 1203 |
return p |
| 1204 |
if sys.platform == 'darwin': |
| 1205 |
return self.get_framework_header_path(header) |
| 1206 |
|
| 1207 |
def get_framework_header_path(self, header): |
| 1208 |
if '/' in header: |
| 1209 |
|
| 1210 |
framework, header = header.split('/', 1) |
| 1211 |
|
| 1212 |
paths = self.framework_path[:] |
| 1213 |
|
| 1214 |
localpath = '' |
| 1215 |
for parent in self.lexer.filename.split('.framework/')[:-1]: |
| 1216 |
localpath += parent + '.framework' |
| 1217 |
paths.append(os.path.join(localpath, 'Frameworks')) |
| 1218 |
for path in paths: |
| 1219 |
p = os.path.join(path, '%s.framework' % framework, |
| 1220 |
'Headers', header) |
| 1221 |
if os.path.exists(p): |
| 1222 |
return p |
| 1223 |
|
| 1224 |
def error(self, message, filename, line): |
| 1225 |
print('%s:%d #error %s' % (filename, line, message), file=sys.stderr) |
| 1226 |
|
| 1227 |
def condition_if(self, result): |
| 1228 |
self.condition_stack.append( |
| 1229 |
ExecutionState(self.condition_stack[-1].enabled, result)) |
| 1230 |
|
| 1231 |
def condition_elif(self, result): |
| 1232 |
self.condition_stack[-1].enable(result) |
| 1233 |
|
| 1234 |
def condition_else(self): |
| 1235 |
self.condition_stack[-1].enable(True) |
| 1236 |
|
| 1237 |
def condition_endif(self): |
| 1238 |
self.condition_stack.pop() |
| 1239 |
|
| 1240 |
def enable_declaratives(self): |
| 1241 |
return self.condition_stack[-1].enabled |
| 1242 |
|
| 1243 |
def enable_conditionals(self): |
| 1244 |
return self.condition_stack[-1].enabled |
| 1245 |
|
| 1246 |
def enable_elif_conditionals(self): |
| 1247 |
return self.condition_stack[-1].parent_enabled and \ |
| 1248 |
not self.condition_stack[-1].context_enabled |
| 1249 |
|
| 1250 |
def write(self, tokens): |
| 1251 |
for t in tokens: |
| 1252 |
if t.type == 'HEADER_NAME': |
| 1253 |
|
| 1254 |
ta = create_token('<', '<') |
| 1255 |
ta.filename = t.filename |
| 1256 |
ta.lineno = t.lineno |
| 1257 |
self.output.append(ta) |
| 1258 |
|
| 1259 |
l = lex.lex(cls=PreprocessorLexer) |
| 1260 |
l.input(t.value, t.filename) |
| 1261 |
l.lineno = t.lineno |
| 1262 |
tb = l.token() |
| 1263 |
while tb is not None: |
| 1264 |
if hasattr(tb, 'lexer'): |
| 1265 |
del tb.lexer |
| 1266 |
self.output.append(tb) |
| 1267 |
tb = l.token() |
| 1268 |
|
| 1269 |
tc = create_token('>', '>') |
| 1270 |
tc.filename = t.filename |
| 1271 |
tc.lineno = t.lineno |
| 1272 |
self.output.append(tc) |
| 1273 |
|
| 1274 |
continue |
| 1275 |
|
| 1276 |
if hasattr(t, 'lexer'): |
| 1277 |
del t.lexer |
| 1278 |
self.output.append(t) |
| 1279 |
|
| 1280 |
def get_memento(self): |
| 1281 |
return (set(self.namespace.objects.keys()), |
| 1282 |
set(self.namespace.functions.keys())) |
| 1283 |
|
| 1284 |
class ConstantExpressionParser(yacc.Parser): |
| 1285 |
_const_grammar = ConstantExpressionGrammar |
| 1286 |
|
| 1287 |
def __init__(self, lexer, namespace): |
| 1288 |
yacc.Parser.__init__(self) |
| 1289 |
self.lexer = lexer |
| 1290 |
self.namespace = namespace |
| 1291 |
self._const_grammar.get_prototype().init_parser(self) |
| 1292 |
|
| 1293 |
def parse(self, debug=False): |
| 1294 |
self.result = None |
| 1295 |
try: |
| 1296 |
yacc.Parser.parse(self, lexer=self.lexer, debug=debug) |
| 1297 |
except ConstantExpressionParseException: |
| 1298 |
|
| 1299 |
pass |
| 1300 |
return self.result |
| 1301 |
|
| 1302 |
class StrictConstantExpressionParser(ConstantExpressionParser): |
| 1303 |
_const_grammar = StrictConstantExpressionGrammar |
| 1304 |
|
| 1305 |
class PreprocessorNamespace(EvaluationContext): |
| 1306 |
def __init__(self, gcc_macros=True, |
| 1307 |
stdc_macros=True, |
| 1308 |
workaround_macros=True): |
| 1309 |
self.objects = {} |
| 1310 |
self.functions = {} |
| 1311 |
|
| 1312 |
if stdc_macros: |
| 1313 |
self.add_stdc_macros() |
| 1314 |
|
| 1315 |
if gcc_macros: |
| 1316 |
self.add_gcc_macros() |
| 1317 |
|
| 1318 |
if workaround_macros: |
| 1319 |
self.add_workaround_macros() |
| 1320 |
|
| 1321 |
def add_stdc_macros(self): |
| 1322 |
'''Add macros defined in 6.10.8 except __FILE__ and __LINE__. |
| 1323 |
|
| 1324 |
This is potentially dangerous, as this preprocessor is not ISO |
| 1325 |
compliant in many ways (the most obvious is the lack of # and ## |
| 1326 |
operators). It is required for Apple headers, however, which |
| 1327 |
otherwise assume some truly bizarre syntax is ok. |
| 1328 |
''' |
| 1329 |
import time |
| 1330 |
date = time.strftime('%b %d %Y') |
| 1331 |
t = time.strftime('%H:%M:S') |
| 1332 |
self.define_object('__DATE__', |
| 1333 |
(create_token('STRING_LITERAL', date),)) |
| 1334 |
self.define_object('__TIME__', |
| 1335 |
(create_token('STRING_LITERAL', t),)) |
| 1336 |
self.define_object('__STDC__', |
| 1337 |
(create_token('PP_NUMBER', '1'),)) |
| 1338 |
self.define_object('__STDC_HOSTED__', |
| 1339 |
(create_token('PP_NUMBER', '1'),)) |
| 1340 |
self.define_object('__STDC_VERSION', |
| 1341 |
(create_token('PP_NUMBER', '199901L'),)) |
| 1342 |
|
| 1343 |
def add_gcc_macros(self): |
| 1344 |
import platform |
| 1345 |
import sys |
| 1346 |
|
| 1347 |
gcc_macros = ('__GLIBC_HAVE_LONG_LONG', '__GNUC__',) |
| 1348 |
|
| 1349 |
|
| 1350 |
machine_macros = { |
| 1351 |
'x86_64': ('__amd64', '__amd64__', '__x86_64', '__x86_64__', |
| 1352 |
'__tune_k8__', '__MMX__', '__SSE__', '__SSE2__', |
| 1353 |
'__SSE_MATH__', '__k8', '__k8__'), |
| 1354 |
'Power Macintosh': ('_ARCH_PPC', '__BIG_ENDIAN__', '_BIG_ENDIAN', |
| 1355 |
'__ppc__', '__POWERPC__'), |
| 1356 |
|
| 1357 |
}.get(platform.machine(), ()) |
| 1358 |
platform_macros = { |
| 1359 |
'linux': ('__gnu_linux__', '__linux', '__linux__', 'linux', |
| 1360 |
'__unix', '__unix__', 'unix'), |
| 1361 |
'linux2': ('__gnu_linux__', '__linux', '__linux__', 'linux', |
| 1362 |
'__unix', '__unix__', 'unix'), |
| 1363 |
'linux3': ('__gnu_linux__', '__linux', '__linux__', 'linux', |
| 1364 |
'__unix', '__unix__', 'unix'), |
| 1365 |
'darwin': ('__MACH__', '__APPLE__', '__DYNAMIC__', '__APPLE_CC__'), |
| 1366 |
'win32': ('_WIN32',), |
| 1367 |
|
| 1368 |
}.get(sys.platform, ()) |
| 1369 |
|
| 1370 |
tok1 = lex.LexToken() |
| 1371 |
tok1.type = 'PP_NUMBER' |
| 1372 |
tok1.value = '1' |
| 1373 |
tok1.lineno = -1 |
| 1374 |
tok1.lexpos = -1 |
| 1375 |
|
| 1376 |
for macro in machine_macros + platform_macros + gcc_macros: |
| 1377 |
self.define_object(macro, (tok1,)) |
| 1378 |
|
| 1379 |
self.define_object('inline', ()) |
| 1380 |
self.define_object('__inline', ()) |
| 1381 |
self.define_object('__inline__', ()) |
| 1382 |
self.define_object('__const', (create_token('IDENTIFIER', 'const'),)) |
| 1383 |
|
| 1384 |
def add_workaround_macros(self): |
| 1385 |
if sys.platform == 'darwin': |
| 1386 |
self.define_object('CF_INLINE', ()) |
| 1387 |
|
| 1388 |
def is_defined(self, name): |
| 1389 |
return name in self.objects or name in self.functions |
| 1390 |
|
| 1391 |
def undef(self, name): |
| 1392 |
if name in self.objects: |
| 1393 |
del self.objects[name] |
| 1394 |
|
| 1395 |
if name in self.functions: |
| 1396 |
del self.functions[name] |
| 1397 |
|
| 1398 |
def define_object(self, name, replacements): |
| 1399 |
|
| 1400 |
for r in replacements: |
| 1401 |
if hasattr(r, 'lexer'): |
| 1402 |
del r.lexer |
| 1403 |
self.objects[name] = replacements |
| 1404 |
|
| 1405 |
def define_function(self, name, params, replacements): |
| 1406 |
|
| 1407 |
for r in replacements: |
| 1408 |
if hasattr(r, 'lexer'): |
| 1409 |
del r.lexer |
| 1410 |
replacements = list(replacements) |
| 1411 |
params = list(params) |
| 1412 |
numargs = len(params) |
| 1413 |
for i, t in enumerate(replacements): |
| 1414 |
if hasattr(t, 'lexer'): |
| 1415 |
del t.lexer |
| 1416 |
if t.type == 'IDENTIFIER' and t.value in params: |
| 1417 |
replacements[i] = params.index(t.value) |
| 1418 |
elif t.type == 'IDENTIFIER' and t.value == '__VA_ARGS__' and \ |
| 1419 |
'...' in params: |
| 1420 |
replacements[i] = len(params) - 1 |
| 1421 |
|
| 1422 |
self.functions[name] = replacements, numargs |
| 1423 |
|
| 1424 |
def apply_macros(self, tokens, replacing=None): |
| 1425 |
repl = [] |
| 1426 |
i = 0 |
| 1427 |
while i < len(tokens): |
| 1428 |
token = tokens[i] |
| 1429 |
if token.type == 'IDENTIFIER' and token.value in self.objects: |
| 1430 |
r = self.objects[token.value] |
| 1431 |
if token.value != replacing and r: |
| 1432 |
repl += self.apply_macros(r, token.value) |
| 1433 |
elif token.type == 'IDENTIFIER' and \ |
| 1434 |
token.value in self.functions and \ |
| 1435 |
len(tokens) - i > 2 and \ |
| 1436 |
tokens[i+1].value == '(': |
| 1437 |
|
| 1438 |
r, numargs = self.functions[token.value][:] |
| 1439 |
|
| 1440 |
|
| 1441 |
i += 2 |
| 1442 |
params = [[]] |
| 1443 |
parens = 0 |
| 1444 |
while i < len(tokens): |
| 1445 |
if tokens[i].value == ',' and parens == 0 and \ |
| 1446 |
len(params) < numargs: |
| 1447 |
params.append([]) |
| 1448 |
elif tokens[i].value == ')' and parens == 0: |
| 1449 |
break |
| 1450 |
else: |
| 1451 |
if tokens[i].value == '(': |
| 1452 |
parens += 1 |
| 1453 |
elif tokens[i].value == ')': |
| 1454 |
parens -= 1 |
| 1455 |
params[-1].append(tokens[i]) |
| 1456 |
i += 1 |
| 1457 |
|
| 1458 |
if token.value != replacing and r: |
| 1459 |
newr = [] |
| 1460 |
for t in r: |
| 1461 |
if type(t) == int: |
| 1462 |
newr += params[t] |
| 1463 |
else: |
| 1464 |
newr.append(t) |
| 1465 |
repl += self.apply_macros(newr, token.value) |
| 1466 |
elif token.type == 'DEFINED': |
| 1467 |
if len(tokens) - i > 3 and \ |
| 1468 |
tokens[i + 1].type in ('(', 'LPAREN') and \ |
| 1469 |
tokens[i + 2].type == 'IDENTIFIER' and \ |
| 1470 |
tokens[i + 3].type == ')': |
| 1471 |
result = self.is_defined(tokens[i + 2].value) |
| 1472 |
i += 3 |
| 1473 |
elif len(tokens) - i > 1 and \ |
| 1474 |
tokens[i + 1].type == 'IDENTIFIER': |
| 1475 |
result = self.is_defined(tokens[i + 1].value) |
| 1476 |
i += 1 |
| 1477 |
else: |
| 1478 |
|
| 1479 |
print('Invalid use of "defined"', file=sys.stderr) |
| 1480 |
result = 0 |
| 1481 |
t = lex.LexToken() |
| 1482 |
t.value = str(int(result)) |
| 1483 |
t.type = 'PP_NUMBER' |
| 1484 |
t.lexpos = token.lexpos |
| 1485 |
t.lineno = token.lineno |
| 1486 |
repl.append(t) |
| 1487 |
else: |
| 1488 |
repl.append(token) |
| 1489 |
i += 1 |
| 1490 |
return repl |
| 1491 |
|
| 1492 |
def copy(self): |
| 1493 |
n = PreprocessorNamespace(gcc_macros=False, workaround_macros=False) |
| 1494 |
n.functions = self.functions.copy() |
| 1495 |
n.objects = self.objects.copy() |
| 1496 |
return n |
| 1497 |
|
| 1498 |
if __name__ == '__main__': |
| 1499 |
filename = sys.argv[1] |
| 1500 |
parser = PreprocessorParser() |
| 1501 |
parser.parse(filename, debug=True) |
| 1502 |
print(' '.join([str(t.value) for t in parser.output])) |