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