BaseTools: remove local hex number regular expression
[mirror_edk2.git] / BaseTools / Source / Python / Common / RangeExpression.py
CommitLineData
82a6a960
BF
1# # @file\r
2# This file is used to parse and evaluate range expression in Pcd declaration.\r
3#\r
c1e73234 4# Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR>\r
82a6a960
BF
5# This program and the accompanying materials\r
6# are licensed and made available under the terms and conditions of the BSD License\r
7# which accompanies this distribution. The full text of the license may be found at\r
8# http://opensource.org/licenses/bsd-license.php\r
9#\r
10# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
11# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
12\r
13# # Import Modules\r
14#\r
15from Common.GlobalData import *\r
16from CommonDataClass.Exceptions import BadExpression\r
17from CommonDataClass.Exceptions import WrnExpression\r
18import uuid\r
19\r
20ERR_STRING_EXPR = 'This operator cannot be used in string expression: [%s].'\r
21ERR_SNYTAX = 'Syntax error, the rest of expression cannot be evaluated: [%s].'\r
22ERR_MATCH = 'No matching right parenthesis.'\r
23ERR_STRING_TOKEN = 'Bad string token: [%s].'\r
24ERR_MACRO_TOKEN = 'Bad macro token: [%s].'\r
25ERR_EMPTY_TOKEN = 'Empty token is not allowed.'\r
26ERR_PCD_RESOLVE = 'PCD token cannot be resolved: [%s].'\r
27ERR_VALID_TOKEN = 'No more valid token found from rest of string: [%s].'\r
28ERR_EXPR_TYPE = 'Different types found in expression.'\r
29ERR_OPERATOR_UNSUPPORT = 'Unsupported operator: [%s]'\r
30ERR_REL_NOT_IN = 'Expect "IN" after "not" operator.'\r
31WRN_BOOL_EXPR = 'Operand of boolean type cannot be used in arithmetic expression.'\r
32WRN_EQCMP_STR_OTHERS = '== Comparison between Operand of string type and Boolean/Number Type always return False.'\r
33WRN_NECMP_STR_OTHERS = '!= Comparison between Operand of string type and Boolean/Number Type always return True.'\r
34ERR_RELCMP_STR_OTHERS = 'Operator taking Operand of string type and Boolean/Number Type is not allowed: [%s].'\r
35ERR_STRING_CMP = 'Unicode string and general string cannot be compared: [%s %s %s]'\r
36ERR_ARRAY_TOKEN = 'Bad C array or C format GUID token: [%s].'\r
37ERR_ARRAY_ELE = 'This must be HEX value for NList or Array: [%s].'\r
38ERR_EMPTY_EXPR = 'Empty expression is not allowed.'\r
39ERR_IN_OPERAND = 'Macro after IN operator can only be: $(FAMILY), $(ARCH), $(TOOL_CHAIN_TAG) and $(TARGET).'\r
40\r
41def MaxOfType(DataType):\r
42 if DataType == 'UINT8':\r
43 return int('0xFF', 16)\r
44 if DataType == 'UINT16':\r
45 return int('0xFFFF', 16)\r
46 if DataType == 'UINT32':\r
47 return int('0xFFFFFFFF', 16)\r
48 if DataType == 'UINT64':\r
49 return int('0xFFFFFFFFFFFFFFFF', 16)\r
50\r
51class RangeObject(object):\r
52 def __init__(self, start, end, empty = False):\r
53 \r
54 if int(start) < int(end):\r
55 self.start = int(start)\r
56 self.end = int(end)\r
57 else:\r
58 self.start = int(end)\r
59 self.end = int(start)\r
60 self.empty = empty\r
61\r
62class RangeContainer(object):\r
63 def __init__(self):\r
64 self.rangelist = []\r
65 \r
66 def push(self, RangeObject):\r
67 self.rangelist.append(RangeObject)\r
68 self.rangelist = sorted(self.rangelist, key = lambda rangeobj : rangeobj.start)\r
69 self.merge()\r
70 \r
71 def pop(self):\r
72 for item in self.rangelist:\r
73 yield item\r
74 \r
75 def __clean__(self): \r
76 newrangelist = []\r
77 for rangeobj in self.rangelist:\r
78 if rangeobj.empty == True:\r
79 continue\r
80 else:\r
81 newrangelist.append(rangeobj)\r
82 self.rangelist = newrangelist \r
83 def merge(self):\r
84 self.__clean__()\r
85 for i in range(0, len(self.rangelist) - 1):\r
86 if self.rangelist[i + 1].start > self.rangelist[i].end:\r
87 continue\r
88 else:\r
89 self.rangelist[i + 1].start = self.rangelist[i].start\r
90 self.rangelist[i + 1].end = self.rangelist[i + 1].end > self.rangelist[i].end and self.rangelist[i + 1].end or self.rangelist[i].end \r
91 self.rangelist[i].empty = True\r
92\r
93 self.__clean__()\r
94 \r
95 def dump(self):\r
96 print "----------------------"\r
97 rangelist = ""\r
98 for object in self.rangelist:\r
99 rangelist = rangelist + "[%d , %d]" % (object.start, object.end)\r
100 print rangelist\r
101 \r
102 \r
103class XOROperatorObject(object): \r
104 def __init__(self): \r
105 pass\r
106 def Calculate(self, Operand, DataType, SymbolTable): \r
107 if type(Operand) == type('') and not Operand.isalnum():\r
108 Expr = "XOR ..."\r
109 raise BadExpression(ERR_SNYTAX % Expr)\r
110 rangeId = str(uuid.uuid1())\r
111 rangeContainer = RangeContainer()\r
112 rangeContainer.push(RangeObject(0, int(Operand) - 1))\r
113 rangeContainer.push(RangeObject(int(Operand) + 1, MaxOfType(DataType)))\r
114 SymbolTable[rangeId] = rangeContainer\r
115 return rangeId\r
116\r
117class LEOperatorObject(object):\r
118 def __init__(self): \r
119 pass\r
120 def Calculate(self, Operand, DataType, SymbolTable): \r
121 if type(Operand) == type('') and not Operand.isalnum():\r
122 Expr = "LE ..."\r
123 raise BadExpression(ERR_SNYTAX % Expr)\r
124 rangeId1 = str(uuid.uuid1())\r
125 rangeContainer = RangeContainer()\r
126 rangeContainer.push(RangeObject(0, int(Operand)))\r
127 SymbolTable[rangeId1] = rangeContainer\r
128 return rangeId1\r
129class LTOperatorObject(object):\r
130 def __init__(self): \r
131 pass\r
132 def Calculate(self, Operand, DataType, SymbolTable):\r
133 if type(Operand) == type('') and not Operand.isalnum():\r
134 Expr = "LT ..." \r
135 raise BadExpression(ERR_SNYTAX % Expr) \r
136 rangeId1 = str(uuid.uuid1())\r
137 rangeContainer = RangeContainer()\r
138 rangeContainer.push(RangeObject(0, int(Operand) - 1))\r
139 SymbolTable[rangeId1] = rangeContainer\r
140 return rangeId1 \r
141\r
142class GEOperatorObject(object):\r
143 def __init__(self): \r
144 pass\r
145 def Calculate(self, Operand, DataType, SymbolTable): \r
146 if type(Operand) == type('') and not Operand.isalnum():\r
147 Expr = "GE ..."\r
148 raise BadExpression(ERR_SNYTAX % Expr)\r
149 rangeId1 = str(uuid.uuid1())\r
150 rangeContainer = RangeContainer()\r
151 rangeContainer.push(RangeObject(int(Operand), MaxOfType(DataType)))\r
152 SymbolTable[rangeId1] = rangeContainer\r
153 return rangeId1 \r
154 \r
155class GTOperatorObject(object):\r
156 def __init__(self): \r
157 pass\r
158 def Calculate(self, Operand, DataType, SymbolTable): \r
159 if type(Operand) == type('') and not Operand.isalnum():\r
160 Expr = "GT ..."\r
161 raise BadExpression(ERR_SNYTAX % Expr)\r
162 rangeId1 = str(uuid.uuid1())\r
163 rangeContainer = RangeContainer()\r
164 rangeContainer.push(RangeObject(int(Operand) + 1, MaxOfType(DataType)))\r
165 SymbolTable[rangeId1] = rangeContainer\r
166 return rangeId1 \r
167 \r
168class EQOperatorObject(object):\r
169 def __init__(self): \r
170 pass\r
171 def Calculate(self, Operand, DataType, SymbolTable): \r
172 if type(Operand) == type('') and not Operand.isalnum():\r
173 Expr = "EQ ..."\r
174 raise BadExpression(ERR_SNYTAX % Expr)\r
175 rangeId1 = str(uuid.uuid1())\r
176 rangeContainer = RangeContainer()\r
177 rangeContainer.push(RangeObject(int(Operand) , int(Operand)))\r
178 SymbolTable[rangeId1] = rangeContainer\r
179 return rangeId1 \r
180 \r
181def GetOperatorObject(Operator):\r
182 if Operator == '>':\r
183 return GTOperatorObject()\r
184 elif Operator == '>=':\r
185 return GEOperatorObject()\r
186 elif Operator == '<':\r
187 return LTOperatorObject()\r
188 elif Operator == '<=':\r
189 return LEOperatorObject()\r
190 elif Operator == '==':\r
191 return EQOperatorObject()\r
192 elif Operator == '^':\r
193 return XOROperatorObject()\r
194 else:\r
195 raise BadExpression("Bad Operator")\r
196\r
197class RangeExpression(object):\r
198 # Logical operator mapping\r
199 LogicalOperators = {\r
200 '&&' : 'and', '||' : 'or',\r
201 '!' : 'not', 'AND': 'and',\r
202 'OR' : 'or' , 'NOT': 'not',\r
203 'XOR': '^' , 'xor': '^',\r
204 'EQ' : '==' , 'NE' : '!=',\r
205 'GT' : '>' , 'LT' : '<',\r
206 'GE' : '>=' , 'LE' : '<=',\r
207 'IN' : 'in'\r
208 }\r
209\r
210 NonLetterOpLst = ['+', '-', '&', '|', '^', '!', '=', '>', '<']\r
211\r
212 PcdPattern = re.compile(r'[_a-zA-Z][0-9A-Za-z_]*\.[_a-zA-Z][0-9A-Za-z_]*$')\r
82a6a960 213 \r
82a6a960
BF
214 RangePattern = re.compile(r'[0-9]+ - [0-9]+')\r
215\r
216 def preProcessRangeExpr(self, expr):\r
217 # convert hex to int\r
218 # convert interval to object index. ex. 1 - 10 to a GUID\r
219 expr = expr.strip()\r
220 NumberDict = {}\r
56326323 221 for HexNumber in gHexPattern.findall(expr):\r
82a6a960
BF
222 Number = str(int(HexNumber, 16))\r
223 NumberDict[HexNumber] = Number\r
224 for HexNum in NumberDict:\r
225 expr = expr.replace(HexNum, NumberDict[HexNum])\r
226 \r
227 rangedict = {} \r
228 for validrange in self.RangePattern.findall(expr):\r
229 start, end = validrange.split(" - ")\r
230 start = start.strip()\r
231 end = end.strip()\r
232 rangeid = str(uuid.uuid1())\r
233 rangeContainer = RangeContainer()\r
234 rangeContainer.push(RangeObject(start, end))\r
235 self.operanddict[str(rangeid)] = rangeContainer\r
236 rangedict[validrange] = str(rangeid)\r
237 \r
238 for validrange in rangedict:\r
239 expr = expr.replace(validrange, rangedict[validrange])\r
240 \r
241 self._Expr = expr \r
242 return expr\r
243 \r
244 \r
245 def EvalRange(self, Operator, Oprand):\r
246\r
247 operatorobj = GetOperatorObject(Operator)\r
248 return operatorobj.Calculate(Oprand, self.PcdDataType, self.operanddict)\r
249 \r
250 def Rangeintersection(self, Oprand1, Oprand2):\r
251 rangeContainer1 = self.operanddict[Oprand1]\r
252 rangeContainer2 = self.operanddict[Oprand2]\r
253 rangeContainer = RangeContainer()\r
254 for range1 in rangeContainer1.pop():\r
255 for range2 in rangeContainer2.pop():\r
0b5203bd
BF
256 start1 = range1.start\r
257 end1 = range1.end\r
258 start2 = range2.start\r
259 end2 = range2.end\r
260 if start1 >= start2:\r
261 start1, start2 = start2, start1\r
262 end1, end2 = end2, end1\r
82a6a960
BF
263 if range1.empty:\r
264 rangeid = str(uuid.uuid1())\r
265 rangeContainer.push(RangeObject(0, 0, True))\r
0b5203bd 266 if end1 < start2:\r
82a6a960
BF
267 rangeid = str(uuid.uuid1())\r
268 rangeContainer.push(RangeObject(0, 0, True))\r
0b5203bd 269 elif end1 == start2:\r
82a6a960 270 rangeid = str(uuid.uuid1())\r
0b5203bd
BF
271 rangeContainer.push(RangeObject(end1, end1))\r
272 elif end1 <= end2 and end1 > start2:\r
82a6a960 273 rangeid = str(uuid.uuid1())\r
0b5203bd
BF
274 rangeContainer.push(RangeObject(start2, end1))\r
275 elif end1 >= end2:\r
82a6a960 276 rangeid = str(uuid.uuid1())\r
0b5203bd 277 rangeContainer.push(RangeObject(start2, end2))\r
82a6a960
BF
278 \r
279 self.operanddict[rangeid] = rangeContainer\r
280# rangeContainer.dump()\r
281 return rangeid\r
282 \r
283 def Rangecollections(self, Oprand1, Oprand2):\r
284\r
285 rangeContainer1 = self.operanddict[Oprand1]\r
286 rangeContainer2 = self.operanddict[Oprand2]\r
287 rangeContainer = RangeContainer()\r
288 \r
289 for rangeobj in rangeContainer2.pop():\r
290 rangeContainer.push(rangeobj)\r
291 for rangeobj in rangeContainer1.pop():\r
292 rangeContainer.push(rangeobj)\r
293 \r
294 rangeid = str(uuid.uuid1())\r
295 self.operanddict[rangeid] = rangeContainer\r
296 \r
297# rangeContainer.dump()\r
298 return rangeid\r
299 \r
300 \r
301 def NegtiveRange(self, Oprand1):\r
302 rangeContainer1 = self.operanddict[Oprand1]\r
303 \r
304 \r
305 rangeids = []\r
306 \r
307 for rangeobj in rangeContainer1.pop():\r
308 rangeContainer = RangeContainer()\r
309 rangeid = str(uuid.uuid1())\r
310 if rangeobj.empty:\r
311 rangeContainer.push(RangeObject(0, MaxOfType(self.PcdDataType)))\r
312 else:\r
313 if rangeobj.start > 0:\r
314 rangeContainer.push(RangeObject(0, rangeobj.start - 1))\r
315 if rangeobj.end < MaxOfType(self.PcdDataType):\r
316 rangeContainer.push(RangeObject(rangeobj.end + 1, MaxOfType(self.PcdDataType)))\r
317 self.operanddict[rangeid] = rangeContainer\r
318 rangeids.append(rangeid)\r
319\r
320 if len(rangeids) == 0:\r
321 rangeContainer = RangeContainer()\r
322 rangeContainer.push(RangeObject(0, MaxOfType(self.PcdDataType)))\r
323 rangeid = str(uuid.uuid1())\r
324 self.operanddict[rangeid] = rangeContainer\r
325 return rangeid\r
326\r
327 if len(rangeids) == 1:\r
328 return rangeids[0]\r
329\r
330 re = self.Rangeintersection(rangeids[0], rangeids[1])\r
331 for i in range(2, len(rangeids)):\r
332 re = self.Rangeintersection(re, rangeids[i])\r
333 \r
334 rangeid2 = str(uuid.uuid1())\r
335 self.operanddict[rangeid2] = self.operanddict[re]\r
336 return rangeid2\r
337 \r
338 def Eval(self, Operator, Oprand1, Oprand2 = None):\r
339 \r
340 if Operator in ["!", "NOT", "not"]:\r
b1a9e404 341 if not gGuidPattern.match(Oprand1.strip()):\r
82a6a960
BF
342 raise BadExpression(ERR_STRING_EXPR % Operator)\r
343 return self.NegtiveRange(Oprand1)\r
344 else:\r
345 if Operator in ["==", ">=", "<=", ">", "<", '^']:\r
346 return self.EvalRange(Operator, Oprand1)\r
347 elif Operator == 'and' :\r
b1a9e404 348 if not gGuidPatternEnd.match(Oprand1.strip()) or not gGuidPatternEnd.match(Oprand2.strip()):\r
82a6a960
BF
349 raise BadExpression(ERR_STRING_EXPR % Operator)\r
350 return self.Rangeintersection(Oprand1, Oprand2) \r
351 elif Operator == 'or':\r
b1a9e404 352 if not gGuidPatternEnd.match(Oprand1.strip()) or not gGuidPatternEnd.match(Oprand2.strip()):\r
82a6a960
BF
353 raise BadExpression(ERR_STRING_EXPR % Operator)\r
354 return self.Rangecollections(Oprand1, Oprand2)\r
355 else:\r
356 raise BadExpression(ERR_STRING_EXPR % Operator)\r
357\r
358\r
359 def __init__(self, Expression, PcdDataType, SymbolTable = {}):\r
360 self._NoProcess = False\r
361 if type(Expression) != type(''):\r
362 self._Expr = Expression\r
363 self._NoProcess = True\r
364 return\r
365\r
366 self._Expr = Expression.strip()\r
367\r
368 if not self._Expr.strip():\r
369 raise BadExpression(ERR_EMPTY_EXPR)\r
370\r
371 #\r
372 # The symbol table including PCD and macro mapping\r
373 #\r
374 self._Symb = SymbolTable\r
375 self._Symb.update(self.LogicalOperators)\r
376 self._Idx = 0\r
377 self._Len = len(self._Expr)\r
378 self._Token = ''\r
379 self._WarnExcept = None\r
380 \r
381\r
382 # Literal token without any conversion\r
383 self._LiteralToken = ''\r
384 \r
385 # store the operand object\r
386 self.operanddict = {}\r
387 # The Pcd max value depends on PcdDataType\r
388 self.PcdDataType = PcdDataType\r
389\r
390 # Public entry for this class\r
391 # @param RealValue: False: only evaluate if the expression is true or false, used for conditional expression\r
392 # True : return the evaluated str(value), used for PCD value\r
393 #\r
394 # @return: True or False if RealValue is False\r
395 # Evaluated value of string format if RealValue is True\r
396 #\r
397 def __call__(self, RealValue = False, Depth = 0):\r
398 if self._NoProcess:\r
399 return self._Expr\r
400\r
401 self._Depth = Depth\r
402\r
403 self._Expr = self._Expr.strip()\r
404 \r
405 self.preProcessRangeExpr(self._Expr)\r
406 \r
407 # check if the expression does not need to evaluate\r
408 if RealValue and Depth == 0:\r
409 self._Token = self._Expr\r
b1a9e404 410 if gGuidPatternEnd.match(self._Expr):\r
82a6a960
BF
411 return [self.operanddict[self._Expr] ]\r
412\r
413 self._Idx = 0\r
414 self._Token = ''\r
415\r
416 Val = self._OrExpr()\r
417 RealVal = Val\r
418 \r
419 RangeIdList = RealVal.split("or")\r
420 RangeList = []\r
421 for rangeid in RangeIdList:\r
422 RangeList.append(self.operanddict[rangeid.strip()])\r
423 \r
424 return RangeList\r
425\r
426 # Template function to parse binary operators which have same precedence\r
427 # Expr [Operator Expr]*\r
428 def _ExprFuncTemplate(self, EvalFunc, OpLst):\r
429 Val = EvalFunc()\r
430 while self._IsOperator(OpLst):\r
431 Op = self._Token\r
432 try:\r
433 Val = self.Eval(Op, Val, EvalFunc())\r
434 except WrnExpression, Warn:\r
435 self._WarnExcept = Warn\r
436 Val = Warn.result\r
437 return Val\r
438\r
439 # A [|| B]*\r
440 def _OrExpr(self):\r
441 return self._ExprFuncTemplate(self._AndExpr, ["OR", "or"])\r
442\r
443 # A [&& B]*\r
444 def _AndExpr(self):\r
445 return self._ExprFuncTemplate(self._NeExpr, ["AND", "and"])\r
446\r
447 def _NeExpr(self):\r
448 Val = self._RelExpr()\r
449 while self._IsOperator([ "!=", "NOT", "not"]):\r
450 Op = self._Token\r
451 if Op in ["!", "NOT", "not"]:\r
452 if not self._IsOperator(["IN", "in"]):\r
453 raise BadExpression(ERR_REL_NOT_IN)\r
454 Op += ' ' + self._Token\r
455 try:\r
456 Val = self.Eval(Op, Val, self._RelExpr())\r
457 except WrnExpression, Warn:\r
458 self._WarnExcept = Warn\r
459 Val = Warn.result\r
460 return Val\r
461\r
462 # [!]*A\r
463 def _RelExpr(self):\r
464 if self._IsOperator(["NOT" , "LE", "GE", "LT", "GT", "EQ", "XOR"]):\r
465 Token = self._Token\r
466 Val = self._NeExpr()\r
467 try:\r
468 return self.Eval(Token, Val)\r
469 except WrnExpression, Warn:\r
470 self._WarnExcept = Warn\r
471 return Warn.result\r
472 return self._IdenExpr()\r
473\r
474 # Parse identifier or encapsulated expression\r
475 def _IdenExpr(self):\r
476 Tk = self._GetToken()\r
477 if Tk == '(':\r
478 Val = self._OrExpr()\r
479 try:\r
480 # _GetToken may also raise BadExpression\r
481 if self._GetToken() != ')':\r
482 raise BadExpression(ERR_MATCH)\r
483 except BadExpression:\r
484 raise BadExpression(ERR_MATCH)\r
485 return Val\r
486 return Tk\r
487\r
488 # Skip whitespace or tab\r
489 def __SkipWS(self):\r
490 for Char in self._Expr[self._Idx:]:\r
491 if Char not in ' \t':\r
492 break\r
493 self._Idx += 1\r
494\r
495 # Try to convert string to number\r
496 def __IsNumberToken(self):\r
497 Radix = 10\r
498 if self._Token.lower()[0:2] == '0x' and len(self._Token) > 2:\r
499 Radix = 16\r
500 try:\r
501 self._Token = int(self._Token, Radix)\r
502 return True\r
503 except ValueError:\r
504 return False\r
505 except TypeError:\r
506 return False\r
507\r
508 # Parse array: {...}\r
509 def __GetArray(self):\r
510 Token = '{'\r
511 self._Idx += 1\r
512 self.__GetNList(True)\r
513 Token += self._LiteralToken\r
514 if self._Idx >= self._Len or self._Expr[self._Idx] != '}':\r
515 raise BadExpression(ERR_ARRAY_TOKEN % Token)\r
516 Token += '}'\r
517\r
518 # All whitespace and tabs in array are already stripped.\r
519 IsArray = IsGuid = False\r
520 if len(Token.split(',')) == 11 and len(Token.split(',{')) == 2 \\r
521 and len(Token.split('},')) == 1:\r
522 HexLen = [11, 6, 6, 5, 4, 4, 4, 4, 4, 4, 6]\r
523 HexList = Token.split(',')\r
524 if HexList[3].startswith('{') and \\r
525 not [Index for Index, Hex in enumerate(HexList) if len(Hex) > HexLen[Index]]:\r
526 IsGuid = True\r
527 if Token.lstrip('{').rstrip('}').find('{') == -1:\r
528 if not [Hex for Hex in Token.lstrip('{').rstrip('}').split(',') if len(Hex) > 4]:\r
529 IsArray = True\r
530 if not IsArray and not IsGuid:\r
531 raise BadExpression(ERR_ARRAY_TOKEN % Token)\r
532 self._Idx += 1\r
533 self._Token = self._LiteralToken = Token\r
534 return self._Token\r
535\r
536 # Parse string, the format must be: "..."\r
537 def __GetString(self):\r
538 Idx = self._Idx\r
539\r
540 # Skip left quote\r
541 self._Idx += 1\r
542\r
543 # Replace escape \\\", \"\r
544 Expr = self._Expr[self._Idx:].replace('\\\\', '//').replace('\\\"', '\\\'')\r
545 for Ch in Expr:\r
546 self._Idx += 1\r
547 if Ch == '"':\r
548 break\r
549 self._Token = self._LiteralToken = self._Expr[Idx:self._Idx]\r
550 if not self._Token.endswith('"'):\r
551 raise BadExpression(ERR_STRING_TOKEN % self._Token)\r
552 self._Token = self._Token[1:-1]\r
553 return self._Token\r
554\r
555 # Get token that is comprised by alphanumeric, underscore or dot(used by PCD)\r
556 # @param IsAlphaOp: Indicate if parsing general token or script operator(EQ, NE...)\r
557 def __GetIdToken(self, IsAlphaOp = False):\r
558 IdToken = ''\r
559 for Ch in self._Expr[self._Idx:]:\r
560 if not self.__IsIdChar(Ch):\r
561 break\r
562 self._Idx += 1\r
563 IdToken += Ch\r
564\r
565 self._Token = self._LiteralToken = IdToken\r
566 if not IsAlphaOp:\r
567 self.__ResolveToken()\r
568 return self._Token\r
569\r
570 # Try to resolve token\r
571 def __ResolveToken(self):\r
572 if not self._Token:\r
573 raise BadExpression(ERR_EMPTY_TOKEN)\r
574\r
575 # PCD token\r
576 if self.PcdPattern.match(self._Token):\r
577 if self._Token not in self._Symb:\r
578 Ex = BadExpression(ERR_PCD_RESOLVE % self._Token)\r
579 Ex.Pcd = self._Token\r
580 raise Ex\r
581 self._Token = RangeExpression(self._Symb[self._Token], self._Symb)(True, self._Depth + 1)\r
582 if type(self._Token) != type(''):\r
583 self._LiteralToken = hex(self._Token)\r
584 return\r
585\r
586 if self._Token.startswith('"'):\r
587 self._Token = self._Token[1:-1]\r
588 elif self._Token in ["FALSE", "false", "False"]:\r
589 self._Token = False\r
590 elif self._Token in ["TRUE", "true", "True"]:\r
591 self._Token = True\r
592 else:\r
593 self.__IsNumberToken()\r
594\r
595 def __GetNList(self, InArray = False):\r
596 self._GetSingleToken()\r
597 if not self.__IsHexLiteral():\r
598 if InArray:\r
599 raise BadExpression(ERR_ARRAY_ELE % self._Token)\r
600 return self._Token\r
601\r
602 self.__SkipWS()\r
603 Expr = self._Expr[self._Idx:]\r
604 if not Expr.startswith(','):\r
605 return self._Token\r
606\r
607 NList = self._LiteralToken\r
608 while Expr.startswith(','):\r
609 NList += ','\r
610 self._Idx += 1\r
611 self.__SkipWS()\r
612 self._GetSingleToken()\r
613 if not self.__IsHexLiteral():\r
614 raise BadExpression(ERR_ARRAY_ELE % self._Token)\r
615 NList += self._LiteralToken\r
616 self.__SkipWS()\r
617 Expr = self._Expr[self._Idx:]\r
618 self._Token = self._LiteralToken = NList\r
619 return self._Token\r
620\r
621 def __IsHexLiteral(self):\r
622 if self._LiteralToken.startswith('{') and \\r
623 self._LiteralToken.endswith('}'):\r
624 return True\r
625\r
56326323 626 if gHexPattern.match(self._LiteralToken):\r
82a6a960
BF
627 Token = self._LiteralToken[2:]\r
628 Token = Token.lstrip('0')\r
629 if not Token:\r
630 self._LiteralToken = '0x0'\r
631 else:\r
632 self._LiteralToken = '0x' + Token.lower()\r
633 return True\r
634 return False\r
635\r
636 def _GetToken(self):\r
637 return self.__GetNList()\r
638\r
639 @staticmethod\r
640 def __IsIdChar(Ch):\r
641 return Ch in '._/:' or Ch.isalnum()\r
642\r
643 # Parse operand\r
644 def _GetSingleToken(self):\r
645 self.__SkipWS()\r
646 Expr = self._Expr[self._Idx:]\r
647 if Expr.startswith('L"'):\r
648 # Skip L\r
649 self._Idx += 1\r
650 UStr = self.__GetString()\r
651 self._Token = 'L"' + UStr + '"'\r
652 return self._Token\r
653\r
654 self._Token = ''\r
655 if Expr:\r
656 Ch = Expr[0]\r
b1a9e404 657 Match = gGuidPattern.match(Expr)\r
82a6a960
BF
658 if Match and not Expr[Match.end():Match.end() + 1].isalnum() \\r
659 and Expr[Match.end():Match.end() + 1] != '_':\r
660 self._Idx += Match.end()\r
661 self._Token = Expr[0:Match.end()]\r
662 return self._Token\r
663 elif self.__IsIdChar(Ch):\r
664 return self.__GetIdToken()\r
665 elif Ch == '(' or Ch == ')':\r
666 self._Idx += 1\r
667 self._Token = Ch\r
668 return self._Token\r
669\r
670 raise BadExpression(ERR_VALID_TOKEN % Expr)\r
671\r
672 # Parse operator\r
673 def _GetOperator(self):\r
674 self.__SkipWS()\r
675 LegalOpLst = ['&&', '||', '!=', '==', '>=', '<='] + self.NonLetterOpLst\r
676\r
677 self._Token = ''\r
678 Expr = self._Expr[self._Idx:]\r
679\r
680 # Reach end of expression\r
681 if not Expr:\r
682 return ''\r
683\r
684 # Script operator: LT, GT, LE, GE, EQ, NE, and, or, xor, not\r
685 if Expr[0].isalpha():\r
686 return self.__GetIdToken(True)\r
687\r
688 # Start to get regular operator: +, -, <, > ...\r
689 if Expr[0] not in self.NonLetterOpLst:\r
690 return ''\r
691\r
692 OpToken = ''\r
693 for Ch in Expr:\r
694 if Ch in self.NonLetterOpLst:\r
695 if '!' == Ch and OpToken:\r
696 break\r
697 self._Idx += 1\r
698 OpToken += Ch\r
699 else:\r
700 break\r
701\r
702 if OpToken not in LegalOpLst:\r
703 raise BadExpression(ERR_OPERATOR_UNSUPPORT % OpToken)\r
704 self._Token = OpToken\r
705 return OpToken\r
706\r
707 # Check if current token matches the operators given from OpList\r
708 def _IsOperator(self, OpList):\r
709 Idx = self._Idx\r
710 self._GetOperator()\r
711 if self._Token in OpList:\r
712 if self._Token in self.LogicalOperators:\r
713 self._Token = self.LogicalOperators[self._Token]\r
714 return True\r
715 self._Idx = Idx\r
716 return False\r
717\r
718\r
719 \r
720 \r
721 \r
722 \r
723\r
724\r
725\r
726\r
727# UTRangeList()\r