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