Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | """A glorified C pre-processor parser.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 3 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 4 | import ctypes |
| 5 | import logging |
| 6 | import os |
| 7 | import re |
| 8 | import site |
| 9 | import utils |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 10 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 11 | top = os.getenv('ANDROID_BUILD_TOP') |
| 12 | if top is None: |
| 13 | utils.panic('ANDROID_BUILD_TOP not set.\n') |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 14 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 15 | # Set up the env vars for libclang. |
| 16 | site.addsitedir(os.path.join(top, 'external/clang/bindings/python')) |
| 17 | os.putenv('LD_LIBRARY_PATH', os.path.join(top, 'prebuilts/sdk/tools/linux')) |
| 18 | |
| 19 | import clang.cindex |
| 20 | from clang.cindex import conf |
| 21 | from clang.cindex import Cursor |
| 22 | from clang.cindex import CursorKind |
| 23 | from clang.cindex import SourceLocation |
| 24 | from clang.cindex import SourceRange |
| 25 | from clang.cindex import TokenGroup |
| 26 | from clang.cindex import TokenKind |
| 27 | from clang.cindex import TranslationUnit |
| 28 | |
| 29 | from defaults import kCppUndefinedMacro |
| 30 | from defaults import kernel_remove_config_macros |
| 31 | from defaults import kernel_token_replacements |
| 32 | |
| 33 | |
| 34 | debugBlockParser = False |
| 35 | debugCppExpr = False |
| 36 | debugOptimIf01 = False |
| 37 | |
| 38 | ############################################################################### |
| 39 | ############################################################################### |
| 40 | ##### ##### |
| 41 | ##### C P P T O K E N S ##### |
| 42 | ##### ##### |
| 43 | ############################################################################### |
| 44 | ############################################################################### |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 45 | |
| 46 | # the list of supported C-preprocessor tokens |
| 47 | # plus a couple of C tokens as well |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 48 | tokEOF = "\0" |
| 49 | tokLN = "\n" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 50 | tokSTRINGIFY = "#" |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 51 | tokCONCAT = "##" |
| 52 | tokLOGICAND = "&&" |
| 53 | tokLOGICOR = "||" |
| 54 | tokSHL = "<<" |
| 55 | tokSHR = ">>" |
| 56 | tokEQUAL = "==" |
| 57 | tokNEQUAL = "!=" |
| 58 | tokLT = "<" |
| 59 | tokLTE = "<=" |
| 60 | tokGT = ">" |
| 61 | tokGTE = ">=" |
| 62 | tokELLIPSIS = "..." |
| 63 | tokSPACE = " " |
| 64 | tokDEFINED = "defined" |
| 65 | tokLPAREN = "(" |
| 66 | tokRPAREN = ")" |
| 67 | tokNOT = "!" |
| 68 | tokPLUS = "+" |
| 69 | tokMINUS = "-" |
| 70 | tokMULTIPLY = "*" |
| 71 | tokDIVIDE = "/" |
| 72 | tokMODULUS = "%" |
| 73 | tokBINAND = "&" |
| 74 | tokBINOR = "|" |
| 75 | tokBINXOR = "^" |
| 76 | tokCOMMA = "," |
| 77 | tokLBRACE = "{" |
| 78 | tokRBRACE = "}" |
| 79 | tokARROW = "->" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 80 | tokINCREMENT = "++" |
| 81 | tokDECREMENT = "--" |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 82 | tokNUMBER = "<number>" |
| 83 | tokIDENT = "<ident>" |
| 84 | tokSTRING = "<string>" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 85 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 86 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 87 | class Token(clang.cindex.Token): |
| 88 | """A class that represents one token after parsing. |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 89 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 90 | It inherits the class in libclang, with an extra id property to hold the |
| 91 | new spelling of the token. The spelling property in the base class is |
| 92 | defined as read-only. New names after macro instantiation are saved in |
| 93 | their ids now. It also facilitates the renaming of directive optimizations |
| 94 | like replacing 'ifndef X' with 'if !defined(X)'. |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 95 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 96 | It also overrides the cursor property of the base class. Because the one |
| 97 | in libclang always queries based on a single token, which usually doesn't |
| 98 | hold useful information. The cursor in this class can be set by calling |
| 99 | CppTokenizer.getTokensWithCursors(). Otherwise it returns the one in the |
| 100 | base class. |
| 101 | """ |
| 102 | |
| 103 | def __init__(self, tu=None, group=None, int_data=None, ptr_data=None, |
| 104 | cursor=None): |
| 105 | clang.cindex.Token.__init__(self) |
| 106 | self._id = None |
| 107 | self._tu = tu |
| 108 | self._group = group |
| 109 | self._cursor = cursor |
| 110 | # self.int_data and self.ptr_data are from the base class. But |
| 111 | # self.int_data doesn't accept a None value. |
| 112 | if int_data is not None: |
| 113 | self.int_data = int_data |
| 114 | self.ptr_data = ptr_data |
| 115 | |
| 116 | @property |
| 117 | def id(self): |
| 118 | """Name of the token.""" |
| 119 | if self._id is None: |
| 120 | return self.spelling |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 121 | else: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 122 | return self._id |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 123 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 124 | @id.setter |
| 125 | def id(self, new_id): |
| 126 | """Setting name of the token.""" |
| 127 | self._id = new_id |
| 128 | |
| 129 | @property |
| 130 | def cursor(self): |
| 131 | if self._cursor is None: |
| 132 | self._cursor = clang.cindex.Token.cursor |
| 133 | return self._cursor |
| 134 | |
| 135 | @cursor.setter |
| 136 | def cursor(self, new_cursor): |
| 137 | self._cursor = new_cursor |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 138 | |
| 139 | def __repr__(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 140 | if self.id == 'defined': |
| 141 | return self.id |
| 142 | elif self.kind == TokenKind.IDENTIFIER: |
| 143 | return "(ident %s)" % self.id |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 144 | |
| 145 | return self.id |
| 146 | |
| 147 | def __str__(self): |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 148 | return self.id |
| 149 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 150 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 151 | class BadExpectedToken(Exception): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 152 | """An exception that will be raised for unexpected tokens.""" |
| 153 | pass |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 154 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 155 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 156 | # The __contains__ function in libclang SourceRange class contains a bug. It |
| 157 | # gives wrong result when dealing with single line range. |
| 158 | # Bug filed with upstream: |
| 159 | # http://llvm.org/bugs/show_bug.cgi?id=22243, http://reviews.llvm.org/D7277 |
| 160 | def SourceRange__contains__(self, other): |
| 161 | """Determine if a given location is inside the range.""" |
| 162 | if not isinstance(other, SourceLocation): |
| 163 | return False |
| 164 | if other.file is None and self.start.file is None: |
| 165 | pass |
| 166 | elif (self.start.file.name != other.file.name or |
| 167 | other.file.name != self.end.file.name): |
| 168 | # same file name |
| 169 | return False |
| 170 | # same file, in between lines |
| 171 | if self.start.line < other.line < self.end.line: |
| 172 | return True |
| 173 | # same file, same line |
| 174 | elif self.start.line == other.line == self.end.line: |
| 175 | if self.start.column <= other.column <= self.end.column: |
| 176 | return True |
| 177 | elif self.start.line == other.line: |
| 178 | # same file first line |
| 179 | if self.start.column <= other.column: |
| 180 | return True |
| 181 | elif other.line == self.end.line: |
| 182 | # same file last line |
| 183 | if other.column <= self.end.column: |
| 184 | return True |
| 185 | return False |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 186 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 187 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 188 | SourceRange.__contains__ = SourceRange__contains__ |
| 189 | |
| 190 | |
| 191 | ################################################################################ |
| 192 | ################################################################################ |
| 193 | ##### ##### |
| 194 | ##### C P P T O K E N I Z E R ##### |
| 195 | ##### ##### |
| 196 | ################################################################################ |
| 197 | ################################################################################ |
| 198 | |
| 199 | |
| 200 | class CppTokenizer(object): |
| 201 | """A tokenizer that converts some input text into a list of tokens. |
| 202 | |
| 203 | It calls libclang's tokenizer to get the parsed tokens. In addition, it |
| 204 | updates the cursor property in each token after parsing, by calling |
| 205 | getTokensWithCursors(). |
| 206 | """ |
| 207 | |
| 208 | clang_flags = ['-E', '-x', 'c'] |
| 209 | options = TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 210 | |
| 211 | def __init__(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 212 | """Initialize a new CppTokenizer object.""" |
| 213 | self._indexer = clang.cindex.Index.create() |
| 214 | self._tu = None |
| 215 | self._index = 0 |
| 216 | self.tokens = None |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 217 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 218 | def _getTokensWithCursors(self): |
| 219 | """Helper method to return all tokens with their cursors. |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 220 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 221 | The cursor property in a clang Token doesn't provide enough |
| 222 | information. Because it is queried based on single token each time |
| 223 | without any context, i.e. via calling conf.lib.clang_annotateTokens() |
| 224 | with only one token given. So we often see 'INVALID_FILE' in one |
| 225 | token's cursor. In this function it passes all the available tokens |
| 226 | to get more informative cursors. |
| 227 | """ |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 228 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 229 | tokens_memory = ctypes.POINTER(clang.cindex.Token)() |
| 230 | tokens_count = ctypes.c_uint() |
| 231 | |
| 232 | conf.lib.clang_tokenize(self._tu, self._tu.cursor.extent, |
| 233 | ctypes.byref(tokens_memory), |
| 234 | ctypes.byref(tokens_count)) |
| 235 | |
| 236 | count = int(tokens_count.value) |
| 237 | |
| 238 | # If we get no tokens, no memory was allocated. Be sure not to return |
| 239 | # anything and potentially call a destructor on nothing. |
| 240 | if count < 1: |
| 241 | return |
| 242 | |
| 243 | cursors = (Cursor * count)() |
| 244 | cursors_memory = ctypes.cast(cursors, ctypes.POINTER(Cursor)) |
| 245 | |
| 246 | conf.lib.clang_annotateTokens(self._tu, tokens_memory, count, |
| 247 | cursors_memory) |
| 248 | |
| 249 | tokens_array = ctypes.cast( |
| 250 | tokens_memory, |
| 251 | ctypes.POINTER(clang.cindex.Token * count)).contents |
| 252 | token_group = TokenGroup(self._tu, tokens_memory, tokens_count) |
| 253 | |
| 254 | tokens = [] |
| 255 | for i in xrange(0, count): |
| 256 | token = Token(self._tu, token_group, |
| 257 | int_data=tokens_array[i].int_data, |
| 258 | ptr_data=tokens_array[i].ptr_data, |
| 259 | cursor=cursors[i]) |
| 260 | # We only want non-comment tokens. |
| 261 | if token.kind != TokenKind.COMMENT: |
| 262 | tokens.append(token) |
| 263 | |
| 264 | return tokens |
| 265 | |
| 266 | def parseString(self, lines): |
| 267 | """Parse a list of text lines into a BlockList object.""" |
| 268 | file_ = 'dummy.c' |
| 269 | self._tu = self._indexer.parse(file_, self.clang_flags, |
| 270 | unsaved_files=[(file_, lines)], |
| 271 | options=self.options) |
| 272 | self.tokens = self._getTokensWithCursors() |
| 273 | |
| 274 | def parseFile(self, file_): |
| 275 | """Parse a file into a BlockList object.""" |
| 276 | self._tu = self._indexer.parse(file_, self.clang_flags, |
| 277 | options=self.options) |
| 278 | self.tokens = self._getTokensWithCursors() |
| 279 | |
| 280 | def nextToken(self): |
| 281 | """Return next token from the list.""" |
| 282 | if self._index < len(self.tokens): |
| 283 | t = self.tokens[self._index] |
| 284 | self._index += 1 |
| 285 | return t |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 286 | else: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 287 | return None |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 288 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 289 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 290 | class CppStringTokenizer(CppTokenizer): |
| 291 | """A CppTokenizer derived class that accepts a string of text as input.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 292 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 293 | def __init__(self, line): |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 294 | CppTokenizer.__init__(self) |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 295 | self.parseString(line) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 296 | |
| 297 | |
| 298 | class CppFileTokenizer(CppTokenizer): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 299 | """A CppTokenizer derived class that accepts a file as input.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 300 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 301 | def __init__(self, file_): |
| 302 | CppTokenizer.__init__(self) |
| 303 | self.parseFile(file_) |
| 304 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 305 | |
| 306 | # Unit testing |
| 307 | # |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 308 | class CppTokenizerTester(object): |
| 309 | """A class used to test CppTokenizer classes.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 310 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 311 | def __init__(self, tokenizer=None): |
| 312 | self._tokenizer = tokenizer |
| 313 | self._token = None |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 314 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 315 | def setTokenizer(self, tokenizer): |
| 316 | self._tokenizer = tokenizer |
| 317 | |
| 318 | def expect(self, id): |
| 319 | self._token = self._tokenizer.nextToken() |
| 320 | if self._token is None: |
| 321 | tokid = '' |
| 322 | else: |
| 323 | tokid = self._token.id |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 324 | if tokid == id: |
| 325 | return |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 326 | raise BadExpectedToken("### BAD TOKEN: '%s' expecting '%s'" % ( |
| 327 | tokid, id)) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 328 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 329 | def expectToken(self, id, line, col): |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 330 | self.expect(id) |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 331 | if self._token.location.line != line: |
| 332 | raise BadExpectedToken( |
| 333 | "### BAD LINENO: token '%s' got '%d' expecting '%d'" % ( |
| 334 | id, self._token.lineno, line)) |
| 335 | if self._token.location.column != col: |
| 336 | raise BadExpectedToken("### BAD COLNO: '%d' expecting '%d'" % ( |
| 337 | self._token.colno, col)) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 338 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 339 | def expectTokens(self, tokens): |
| 340 | for id, line, col in tokens: |
| 341 | self.expectToken(id, line, col) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 342 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 343 | def expectList(self, list_): |
| 344 | for item in list_: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 345 | self.expect(item) |
| 346 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 347 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 348 | def test_CppTokenizer(): |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 349 | tester = CppTokenizerTester() |
| 350 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 351 | tester.setTokenizer(CppStringTokenizer("#an/example && (01923_xy)")) |
| 352 | tester.expectList(["#", "an", "/", "example", tokLOGICAND, tokLPAREN, |
| 353 | "01923_xy", tokRPAREN]) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 354 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 355 | tester.setTokenizer(CppStringTokenizer("FOO(BAR) && defined(BAZ)")) |
| 356 | tester.expectList(["FOO", tokLPAREN, "BAR", tokRPAREN, tokLOGICAND, |
| 357 | "defined", tokLPAREN, "BAZ", tokRPAREN]) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 358 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 359 | tester.setTokenizer(CppStringTokenizer("/*\n#\n*/")) |
| 360 | tester.expectList([]) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 361 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 362 | tester.setTokenizer(CppStringTokenizer("first\nsecond")) |
| 363 | tester.expectList(["first", "second"]) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 364 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 365 | tester.setTokenizer(CppStringTokenizer("first second\n third")) |
| 366 | tester.expectTokens([("first", 1, 1), |
| 367 | ("second", 1, 7), |
| 368 | ("third", 2, 3)]) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 369 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 370 | tester.setTokenizer(CppStringTokenizer("boo /* what the\nhell */")) |
| 371 | tester.expectTokens([("boo", 1, 1)]) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 372 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 373 | tester.setTokenizer(CppStringTokenizer("an \\\n example")) |
| 374 | tester.expectTokens([("an", 1, 1), |
| 375 | ("example", 2, 2)]) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 376 | return True |
| 377 | |
| 378 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 379 | ################################################################################ |
| 380 | ################################################################################ |
| 381 | ##### ##### |
| 382 | ##### C P P E X P R E S S I O N S ##### |
| 383 | ##### ##### |
| 384 | ################################################################################ |
| 385 | ################################################################################ |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 386 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 387 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 388 | class CppExpr(object): |
| 389 | """A class that models the condition of #if directives into an expr tree. |
| 390 | |
| 391 | Each node in the tree is of the form (op, arg) or (op, arg1, arg2) where |
| 392 | "op" is a string describing the operation |
| 393 | """ |
| 394 | |
| 395 | unaries = ["!", "~"] |
| 396 | binaries = ["+", "-", "<", "<=", ">=", ">", "&&", "||", "*", "/", "%", |
| 397 | "&", "|", "^", "<<", ">>", "==", "!=", "?", ":"] |
Elliott Hughes | 1198fd3 | 2013-11-21 11:12:34 -0800 | [diff] [blame] | 398 | precedences = { |
| 399 | "?": 1, ":": 1, |
| 400 | "||": 2, |
| 401 | "&&": 3, |
| 402 | "|": 4, |
| 403 | "^": 5, |
| 404 | "&": 6, |
| 405 | "==": 7, "!=": 7, |
| 406 | "<": 8, "<=": 8, ">": 8, ">=": 8, |
| 407 | "<<": 9, ">>": 9, |
| 408 | "+": 10, "-": 10, |
| 409 | "*": 11, "/": 11, "%": 11, |
| 410 | "!": 12, "~": 12 |
| 411 | } |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 412 | |
| 413 | def __init__(self, tokens): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 414 | """Initialize a CppExpr. 'tokens' must be a CppToken list.""" |
| 415 | self.tokens = tokens |
| 416 | self._num_tokens = len(tokens) |
| 417 | self._index = 0 |
| 418 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 419 | if debugCppExpr: |
| 420 | print "CppExpr: trying to parse %s" % repr(tokens) |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 421 | self.expr = self.parseExpression(0) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 422 | if debugCppExpr: |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 423 | print "CppExpr: got " + repr(self.expr) |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 424 | if self._index != self._num_tokens: |
| 425 | self.throw(BadExpectedToken, "crap at end of input (%d != %d): %s" |
| 426 | % (self._index, self._num_tokens, repr(tokens))) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 427 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 428 | def throw(self, exception, msg): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 429 | if self._index < self._num_tokens: |
| 430 | tok = self.tokens[self._index] |
| 431 | print "%d:%d: %s" % (tok.location.line, tok.location.column, msg) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 432 | else: |
| 433 | print "EOF: %s" % msg |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 434 | raise exception(msg) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 435 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 436 | def expectId(self, id): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 437 | """Check that a given token id is at the current position.""" |
| 438 | token = self.tokens[self._index] |
| 439 | if self._index >= self._num_tokens or token.id != id: |
| 440 | self.throw(BadExpectedToken, |
| 441 | "### expecting '%s' in expression, got '%s'" % ( |
| 442 | id, token.id)) |
| 443 | self._index += 1 |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 444 | |
| 445 | def is_decimal(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 446 | token = self.tokens[self._index].id |
| 447 | if token[-1] in "ULul": |
| 448 | token = token[:-1] |
| 449 | try: |
| 450 | val = int(token, 10) |
| 451 | self._index += 1 |
| 452 | return ('int', val) |
| 453 | except ValueError: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 454 | return None |
| 455 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 456 | def is_octal(self): |
| 457 | token = self.tokens[self._index].id |
| 458 | if token[-1] in "ULul": |
| 459 | token = token[:-1] |
| 460 | if len(token) < 2 or token[0] != '0': |
| 461 | return None |
| 462 | try: |
| 463 | val = int(token, 8) |
| 464 | self._index += 1 |
| 465 | return ('oct', val) |
| 466 | except ValueError: |
| 467 | return None |
| 468 | |
| 469 | def is_hexadecimal(self): |
| 470 | token = self.tokens[self._index].id |
| 471 | if token[-1] in "ULul": |
| 472 | token = token[:-1] |
| 473 | if len(token) < 3 or (token[:2] != '0x' and token[:2] != '0X'): |
| 474 | return None |
| 475 | try: |
| 476 | val = int(token, 16) |
| 477 | self._index += 1 |
| 478 | return ('hex', val) |
| 479 | except ValueError: |
| 480 | return None |
| 481 | |
| 482 | def is_integer(self): |
| 483 | if self.tokens[self._index].kind != TokenKind.LITERAL: |
| 484 | return None |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 485 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 486 | c = self.is_hexadecimal() |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 487 | if c: |
| 488 | return c |
| 489 | |
| 490 | c = self.is_octal() |
| 491 | if c: |
| 492 | return c |
| 493 | |
| 494 | c = self.is_decimal() |
| 495 | if c: |
| 496 | return c |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 497 | |
| 498 | return None |
| 499 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 500 | def is_number(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 501 | t = self.tokens[self._index] |
| 502 | if t.id == tokMINUS and self._index + 1 < self._num_tokens: |
| 503 | self._index += 1 |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 504 | c = self.is_integer() |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 505 | if c: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 506 | op, val = c |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 507 | return (op, -val) |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 508 | if t.id == tokPLUS and self._index + 1 < self._num_tokens: |
| 509 | self._index += 1 |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 510 | c = self.is_integer() |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 511 | if c: |
| 512 | return c |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 513 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 514 | return self.is_integer() |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 515 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 516 | def is_defined(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 517 | t = self.tokens[self._index] |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 518 | if t.id != tokDEFINED: |
| 519 | return None |
| 520 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 521 | # We have the defined keyword, check the rest. |
| 522 | self._index += 1 |
| 523 | used_parens = False |
| 524 | if (self._index < self._num_tokens and |
| 525 | self.tokens[self._index].id == tokLPAREN): |
| 526 | used_parens = True |
| 527 | self._index += 1 |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 528 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 529 | if self._index >= self._num_tokens: |
| 530 | self.throw(BadExpectedToken, |
| 531 | "### 'defined' must be followed by macro name or left " |
| 532 | "paren") |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 533 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 534 | t = self.tokens[self._index] |
| 535 | if t.kind != TokenKind.IDENTIFIER: |
| 536 | self.throw(BadExpectedToken, |
| 537 | "### 'defined' must be followed by macro name") |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 538 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 539 | self._index += 1 |
Elliott Hughes | fddbafd | 2014-05-01 10:17:27 -0700 | [diff] [blame] | 540 | if used_parens: |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 541 | self.expectId(tokRPAREN) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 542 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 543 | return ("defined", t.id) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 544 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 545 | def is_call_or_ident(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 546 | if self._index >= self._num_tokens: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 547 | return None |
| 548 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 549 | t = self.tokens[self._index] |
| 550 | if t.kind != TokenKind.IDENTIFIER: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 551 | return None |
| 552 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 553 | name = t.id |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 554 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 555 | self._index += 1 |
| 556 | if (self._index >= self._num_tokens or |
| 557 | self.tokens[self._index].id != tokLPAREN): |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 558 | return ("ident", name) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 559 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 560 | params = [] |
| 561 | depth = 1 |
| 562 | self._index += 1 |
| 563 | j = self._index |
| 564 | while self._index < self._num_tokens: |
| 565 | id = self.tokens[self._index].id |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 566 | if id == tokLPAREN: |
| 567 | depth += 1 |
| 568 | elif depth == 1 and (id == tokCOMMA or id == tokRPAREN): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 569 | k = self._index |
| 570 | param = self.tokens[j:k] |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 571 | params.append(param) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 572 | if id == tokRPAREN: |
| 573 | break |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 574 | j = self._index + 1 |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 575 | elif id == tokRPAREN: |
| 576 | depth -= 1 |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 577 | self._index += 1 |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 578 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 579 | if self._index >= self._num_tokens: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 580 | return None |
| 581 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 582 | self._index += 1 |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 583 | return ("call", (name, params)) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 584 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 585 | # Implements the "precedence climbing" algorithm from |
| 586 | # http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm. |
| 587 | # The "classic" algorithm would be fine if we were using a tool to |
| 588 | # generate the parser, but we're not. Dijkstra's "shunting yard" |
| 589 | # algorithm hasn't been necessary yet. |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 590 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 591 | def parseExpression(self, minPrecedence): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 592 | if self._index >= self._num_tokens: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 593 | return None |
| 594 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 595 | node = self.parsePrimary() |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 596 | while (self.token() and self.isBinary(self.token()) and |
| 597 | self.precedence(self.token()) >= minPrecedence): |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 598 | op = self.token() |
| 599 | self.nextToken() |
| 600 | rhs = self.parseExpression(self.precedence(op) + 1) |
| 601 | node = (op.id, node, rhs) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 602 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 603 | return node |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 604 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 605 | def parsePrimary(self): |
| 606 | op = self.token() |
| 607 | if self.isUnary(op): |
| 608 | self.nextToken() |
| 609 | return (op.id, self.parseExpression(self.precedence(op))) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 610 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 611 | primary = None |
| 612 | if op.id == tokLPAREN: |
| 613 | self.nextToken() |
| 614 | primary = self.parseExpression(0) |
| 615 | self.expectId(tokRPAREN) |
Elliott Hughes | 1198fd3 | 2013-11-21 11:12:34 -0800 | [diff] [blame] | 616 | elif op.id == "?": |
| 617 | self.nextToken() |
| 618 | primary = self.parseExpression(0) |
| 619 | self.expectId(":") |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 620 | elif op.id == '+' or op.id == '-' or op.kind == TokenKind.LITERAL: |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 621 | primary = self.is_number() |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 622 | # Checking for 'defined' needs to come first now because 'defined' is |
| 623 | # recognized as IDENTIFIER. |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 624 | elif op.id == tokDEFINED: |
| 625 | primary = self.is_defined() |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 626 | elif op.kind == TokenKind.IDENTIFIER: |
| 627 | primary = self.is_call_or_ident() |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 628 | else: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 629 | self.throw(BadExpectedToken, |
| 630 | "didn't expect to see a %s in factor" % ( |
| 631 | self.tokens[self._index].id)) |
| 632 | return primary |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 633 | |
| 634 | def isBinary(self, token): |
| 635 | return token.id in self.binaries |
| 636 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 637 | def isUnary(self, token): |
| 638 | return token.id in self.unaries |
| 639 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 640 | def precedence(self, token): |
| 641 | return self.precedences.get(token.id) |
| 642 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 643 | def token(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 644 | if self._index >= self._num_tokens: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 645 | return None |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 646 | return self.tokens[self._index] |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 647 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 648 | def nextToken(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 649 | self._index += 1 |
| 650 | if self._index >= self._num_tokens: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 651 | return None |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 652 | return self.tokens[self._index] |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 653 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 654 | def dump_node(self, e): |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 655 | op = e[0] |
| 656 | line = "(" + op |
| 657 | if op == "int": |
| 658 | line += " %d)" % e[1] |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 659 | elif op == "oct": |
| 660 | line += " 0%o)" % e[1] |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 661 | elif op == "hex": |
| 662 | line += " 0x%x)" % e[1] |
| 663 | elif op == "ident": |
| 664 | line += " %s)" % e[1] |
| 665 | elif op == "defined": |
| 666 | line += " %s)" % e[1] |
| 667 | elif op == "call": |
| 668 | arg = e[1] |
| 669 | line += " %s [" % arg[0] |
| 670 | prefix = "" |
| 671 | for param in arg[1]: |
| 672 | par = "" |
| 673 | for tok in param: |
| 674 | par += str(tok) |
| 675 | line += "%s%s" % (prefix, par) |
| 676 | prefix = "," |
| 677 | line += "])" |
| 678 | elif op in CppExpr.unaries: |
| 679 | line += " %s)" % self.dump_node(e[1]) |
| 680 | elif op in CppExpr.binaries: |
| 681 | line += " %s %s)" % (self.dump_node(e[1]), self.dump_node(e[2])) |
| 682 | else: |
| 683 | line += " ?%s)" % repr(e[1]) |
| 684 | |
| 685 | return line |
| 686 | |
| 687 | def __repr__(self): |
| 688 | return self.dump_node(self.expr) |
| 689 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 690 | def source_node(self, e): |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 691 | op = e[0] |
| 692 | if op == "int": |
| 693 | return "%d" % e[1] |
| 694 | if op == "hex": |
| 695 | return "0x%x" % e[1] |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 696 | if op == "oct": |
| 697 | return "0%o" % e[1] |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 698 | if op == "ident": |
| 699 | # XXX: should try to expand |
| 700 | return e[1] |
| 701 | if op == "defined": |
| 702 | return "defined(%s)" % e[1] |
| 703 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 704 | prec = CppExpr.precedences.get(op, 1000) |
| 705 | arg = e[1] |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 706 | if op in CppExpr.unaries: |
| 707 | arg_src = self.source_node(arg) |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 708 | arg_op = arg[0] |
| 709 | arg_prec = CppExpr.precedences.get(arg_op, 1000) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 710 | if arg_prec < prec: |
| 711 | return "!(" + arg_src + ")" |
| 712 | else: |
| 713 | return "!" + arg_src |
| 714 | if op in CppExpr.binaries: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 715 | arg2 = e[2] |
| 716 | arg1_op = arg[0] |
| 717 | arg2_op = arg2[0] |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 718 | arg1_src = self.source_node(arg) |
| 719 | arg2_src = self.source_node(arg2) |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 720 | if CppExpr.precedences.get(arg1_op, 1000) < prec: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 721 | arg1_src = "(%s)" % arg1_src |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 722 | if CppExpr.precedences.get(arg2_op, 1000) < prec: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 723 | arg2_src = "(%s)" % arg2_src |
| 724 | |
| 725 | return "%s %s %s" % (arg1_src, op, arg2_src) |
| 726 | return "???" |
| 727 | |
| 728 | def __str__(self): |
| 729 | return self.source_node(self.expr) |
| 730 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 731 | @staticmethod |
| 732 | def int_node(e): |
| 733 | if e[0] in ["int", "oct", "hex"]: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 734 | return e[1] |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 735 | else: |
| 736 | return None |
| 737 | |
| 738 | def toInt(self): |
| 739 | return self.int_node(self.expr) |
| 740 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 741 | def optimize_node(self, e, macros=None): |
| 742 | if macros is None: |
| 743 | macros = {} |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 744 | op = e[0] |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 745 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 746 | if op == "defined": |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 747 | op, name = e |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 748 | if macros.has_key(name): |
| 749 | if macros[name] == kCppUndefinedMacro: |
| 750 | return ("int", 0) |
| 751 | else: |
Elliott Hughes | d3e64a3 | 2013-09-30 17:41:08 -0700 | [diff] [blame] | 752 | try: |
| 753 | value = int(macros[name]) |
| 754 | return ("int", value) |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 755 | except ValueError: |
Elliott Hughes | d3e64a3 | 2013-09-30 17:41:08 -0700 | [diff] [blame] | 756 | return ("defined", macros[name]) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 757 | |
| 758 | if kernel_remove_config_macros and name.startswith("CONFIG_"): |
| 759 | return ("int", 0) |
| 760 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 761 | return e |
| 762 | |
| 763 | elif op == "ident": |
| 764 | op, name = e |
| 765 | if macros.has_key(name): |
| 766 | try: |
| 767 | value = int(macros[name]) |
| 768 | expanded = ("int", value) |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 769 | except ValueError: |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 770 | expanded = ("ident", macros[name]) |
| 771 | return self.optimize_node(expanded, macros) |
| 772 | return e |
| 773 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 774 | elif op == "!": |
| 775 | op, v = e |
| 776 | v = self.optimize_node(v, macros) |
| 777 | if v[0] == "int": |
| 778 | if v[1] == 0: |
| 779 | return ("int", 1) |
| 780 | else: |
| 781 | return ("int", 0) |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 782 | return ('!', v) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 783 | |
| 784 | elif op == "&&": |
| 785 | op, l, r = e |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 786 | l = self.optimize_node(l, macros) |
| 787 | r = self.optimize_node(r, macros) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 788 | li = self.int_node(l) |
| 789 | ri = self.int_node(r) |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 790 | if li is not None: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 791 | if li == 0: |
| 792 | return ("int", 0) |
| 793 | else: |
| 794 | return r |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 795 | elif ri is not None: |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 796 | if ri == 0: |
| 797 | return ("int", 0) |
| 798 | else: |
| 799 | return l |
| 800 | return (op, l, r) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 801 | |
| 802 | elif op == "||": |
| 803 | op, l, r = e |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 804 | l = self.optimize_node(l, macros) |
| 805 | r = self.optimize_node(r, macros) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 806 | li = self.int_node(l) |
| 807 | ri = self.int_node(r) |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 808 | if li is not None: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 809 | if li == 0: |
| 810 | return r |
| 811 | else: |
| 812 | return ("int", 1) |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 813 | elif ri is not None: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 814 | if ri == 0: |
| 815 | return l |
| 816 | else: |
| 817 | return ("int", 1) |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 818 | return (op, l, r) |
| 819 | |
| 820 | else: |
| 821 | return e |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 822 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 823 | def optimize(self, macros=None): |
| 824 | if macros is None: |
| 825 | macros = {} |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 826 | self.expr = self.optimize_node(self.expr, macros) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 827 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 828 | |
| 829 | def test_cpp_expr(expr, expected): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 830 | e = CppExpr(CppStringTokenizer(expr).tokens) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 831 | s1 = repr(e) |
| 832 | if s1 != expected: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 833 | print ("[FAIL]: expression '%s' generates '%s', should be " |
| 834 | "'%s'" % (expr, s1, expected)) |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 835 | global failure_count |
| 836 | failure_count += 1 |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 837 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 838 | |
| 839 | def test_cpp_expr_optim(expr, expected, macros=None): |
| 840 | if macros is None: |
| 841 | macros = {} |
| 842 | e = CppExpr(CppStringTokenizer(expr).tokens) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 843 | e.optimize(macros) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 844 | s1 = repr(e) |
| 845 | if s1 != expected: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 846 | print ("[FAIL]: optimized expression '%s' generates '%s' with " |
| 847 | "macros %s, should be '%s'" % (expr, s1, macros, expected)) |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 848 | global failure_count |
| 849 | failure_count += 1 |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 850 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 851 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 852 | def test_cpp_expr_source(expr, expected): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 853 | e = CppExpr(CppStringTokenizer(expr).tokens) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 854 | s1 = str(e) |
| 855 | if s1 != expected: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 856 | print ("[FAIL]: source expression '%s' generates '%s', should " |
| 857 | "be '%s'" % (expr, s1, expected)) |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 858 | global failure_count |
| 859 | failure_count += 1 |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 860 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 861 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 862 | def test_CppExpr(): |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 863 | test_cpp_expr("0", "(int 0)") |
| 864 | test_cpp_expr("1", "(int 1)") |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 865 | test_cpp_expr("-5", "(int -5)") |
| 866 | test_cpp_expr("+1", "(int 1)") |
| 867 | test_cpp_expr("0U", "(int 0)") |
| 868 | test_cpp_expr("015", "(oct 015)") |
| 869 | test_cpp_expr("015l", "(oct 015)") |
| 870 | test_cpp_expr("0x3e", "(hex 0x3e)") |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 871 | test_cpp_expr("(0)", "(int 0)") |
| 872 | test_cpp_expr("1 && 1", "(&& (int 1) (int 1))") |
| 873 | test_cpp_expr("1 && 0", "(&& (int 1) (int 0))") |
| 874 | test_cpp_expr("EXAMPLE", "(ident EXAMPLE)") |
| 875 | test_cpp_expr("EXAMPLE - 3", "(- (ident EXAMPLE) (int 3))") |
| 876 | test_cpp_expr("defined(EXAMPLE)", "(defined EXAMPLE)") |
| 877 | test_cpp_expr("defined ( EXAMPLE ) ", "(defined EXAMPLE)") |
| 878 | test_cpp_expr("!defined(EXAMPLE)", "(! (defined EXAMPLE))") |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 879 | test_cpp_expr("defined(ABC) || defined(BINGO)", |
| 880 | "(|| (defined ABC) (defined BINGO))") |
| 881 | test_cpp_expr("FOO(BAR,5)", "(call FOO [BAR,5])") |
| 882 | test_cpp_expr("A == 1 || defined(B)", |
| 883 | "(|| (== (ident A) (int 1)) (defined B))") |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 884 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 885 | test_cpp_expr_optim("0", "(int 0)") |
| 886 | test_cpp_expr_optim("1", "(int 1)") |
| 887 | test_cpp_expr_optim("1 && 1", "(int 1)") |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 888 | test_cpp_expr_optim("1 && +1", "(int 1)") |
| 889 | test_cpp_expr_optim("0x1 && 01", "(oct 01)") |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 890 | test_cpp_expr_optim("1 && 0", "(int 0)") |
| 891 | test_cpp_expr_optim("0 && 1", "(int 0)") |
| 892 | test_cpp_expr_optim("0 && 0", "(int 0)") |
| 893 | test_cpp_expr_optim("1 || 1", "(int 1)") |
| 894 | test_cpp_expr_optim("1 || 0", "(int 1)") |
| 895 | test_cpp_expr_optim("0 || 1", "(int 1)") |
| 896 | test_cpp_expr_optim("0 || 0", "(int 0)") |
| 897 | test_cpp_expr_optim("A", "(ident A)") |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 898 | test_cpp_expr_optim("A", "(int 1)", {"A": 1}) |
| 899 | test_cpp_expr_optim("A || B", "(int 1)", {"A": 1}) |
| 900 | test_cpp_expr_optim("A || B", "(int 1)", {"B": 1}) |
| 901 | test_cpp_expr_optim("A && B", "(ident B)", {"A": 1}) |
| 902 | test_cpp_expr_optim("A && B", "(ident A)", {"B": 1}) |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 903 | test_cpp_expr_optim("A && B", "(&& (ident A) (ident B))") |
| 904 | test_cpp_expr_optim("EXAMPLE", "(ident EXAMPLE)") |
| 905 | test_cpp_expr_optim("EXAMPLE - 3", "(- (ident EXAMPLE) (int 3))") |
| 906 | test_cpp_expr_optim("defined(EXAMPLE)", "(defined EXAMPLE)") |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 907 | test_cpp_expr_optim("defined(EXAMPLE)", "(defined XOWOE)", |
| 908 | {"EXAMPLE": "XOWOE"}) |
| 909 | test_cpp_expr_optim("defined(EXAMPLE)", "(int 0)", |
| 910 | {"EXAMPLE": kCppUndefinedMacro}) |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 911 | test_cpp_expr_optim("!defined(EXAMPLE)", "(! (defined EXAMPLE))") |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 912 | test_cpp_expr_optim("!defined(EXAMPLE)", "(! (defined XOWOE))", |
| 913 | {"EXAMPLE": "XOWOE"}) |
| 914 | test_cpp_expr_optim("!defined(EXAMPLE)", "(int 1)", |
| 915 | {"EXAMPLE": kCppUndefinedMacro}) |
| 916 | test_cpp_expr_optim("defined(A) || defined(B)", |
| 917 | "(|| (defined A) (defined B))") |
| 918 | test_cpp_expr_optim("defined(A) || defined(B)", "(int 1)", {"A": "1"}) |
| 919 | test_cpp_expr_optim("defined(A) || defined(B)", "(int 1)", {"B": "1"}) |
| 920 | test_cpp_expr_optim("defined(A) || defined(B)", "(defined A)", |
| 921 | {"B": kCppUndefinedMacro}) |
| 922 | test_cpp_expr_optim("defined(A) || defined(B)", "(int 0)", |
| 923 | {"A": kCppUndefinedMacro, "B": kCppUndefinedMacro}) |
| 924 | test_cpp_expr_optim("defined(A) && defined(B)", |
| 925 | "(&& (defined A) (defined B))") |
| 926 | test_cpp_expr_optim("defined(A) && defined(B)", |
| 927 | "(defined B)", {"A": "1"}) |
| 928 | test_cpp_expr_optim("defined(A) && defined(B)", |
| 929 | "(defined A)", {"B": "1"}) |
| 930 | test_cpp_expr_optim("defined(A) && defined(B)", "(int 0)", |
| 931 | {"B": kCppUndefinedMacro}) |
| 932 | test_cpp_expr_optim("defined(A) && defined(B)", |
| 933 | "(int 0)", {"A": kCppUndefinedMacro}) |
| 934 | test_cpp_expr_optim("A == 1 || defined(B)", |
| 935 | "(|| (== (ident A) (int 1)) (defined B))") |
| 936 | test_cpp_expr_optim( |
| 937 | "defined(__KERNEL__) || !defined(__GLIBC__) || (__GLIBC__ < 2)", |
| 938 | "(|| (! (defined __GLIBC__)) (< (ident __GLIBC__) (int 2)))", |
| 939 | {"__KERNEL__": kCppUndefinedMacro}) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 940 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 941 | test_cpp_expr_source("0", "0") |
| 942 | test_cpp_expr_source("1", "1") |
| 943 | test_cpp_expr_source("1 && 1", "1 && 1") |
| 944 | test_cpp_expr_source("1 && 0", "1 && 0") |
| 945 | test_cpp_expr_source("0 && 1", "0 && 1") |
| 946 | test_cpp_expr_source("0 && 0", "0 && 0") |
| 947 | test_cpp_expr_source("1 || 1", "1 || 1") |
| 948 | test_cpp_expr_source("1 || 0", "1 || 0") |
| 949 | test_cpp_expr_source("0 || 1", "0 || 1") |
| 950 | test_cpp_expr_source("0 || 0", "0 || 0") |
| 951 | test_cpp_expr_source("EXAMPLE", "EXAMPLE") |
| 952 | test_cpp_expr_source("EXAMPLE - 3", "EXAMPLE - 3") |
| 953 | test_cpp_expr_source("defined(EXAMPLE)", "defined(EXAMPLE)") |
| 954 | test_cpp_expr_source("defined EXAMPLE", "defined(EXAMPLE)") |
| 955 | test_cpp_expr_source("A == 1 || defined(B)", "A == 1 || defined(B)") |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 956 | |
| 957 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 958 | ################################################################################ |
| 959 | ################################################################################ |
| 960 | ##### ##### |
| 961 | ##### C P P B L O C K ##### |
| 962 | ##### ##### |
| 963 | ################################################################################ |
| 964 | ################################################################################ |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 965 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 966 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 967 | class Block(object): |
| 968 | """A class used to model a block of input source text. |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 969 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 970 | There are two block types: |
| 971 | - directive blocks: contain the tokens of a single pre-processor |
| 972 | directive (e.g. #if) |
| 973 | - text blocks, contain the tokens of non-directive blocks |
| 974 | |
| 975 | The cpp parser class below will transform an input source file into a list |
| 976 | of Block objects (grouped in a BlockList object for convenience) |
| 977 | """ |
| 978 | |
| 979 | def __init__(self, tokens, directive=None, lineno=0, identifier=None): |
| 980 | """Initialize a new block, if 'directive' is None, it is a text block. |
| 981 | |
| 982 | NOTE: This automatically converts '#ifdef MACRO' into |
| 983 | '#if defined(MACRO)' and '#ifndef MACRO' into '#if !defined(MACRO)'. |
| 984 | """ |
| 985 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 986 | if directive == "ifdef": |
| 987 | tok = Token() |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 988 | tok.id = tokDEFINED |
| 989 | tokens = [tok] + tokens |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 990 | directive = "if" |
| 991 | |
| 992 | elif directive == "ifndef": |
| 993 | tok1 = Token() |
| 994 | tok2 = Token() |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 995 | tok1.id = tokNOT |
| 996 | tok2.id = tokDEFINED |
| 997 | tokens = [tok1, tok2] + tokens |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 998 | directive = "if" |
| 999 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1000 | self.tokens = tokens |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1001 | self.directive = directive |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1002 | self.define_id = identifier |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1003 | if lineno > 0: |
| 1004 | self.lineno = lineno |
| 1005 | else: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1006 | self.lineno = self.tokens[0].location.line |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1007 | |
| 1008 | if self.isIf(): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1009 | self.expr = CppExpr(self.tokens) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1010 | |
| 1011 | def isDirective(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1012 | """Return True iff this is a directive block.""" |
| 1013 | return self.directive is not None |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1014 | |
| 1015 | def isConditional(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1016 | """Return True iff this is a conditional directive block.""" |
| 1017 | return self.directive in ["if", "ifdef", "ifndef", "else", "elif", |
| 1018 | "endif"] |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1019 | |
| 1020 | def isDefine(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1021 | """Return the macro name in a #define directive, or None otherwise.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1022 | if self.directive != "define": |
| 1023 | return None |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1024 | return self.define_id |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1025 | |
| 1026 | def isIf(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1027 | """Return True iff this is an #if-like directive block.""" |
| 1028 | return self.directive in ["if", "ifdef", "ifndef", "elif"] |
| 1029 | |
| 1030 | def isEndif(self): |
| 1031 | """Return True iff this is an #endif directive block.""" |
| 1032 | return self.directive == "endif" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1033 | |
| 1034 | def isInclude(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1035 | """Check whether this is a #include directive. |
| 1036 | |
| 1037 | If true, returns the corresponding file name (with brackets or |
| 1038 | double-qoutes). None otherwise. |
| 1039 | """ |
| 1040 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1041 | if self.directive != "include": |
| 1042 | return None |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1043 | return ''.join([str(x) for x in self.tokens]) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1044 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1045 | @staticmethod |
| 1046 | def format_blocks(tokens, indent=0): |
| 1047 | """Return the formatted lines of strings with proper indentation.""" |
| 1048 | newline = True |
| 1049 | result = [] |
| 1050 | buf = '' |
| 1051 | i = 0 |
| 1052 | while i < len(tokens): |
| 1053 | t = tokens[i] |
| 1054 | if t.id == '{': |
| 1055 | buf += ' {' |
| 1056 | result.append(strip_space(buf)) |
| 1057 | indent += 2 |
| 1058 | buf = '' |
| 1059 | newline = True |
| 1060 | elif t.id == '}': |
| 1061 | indent -= 2 |
| 1062 | if not newline: |
| 1063 | result.append(strip_space(buf)) |
| 1064 | # Look ahead to determine if it's the end of line. |
| 1065 | if (i + 1 < len(tokens) and |
| 1066 | (tokens[i+1].id == ';' or |
| 1067 | tokens[i+1].id in ['else', '__attribute__', |
| 1068 | '__attribute', '__packed'] or |
| 1069 | tokens[i+1].kind == TokenKind.IDENTIFIER)): |
| 1070 | buf = ' ' * indent + '}' |
| 1071 | newline = False |
| 1072 | else: |
| 1073 | result.append(' ' * indent + '}') |
| 1074 | buf = '' |
| 1075 | newline = True |
| 1076 | elif t.id == ';': |
| 1077 | result.append(strip_space(buf) + ';') |
| 1078 | buf = '' |
| 1079 | newline = True |
| 1080 | # We prefer a new line for each constant in enum. |
| 1081 | elif t.id == ',' and t.cursor.kind == CursorKind.ENUM_DECL: |
| 1082 | result.append(strip_space(buf) + ',') |
| 1083 | buf = '' |
| 1084 | newline = True |
| 1085 | else: |
| 1086 | if newline: |
| 1087 | buf += ' ' * indent + str(t) |
| 1088 | else: |
| 1089 | buf += ' ' + str(t) |
| 1090 | newline = False |
| 1091 | i += 1 |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1092 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1093 | if buf: |
| 1094 | result.append(strip_space(buf)) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1095 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1096 | return result, indent |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1097 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1098 | def writeWithWarning(self, out, warning, left_count, repeat_count, indent): |
| 1099 | """Dump the current block with warnings.""" |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1100 | # removeWhiteSpace() will sometimes creates non-directive blocks |
| 1101 | # without any tokens. These come from blocks that only contained |
| 1102 | # empty lines and spaces. They should not be printed in the final |
| 1103 | # output, and then should not be counted for this operation. |
| 1104 | # |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1105 | if self.directive is None and not self.tokens: |
| 1106 | return left_count, indent |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1107 | |
| 1108 | if self.directive: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1109 | out.write(str(self) + '\n') |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1110 | left_count -= 1 |
| 1111 | if left_count == 0: |
| 1112 | out.write(warning) |
| 1113 | left_count = repeat_count |
| 1114 | |
| 1115 | else: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1116 | lines, indent = self.format_blocks(self.tokens, indent) |
| 1117 | for line in lines: |
| 1118 | out.write(line + '\n') |
| 1119 | left_count -= 1 |
| 1120 | if left_count == 0: |
| 1121 | out.write(warning) |
| 1122 | left_count = repeat_count |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1123 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1124 | return left_count, indent |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1125 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1126 | def __repr__(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1127 | """Generate the representation of a given block.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1128 | if self.directive: |
| 1129 | result = "#%s " % self.directive |
| 1130 | if self.isIf(): |
| 1131 | result += repr(self.expr) |
| 1132 | else: |
| 1133 | for tok in self.tokens: |
| 1134 | result += repr(tok) |
| 1135 | else: |
| 1136 | result = "" |
| 1137 | for tok in self.tokens: |
| 1138 | result += repr(tok) |
| 1139 | |
| 1140 | return result |
| 1141 | |
| 1142 | def __str__(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1143 | """Generate the string representation of a given block.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1144 | if self.directive: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1145 | # "#if" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1146 | if self.directive == "if": |
| 1147 | # small optimization to re-generate #ifdef and #ifndef |
| 1148 | e = self.expr.expr |
| 1149 | op = e[0] |
| 1150 | if op == "defined": |
| 1151 | result = "#ifdef %s" % e[1] |
| 1152 | elif op == "!" and e[1][0] == "defined": |
| 1153 | result = "#ifndef %s" % e[1][1] |
| 1154 | else: |
| 1155 | result = "#if " + str(self.expr) |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1156 | |
| 1157 | # "#define" |
| 1158 | elif self.isDefine(): |
| 1159 | result = "#%s %s" % (self.directive, self.define_id) |
| 1160 | if self.tokens: |
| 1161 | result += " " |
| 1162 | expr = strip_space(' '.join([tok.id for tok in self.tokens])) |
| 1163 | # remove the space between name and '(' in function call |
| 1164 | result += re.sub(r'(\w+) \(', r'\1(', expr) |
| 1165 | |
| 1166 | # "#error" |
| 1167 | # Concatenating tokens with a space separator, because they may |
| 1168 | # not be quoted and broken into several tokens |
| 1169 | elif self.directive == "error": |
| 1170 | result = "#error %s" % ' '.join([tok.id for tok in self.tokens]) |
| 1171 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1172 | else: |
| 1173 | result = "#%s" % self.directive |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1174 | if self.tokens: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1175 | result += " " |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1176 | result += ''.join([tok.id for tok in self.tokens]) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1177 | else: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1178 | lines, _ = self.format_blocks(self.tokens) |
| 1179 | result = '\n'.join(lines) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1180 | |
| 1181 | return result |
| 1182 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1183 | |
| 1184 | class BlockList(object): |
| 1185 | """A convenience class used to hold and process a list of blocks. |
| 1186 | |
| 1187 | It calls the cpp parser to get the blocks. |
| 1188 | """ |
| 1189 | |
| 1190 | def __init__(self, blocks): |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1191 | self.blocks = blocks |
| 1192 | |
| 1193 | def __len__(self): |
| 1194 | return len(self.blocks) |
| 1195 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1196 | def __getitem__(self, n): |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1197 | return self.blocks[n] |
| 1198 | |
| 1199 | def __repr__(self): |
| 1200 | return repr(self.blocks) |
| 1201 | |
| 1202 | def __str__(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1203 | result = '\n'.join([str(b) for b in self.blocks]) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1204 | return result |
| 1205 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1206 | def dump(self): |
| 1207 | """Dump all the blocks in current BlockList.""" |
| 1208 | print '##### BEGIN #####' |
| 1209 | for i, b in enumerate(self.blocks): |
| 1210 | print '### BLOCK %d ###' % i |
| 1211 | print b |
| 1212 | print '##### END #####' |
| 1213 | |
| 1214 | def optimizeIf01(self): |
| 1215 | """Remove the code between #if 0 .. #endif in a BlockList.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1216 | self.blocks = optimize_if01(self.blocks) |
| 1217 | |
| 1218 | def optimizeMacros(self, macros): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1219 | """Remove known defined and undefined macros from a BlockList.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1220 | for b in self.blocks: |
| 1221 | if b.isIf(): |
| 1222 | b.expr.optimize(macros) |
| 1223 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1224 | def removeMacroDefines(self, macros): |
| 1225 | """Remove known macro definitions from a BlockList.""" |
| 1226 | self.blocks = remove_macro_defines(self.blocks, macros) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1227 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1228 | def optimizeAll(self, macros): |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1229 | self.optimizeMacros(macros) |
| 1230 | self.optimizeIf01() |
| 1231 | return |
| 1232 | |
| 1233 | def findIncludes(self): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1234 | """Return the list of included files in a BlockList.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1235 | result = [] |
| 1236 | for b in self.blocks: |
| 1237 | i = b.isInclude() |
| 1238 | if i: |
| 1239 | result.append(i) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1240 | return result |
| 1241 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1242 | def write(self, out): |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1243 | out.write(str(self)) |
| 1244 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1245 | def writeWithWarning(self, out, warning, repeat_count): |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1246 | left_count = repeat_count |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1247 | indent = 0 |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1248 | for b in self.blocks: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1249 | left_count, indent = b.writeWithWarning(out, warning, left_count, |
| 1250 | repeat_count, indent) |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1251 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1252 | def removeVarsAndFuncs(self, knownStatics=None): |
| 1253 | """Remove variable and function declarations. |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1254 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1255 | All extern and static declarations corresponding to variable and |
| 1256 | function declarations are removed. We only accept typedefs and |
| 1257 | enum/structs/union declarations. |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1258 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1259 | However, we keep the definitions corresponding to the set of known |
| 1260 | static inline functions in the set 'knownStatics', which is useful |
| 1261 | for optimized byteorder swap functions and stuff like that. |
| 1262 | """ |
| 1263 | |
| 1264 | # NOTE: It's also removing function-like macros, such as __SYSCALL(...) |
| 1265 | # in uapi/asm-generic/unistd.h, or KEY_FIELD(...) in linux/bcache.h. |
| 1266 | # It could be problematic when we have function-like macros but without |
| 1267 | # '}' following them. It will skip all the tokens/blocks until seeing a |
| 1268 | # '}' as the function end. Fortunately we don't have such cases in the |
| 1269 | # current kernel headers. |
| 1270 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1271 | # state = 0 => normal (i.e. LN + spaces) |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1272 | # state = 1 => typedef/struct encountered, ends with ";" |
| 1273 | # state = 2 => var declaration encountered, ends with ";" |
| 1274 | # state = 3 => func declaration encountered, ends with "}" |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1275 | |
| 1276 | if knownStatics is None: |
| 1277 | knownStatics = set() |
| 1278 | state = 0 |
| 1279 | depth = 0 |
| 1280 | blocks2 = [] |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1281 | skipTokens = False |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1282 | for b in self.blocks: |
| 1283 | if b.isDirective(): |
| 1284 | blocks2.append(b) |
| 1285 | else: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1286 | n = len(b.tokens) |
| 1287 | i = 0 |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1288 | if skipTokens: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1289 | first = n |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1290 | else: |
| 1291 | first = 0 |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1292 | while i < n: |
| 1293 | tok = b.tokens[i] |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1294 | tokid = tok.id |
| 1295 | # If we are not looking for the start of a new |
| 1296 | # type/var/func, then skip over tokens until |
| 1297 | # we find our terminator, managing the depth of |
| 1298 | # accolades as we go. |
| 1299 | if state > 0: |
| 1300 | terminator = False |
| 1301 | if tokid == '{': |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1302 | depth += 1 |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1303 | elif tokid == '}': |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1304 | if depth > 0: |
| 1305 | depth -= 1 |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1306 | if (depth == 0) and (state == 3): |
| 1307 | terminator = True |
| 1308 | elif tokid == ';' and depth == 0: |
| 1309 | terminator = True |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1310 | |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1311 | if terminator: |
| 1312 | # we found the terminator |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1313 | state = 0 |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1314 | if skipTokens: |
| 1315 | skipTokens = False |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1316 | first = i + 1 |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1317 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1318 | i += 1 |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1319 | continue |
| 1320 | |
| 1321 | # Is it a new type definition, then start recording it |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1322 | if tok.id in ['struct', 'typedef', 'enum', 'union', |
| 1323 | '__extension__']: |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1324 | state = 1 |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1325 | i += 1 |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1326 | continue |
| 1327 | |
| 1328 | # Is it a variable or function definition. If so, first |
| 1329 | # try to determine which type it is, and also extract |
| 1330 | # its name. |
| 1331 | # |
| 1332 | # We're going to parse the next tokens of the same block |
| 1333 | # until we find a semi-column or a left parenthesis. |
| 1334 | # |
| 1335 | # The semi-column corresponds to a variable definition, |
| 1336 | # the left-parenthesis to a function definition. |
| 1337 | # |
| 1338 | # We also assume that the var/func name is the last |
| 1339 | # identifier before the terminator. |
| 1340 | # |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1341 | j = i + 1 |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1342 | ident = "" |
| 1343 | while j < n: |
| 1344 | tokid = b.tokens[j].id |
| 1345 | if tokid == '(': # a function declaration |
| 1346 | state = 3 |
| 1347 | break |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1348 | elif tokid == ';': # a variable declaration |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1349 | state = 2 |
| 1350 | break |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1351 | if b.tokens[j].kind == TokenKind.IDENTIFIER: |
| 1352 | ident = b.tokens[j].id |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1353 | j += 1 |
| 1354 | |
| 1355 | if j >= n: |
| 1356 | # This can only happen when the declaration |
| 1357 | # does not end on the current block (e.g. with |
| 1358 | # a directive mixed inside it. |
| 1359 | # |
| 1360 | # We will treat it as malformed because |
| 1361 | # it's very hard to recover from this case |
| 1362 | # without making our parser much more |
| 1363 | # complex. |
| 1364 | # |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1365 | logging.debug("### skip unterminated static '%s'", |
| 1366 | ident) |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1367 | break |
| 1368 | |
| 1369 | if ident in knownStatics: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1370 | logging.debug("### keep var/func '%s': %s", ident, |
| 1371 | repr(b.tokens[i:j])) |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1372 | else: |
| 1373 | # We're going to skip the tokens for this declaration |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1374 | logging.debug("### skip var/func '%s': %s", ident, |
| 1375 | repr(b.tokens[i:j])) |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1376 | if i > first: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1377 | blocks2.append(Block(b.tokens[first:i])) |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1378 | skipTokens = True |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1379 | first = n |
David 'Digit' Turner | fc26931 | 2010-10-11 22:11:06 +0200 | [diff] [blame] | 1380 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1381 | i += 1 |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1382 | |
| 1383 | if i > first: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1384 | # print "### final '%s'" % repr(b.tokens[first:i]) |
| 1385 | blocks2.append(Block(b.tokens[first:i])) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1386 | |
| 1387 | self.blocks = blocks2 |
| 1388 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1389 | def replaceTokens(self, replacements): |
| 1390 | """Replace tokens according to the given dict.""" |
Martin Storsjo | d32c805 | 2010-12-08 11:38:14 +0100 | [diff] [blame] | 1391 | for b in self.blocks: |
Elliott Hughes | fddbafd | 2014-05-01 10:17:27 -0700 | [diff] [blame] | 1392 | made_change = False |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1393 | if b.isInclude() is None: |
Martin Storsjo | d32c805 | 2010-12-08 11:38:14 +0100 | [diff] [blame] | 1394 | for tok in b.tokens: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1395 | if tok.kind == TokenKind.IDENTIFIER: |
| 1396 | if tok.id in replacements: |
| 1397 | tok.id = replacements[tok.id] |
Elliott Hughes | fddbafd | 2014-05-01 10:17:27 -0700 | [diff] [blame] | 1398 | made_change = True |
| 1399 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1400 | if b.isDefine() and b.define_id in replacements: |
| 1401 | b.define_id = replacements[b.define_id] |
| 1402 | made_change = True |
| 1403 | |
Elliott Hughes | fddbafd | 2014-05-01 10:17:27 -0700 | [diff] [blame] | 1404 | if made_change and b.isIf(): |
| 1405 | # Keep 'expr' in sync with 'tokens'. |
| 1406 | b.expr = CppExpr(b.tokens) |
Martin Storsjo | d32c805 | 2010-12-08 11:38:14 +0100 | [diff] [blame] | 1407 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1408 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1409 | def strip_space(s): |
| 1410 | """Strip out redundant space in a given string.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1411 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1412 | # NOTE: It ought to be more clever to not destroy spaces in string tokens. |
| 1413 | replacements = {' . ': '.', |
| 1414 | ' [': '[', |
| 1415 | '[ ': '[', |
| 1416 | ' ]': ']', |
| 1417 | '( ': '(', |
| 1418 | ' )': ')', |
| 1419 | ' ,': ',', |
| 1420 | '# ': '#', |
| 1421 | ' ;': ';', |
| 1422 | '~ ': '~', |
| 1423 | ' -> ': '->'} |
| 1424 | result = s |
| 1425 | for r in replacements: |
| 1426 | result = result.replace(r, replacements[r]) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1427 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1428 | # Remove the space between function name and the parenthesis. |
| 1429 | result = re.sub(r'(\w+) \(', r'\1(', result) |
| 1430 | return result |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1431 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1432 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1433 | class BlockParser(object): |
| 1434 | """A class that converts an input source file into a BlockList object.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1435 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1436 | def __init__(self, tokzer=None): |
| 1437 | """Initialize a block parser. |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1438 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1439 | The input source is provided through a Tokenizer object. |
| 1440 | """ |
| 1441 | self._tokzer = tokzer |
| 1442 | self._parsed = False |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1443 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1444 | @property |
| 1445 | def parsed(self): |
| 1446 | return self._parsed |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1447 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1448 | @staticmethod |
| 1449 | def _short_extent(extent): |
| 1450 | return '%d:%d - %d:%d' % (extent.start.line, extent.start.column, |
| 1451 | extent.end.line, extent.end.column) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1452 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1453 | def getBlocks(self, tokzer=None): |
| 1454 | """Return all the blocks parsed.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1455 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1456 | def consume_extent(i, tokens, extent=None, detect_change=False): |
| 1457 | """Return tokens that belong to the given extent. |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1458 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1459 | It parses all the tokens that follow tokens[i], until getting out |
| 1460 | of the extent. When detect_change is True, it may terminate early |
| 1461 | when detecting preprocessing directives inside the extent. |
| 1462 | """ |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1463 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1464 | result = [] |
| 1465 | if extent is None: |
| 1466 | extent = tokens[i].cursor.extent |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1467 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1468 | while i < len(tokens) and tokens[i].location in extent: |
| 1469 | t = tokens[i] |
| 1470 | if debugBlockParser: |
| 1471 | print ' ' * 2, t.id, t.kind, t.cursor.kind |
| 1472 | if (detect_change and t.cursor.extent != extent and |
| 1473 | t.cursor.kind == CursorKind.PREPROCESSING_DIRECTIVE): |
| 1474 | break |
| 1475 | result.append(t) |
| 1476 | i += 1 |
| 1477 | return (i, result) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1478 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1479 | def consume_line(i, tokens): |
| 1480 | """Return tokens that follow tokens[i] in the same line.""" |
| 1481 | result = [] |
| 1482 | line = tokens[i].location.line |
| 1483 | while i < len(tokens) and tokens[i].location.line == line: |
| 1484 | if tokens[i].cursor.kind == CursorKind.PREPROCESSING_DIRECTIVE: |
| 1485 | break |
| 1486 | result.append(tokens[i]) |
| 1487 | i += 1 |
| 1488 | return (i, result) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1489 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1490 | if tokzer is None: |
| 1491 | tokzer = self._tokzer |
| 1492 | tokens = tokzer.tokens |
| 1493 | |
| 1494 | blocks = [] |
| 1495 | buf = [] |
| 1496 | i = 0 |
| 1497 | |
| 1498 | while i < len(tokens): |
| 1499 | t = tokens[i] |
| 1500 | cursor = t.cursor |
| 1501 | |
| 1502 | if debugBlockParser: |
| 1503 | print ("%d: Processing [%s], kind=[%s], cursor=[%s], " |
| 1504 | "extent=[%s]" % (t.location.line, t.spelling, t.kind, |
| 1505 | cursor.kind, |
| 1506 | self._short_extent(cursor.extent))) |
| 1507 | |
| 1508 | if cursor.kind == CursorKind.PREPROCESSING_DIRECTIVE: |
| 1509 | if buf: |
| 1510 | blocks.append(Block(buf)) |
| 1511 | buf = [] |
| 1512 | |
| 1513 | j = i |
| 1514 | if j + 1 >= len(tokens): |
| 1515 | raise BadExpectedToken("### BAD TOKEN at %s" % (t.location)) |
| 1516 | directive = tokens[j+1].id |
| 1517 | |
| 1518 | if directive == 'define': |
| 1519 | if i+2 >= len(tokens): |
| 1520 | raise BadExpectedToken("### BAD TOKEN at %s" % |
| 1521 | (tokens[i].location)) |
| 1522 | |
| 1523 | # Skip '#' and 'define'. |
| 1524 | extent = tokens[i].cursor.extent |
| 1525 | i += 2 |
| 1526 | id = '' |
| 1527 | # We need to separate the id from the remaining of |
| 1528 | # the line, especially for the function-like macro. |
| 1529 | if (i + 1 < len(tokens) and tokens[i+1].id == '(' and |
| 1530 | (tokens[i].location.column + len(tokens[i].spelling) == |
| 1531 | tokens[i+1].location.column)): |
| 1532 | while i < len(tokens): |
| 1533 | id += tokens[i].id |
| 1534 | if tokens[i].spelling == ')': |
| 1535 | i += 1 |
| 1536 | break |
| 1537 | i += 1 |
| 1538 | else: |
| 1539 | id += tokens[i].id |
| 1540 | # Advance to the next token that follows the macro id |
| 1541 | i += 1 |
| 1542 | |
| 1543 | (i, ret) = consume_extent(i, tokens, extent=extent) |
| 1544 | blocks.append(Block(ret, directive=directive, |
| 1545 | lineno=t.location.line, identifier=id)) |
| 1546 | |
| 1547 | else: |
| 1548 | (i, ret) = consume_extent(i, tokens) |
| 1549 | blocks.append(Block(ret[2:], directive=directive, |
| 1550 | lineno=t.location.line)) |
| 1551 | |
| 1552 | elif cursor.kind == CursorKind.INCLUSION_DIRECTIVE: |
| 1553 | if buf: |
| 1554 | blocks.append(Block(buf)) |
| 1555 | buf = [] |
| 1556 | directive = tokens[i+1].id |
| 1557 | (i, ret) = consume_extent(i, tokens) |
| 1558 | |
| 1559 | blocks.append(Block(ret[2:], directive=directive, |
| 1560 | lineno=t.location.line)) |
| 1561 | |
| 1562 | elif cursor.kind == CursorKind.VAR_DECL: |
| 1563 | if buf: |
| 1564 | blocks.append(Block(buf)) |
| 1565 | buf = [] |
| 1566 | |
| 1567 | (i, ret) = consume_extent(i, tokens, detect_change=True) |
| 1568 | buf += ret |
| 1569 | |
| 1570 | elif cursor.kind == CursorKind.FUNCTION_DECL: |
| 1571 | if buf: |
| 1572 | blocks.append(Block(buf)) |
| 1573 | buf = [] |
| 1574 | |
| 1575 | (i, ret) = consume_extent(i, tokens, detect_change=True) |
| 1576 | buf += ret |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1577 | |
| 1578 | else: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1579 | (i, ret) = consume_line(i, tokens) |
| 1580 | buf += ret |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1581 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1582 | if buf: |
| 1583 | blocks.append(Block(buf)) |
| 1584 | |
| 1585 | # _parsed=True indicates a successful parsing, although may result an |
| 1586 | # empty BlockList. |
| 1587 | self._parsed = True |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1588 | |
| 1589 | return BlockList(blocks) |
| 1590 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1591 | def parse(self, tokzer): |
| 1592 | return self.getBlocks(tokzer) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1593 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1594 | def parseFile(self, path): |
| 1595 | return self.getBlocks(CppFileTokenizer(path)) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1596 | |
| 1597 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1598 | def test_block_parsing(lines, expected): |
| 1599 | """Helper method to test the correctness of BlockParser.parse.""" |
| 1600 | blocks = BlockParser().parse(CppStringTokenizer('\n'.join(lines))) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1601 | if len(blocks) != len(expected): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1602 | raise BadExpectedToken("BlockParser.parse() returned '%s' expecting " |
| 1603 | "'%s'" % (str(blocks), repr(expected))) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1604 | for n in range(len(blocks)): |
| 1605 | if str(blocks[n]) != expected[n]: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1606 | raise BadExpectedToken("BlockParser.parse()[%d] is '%s', " |
| 1607 | "expecting '%s'" % (n, str(blocks[n]), |
| 1608 | expected[n])) |
| 1609 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1610 | |
| 1611 | def test_BlockParser(): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1612 | test_block_parsing(["#error hello"], ["#error hello"]) |
| 1613 | test_block_parsing(["foo", "", "bar"], ["foo bar"]) |
| 1614 | |
| 1615 | # We currently cannot handle the following case with libclang properly. |
| 1616 | # Fortunately it doesn't appear in current headers. |
| 1617 | # test_block_parsing(["foo", " # ", "bar"], ["foo", "bar"]) |
| 1618 | |
| 1619 | test_block_parsing(["foo", |
| 1620 | " # /* ahah */ if defined(__KERNEL__) /* more */", |
| 1621 | "bar", "#endif"], |
| 1622 | ["foo", "#ifdef __KERNEL__", "bar", "#endif"]) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1623 | |
| 1624 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1625 | ################################################################################ |
| 1626 | ################################################################################ |
| 1627 | ##### ##### |
| 1628 | ##### B L O C K L I S T O P T I M I Z A T I O N ##### |
| 1629 | ##### ##### |
| 1630 | ################################################################################ |
| 1631 | ################################################################################ |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1632 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1633 | |
| 1634 | def remove_macro_defines(blocks, excludedMacros=None): |
| 1635 | """Remove macro definitions like #define <macroName> ....""" |
| 1636 | if excludedMacros is None: |
| 1637 | excludedMacros = set() |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1638 | result = [] |
| 1639 | for b in blocks: |
| 1640 | macroName = b.isDefine() |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1641 | if macroName is None or macroName not in excludedMacros: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1642 | result.append(b) |
| 1643 | |
| 1644 | return result |
| 1645 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1646 | |
| 1647 | def find_matching_endif(blocks, i): |
| 1648 | """Traverse the blocks to find out the matching #endif.""" |
| 1649 | n = len(blocks) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1650 | depth = 1 |
| 1651 | while i < n: |
| 1652 | if blocks[i].isDirective(): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1653 | dir_ = blocks[i].directive |
| 1654 | if dir_ in ["if", "ifndef", "ifdef"]: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1655 | depth += 1 |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1656 | elif depth == 1 and dir_ in ["else", "elif"]: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1657 | return i |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1658 | elif dir_ == "endif": |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1659 | depth -= 1 |
| 1660 | if depth == 0: |
| 1661 | return i |
| 1662 | i += 1 |
| 1663 | return i |
| 1664 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1665 | |
| 1666 | def optimize_if01(blocks): |
| 1667 | """Remove the code between #if 0 .. #endif in a list of CppBlocks.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1668 | i = 0 |
| 1669 | n = len(blocks) |
| 1670 | result = [] |
| 1671 | while i < n: |
| 1672 | j = i |
| 1673 | while j < n and not blocks[j].isIf(): |
| 1674 | j += 1 |
| 1675 | if j > i: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1676 | logging.debug("appending lines %d to %d", blocks[i].lineno, |
| 1677 | blocks[j-1].lineno) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1678 | result += blocks[i:j] |
| 1679 | if j >= n: |
| 1680 | break |
| 1681 | expr = blocks[j].expr |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1682 | r = expr.toInt() |
| 1683 | if r is None: |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1684 | result.append(blocks[j]) |
| 1685 | i = j + 1 |
| 1686 | continue |
| 1687 | |
| 1688 | if r == 0: |
| 1689 | # if 0 => skip everything until the corresponding #endif |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1690 | j = find_matching_endif(blocks, j + 1) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1691 | if j >= n: |
| 1692 | # unterminated #if 0, finish here |
| 1693 | break |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1694 | dir_ = blocks[j].directive |
| 1695 | if dir_ == "endif": |
| 1696 | logging.debug("remove 'if 0' .. 'endif' (lines %d to %d)", |
| 1697 | blocks[i].lineno, blocks[j].lineno) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1698 | i = j + 1 |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1699 | elif dir_ == "else": |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1700 | # convert 'else' into 'if 1' |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1701 | logging.debug("convert 'if 0' .. 'else' into 'if 1' (lines %d " |
| 1702 | "to %d)", blocks[i].lineno, blocks[j-1].lineno) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1703 | blocks[j].directive = "if" |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1704 | blocks[j].expr = CppExpr(CppStringTokenizer("1").tokens) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1705 | i = j |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1706 | elif dir_ == "elif": |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1707 | # convert 'elif' into 'if' |
Elliott Hughes | dc1fb70 | 2014-08-20 11:16:11 -0700 | [diff] [blame] | 1708 | logging.debug("convert 'if 0' .. 'elif' into 'if'") |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1709 | blocks[j].directive = "if" |
| 1710 | i = j |
| 1711 | continue |
| 1712 | |
| 1713 | # if 1 => find corresponding endif and remove/transform them |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1714 | k = find_matching_endif(blocks, j + 1) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1715 | if k >= n: |
| 1716 | # unterminated #if 1, finish here |
Elliott Hughes | dc1fb70 | 2014-08-20 11:16:11 -0700 | [diff] [blame] | 1717 | logging.debug("unterminated 'if 1'") |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1718 | result += blocks[j+1:k] |
| 1719 | break |
| 1720 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1721 | dir_ = blocks[k].directive |
| 1722 | if dir_ == "endif": |
| 1723 | logging.debug("convert 'if 1' .. 'endif' (lines %d to %d)", |
| 1724 | blocks[j].lineno, blocks[k].lineno) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1725 | result += optimize_if01(blocks[j+1:k]) |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1726 | i = k + 1 |
| 1727 | elif dir_ == "else": |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1728 | # convert 'else' into 'if 0' |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1729 | logging.debug("convert 'if 1' .. 'else' (lines %d to %d)", |
| 1730 | blocks[j].lineno, blocks[k].lineno) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1731 | result += optimize_if01(blocks[j+1:k]) |
| 1732 | blocks[k].directive = "if" |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1733 | blocks[k].expr = CppExpr(CppStringTokenizer("0").tokens) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1734 | i = k |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1735 | elif dir_ == "elif": |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1736 | # convert 'elif' into 'if 0' |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1737 | logging.debug("convert 'if 1' .. 'elif' (lines %d to %d)", |
| 1738 | blocks[j].lineno, blocks[k].lineno) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1739 | result += optimize_if01(blocks[j+1:k]) |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1740 | blocks[k].expr = CppExpr(CppStringTokenizer("0").tokens) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1741 | i = k |
| 1742 | return result |
| 1743 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1744 | |
| 1745 | def test_optimizeAll(): |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1746 | text = """\ |
| 1747 | #if 1 |
| 1748 | #define GOOD_1 |
| 1749 | #endif |
| 1750 | #if 0 |
| 1751 | #define BAD_2 |
| 1752 | #define BAD_3 |
| 1753 | #endif |
| 1754 | |
| 1755 | #if 1 |
| 1756 | #define GOOD_2 |
| 1757 | #else |
| 1758 | #define BAD_4 |
| 1759 | #endif |
| 1760 | |
| 1761 | #if 0 |
| 1762 | #define BAD_5 |
| 1763 | #else |
| 1764 | #define GOOD_3 |
| 1765 | #endif |
| 1766 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 1767 | #if defined(__KERNEL__) |
| 1768 | #define BAD_KERNEL |
| 1769 | #endif |
| 1770 | |
| 1771 | #if defined(__KERNEL__) || !defined(__GLIBC__) || (__GLIBC__ < 2) |
| 1772 | #define X |
| 1773 | #endif |
| 1774 | |
Elliott Hughes | fddbafd | 2014-05-01 10:17:27 -0700 | [diff] [blame] | 1775 | #ifndef SIGRTMAX |
| 1776 | #define SIGRTMAX 123 |
| 1777 | #endif /* SIGRTMAX */ |
| 1778 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1779 | #if 0 |
| 1780 | #if 1 |
| 1781 | #define BAD_6 |
| 1782 | #endif |
| 1783 | #endif\ |
| 1784 | """ |
| 1785 | |
| 1786 | expected = """\ |
| 1787 | #define GOOD_1 |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1788 | #define GOOD_2 |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1789 | #define GOOD_3 |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 1790 | #if !defined(__GLIBC__) || __GLIBC__ < 2 |
| 1791 | #define X |
| 1792 | #endif |
Elliott Hughes | fddbafd | 2014-05-01 10:17:27 -0700 | [diff] [blame] | 1793 | #ifndef __SIGRTMAX |
| 1794 | #define __SIGRTMAX 123 |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1795 | #endif\ |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1796 | """ |
| 1797 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1798 | out = utils.StringOutput() |
| 1799 | blocks = BlockParser().parse(CppStringTokenizer(text)) |
| 1800 | blocks.replaceTokens(kernel_token_replacements) |
| 1801 | blocks.optimizeAll({"__KERNEL__": kCppUndefinedMacro}) |
| 1802 | blocks.write(out) |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1803 | if out.get() != expected: |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 1804 | print "[FAIL]: macro optimization failed\n" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1805 | print "<<<< expecting '", |
| 1806 | print expected, |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1807 | print "'\n>>>> result '", |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1808 | print out.get(), |
| 1809 | print "'\n----" |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 1810 | global failure_count |
| 1811 | failure_count += 1 |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1812 | |
| 1813 | |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1814 | def runUnitTests(): |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1815 | """Always run all unit tests for this program.""" |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1816 | test_CppTokenizer() |
| 1817 | test_CppExpr() |
| 1818 | test_optimizeAll() |
| 1819 | test_BlockParser() |
The Android Open Source Project | 1dc9e47 | 2009-03-03 19:28:35 -0800 | [diff] [blame] | 1820 | |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1821 | |
Elliott Hughes | 40596aa | 2013-11-05 14:54:29 -0800 | [diff] [blame] | 1822 | failure_count = 0 |
| 1823 | runUnitTests() |
| 1824 | if failure_count != 0: |
Tao Bao | d7db594 | 2015-01-28 10:07:51 -0800 | [diff] [blame] | 1825 | utils.panic("Unit tests failed in cpp.py.\n") |