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