]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/Common/Expression.py
BaseTools: Update --pcd parser to support flexible pcd format
[mirror_edk2.git] / BaseTools / Source / Python / Common / Expression.py
1 ## @file
2 # This file is used to parse and evaluate expression in directive or PCD value.
3 #
4 # Copyright (c) 2011 - 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 from Misc import GuidStringToGuidStructureString, ParseFieldValue, IsFieldValueAnArray
19 import Common.EdkLogger as EdkLogger
20 import copy
21
22 ERR_STRING_EXPR = 'This operator cannot be used in string expression: [%s].'
23 ERR_SNYTAX = 'Syntax error, the rest of expression cannot be evaluated: [%s].'
24 ERR_MATCH = 'No matching right parenthesis.'
25 ERR_STRING_TOKEN = 'Bad string token: [%s].'
26 ERR_MACRO_TOKEN = 'Bad macro token: [%s].'
27 ERR_EMPTY_TOKEN = 'Empty token is not allowed.'
28 ERR_PCD_RESOLVE = 'PCD token cannot be resolved: [%s].'
29 ERR_VALID_TOKEN = 'No more valid token found from rest of string: [%s].'
30 ERR_EXPR_TYPE = 'Different types found in expression.'
31 ERR_OPERATOR_UNSUPPORT = 'Unsupported operator: [%s]'
32 ERR_REL_NOT_IN = 'Expect "IN" after "not" operator.'
33 WRN_BOOL_EXPR = 'Operand of boolean type cannot be used in arithmetic expression.'
34 WRN_EQCMP_STR_OTHERS = '== Comparison between Operand of string type and Boolean/Number Type always return False.'
35 WRN_NECMP_STR_OTHERS = '!= Comparison between Operand of string type and Boolean/Number Type always return True.'
36 ERR_RELCMP_STR_OTHERS = 'Operator taking Operand of string type and Boolean/Number Type is not allowed: [%s].'
37 ERR_STRING_CMP = 'Unicode string and general string cannot be compared: [%s %s %s]'
38 ERR_ARRAY_TOKEN = 'Bad C array or C format GUID token: [%s].'
39 ERR_ARRAY_ELE = 'This must be HEX value for NList or Array: [%s].'
40 ERR_EMPTY_EXPR = 'Empty expression is not allowed.'
41 ERR_IN_OPERAND = 'Macro after IN operator can only be: $(FAMILY), $(ARCH), $(TOOL_CHAIN_TAG) and $(TARGET).'
42
43 ## SplitString
44 # Split string to list according double quote
45 # For example: abc"de\"f"ghi"jkl"mn will be: ['abc', '"de\"f"', 'ghi', '"jkl"', 'mn']
46 #
47 def SplitString(String):
48 # There might be escaped quote: "abc\"def\\\"ghi", 'abc\'def\\\'ghi'
49 Str = String
50 RetList = []
51 InSingleQuote = False
52 InDoubleQuote = False
53 Item = ''
54 for i, ch in enumerate(Str):
55 if ch == '"' and not InSingleQuote:
56 if Str[i - 1] != '\\':
57 InDoubleQuote = not InDoubleQuote
58 if not InDoubleQuote:
59 Item += String[i]
60 RetList.append(Item)
61 Item = ''
62 continue
63 if Item:
64 RetList.append(Item)
65 Item = ''
66 elif ch == "'" and not InDoubleQuote:
67 if Str[i - 1] != '\\':
68 InSingleQuote = not InSingleQuote
69 if not InSingleQuote:
70 Item += String[i]
71 RetList.append(Item)
72 Item = ''
73 continue
74 if Item:
75 RetList.append(Item)
76 Item = ''
77 Item += String[i]
78 if InSingleQuote or InDoubleQuote:
79 raise BadExpression(ERR_STRING_TOKEN % Item)
80 if Item:
81 RetList.append(Item)
82 return RetList
83
84 def SplitPcdValueString(String):
85 # There might be escaped comma in GUID() or DEVICE_PATH() or " "
86 # or ' ' or L' ' or L" "
87 Str = String
88 RetList = []
89 InParenthesis = 0
90 InSingleQuote = False
91 InDoubleQuote = False
92 Item = ''
93 for i, ch in enumerate(Str):
94 if ch == '(':
95 InParenthesis += 1
96 if ch == ')':
97 if InParenthesis:
98 InParenthesis -= 1
99 else:
100 raise BadExpression(ERR_STRING_TOKEN % Item)
101 if ch == '"' and not InSingleQuote:
102 if String[i-1] != '\\':
103 InDoubleQuote = not InDoubleQuote
104 if ch == "'" and not InDoubleQuote:
105 if String[i-1] != '\\':
106 InSingleQuote = not InSingleQuote
107 if ch == ',':
108 if InParenthesis or InSingleQuote or InDoubleQuote:
109 Item += String[i]
110 continue
111 elif Item:
112 RetList.append(Item)
113 Item = ''
114 continue
115 Item += String[i]
116 if InSingleQuote or InDoubleQuote or InParenthesis:
117 raise BadExpression(ERR_STRING_TOKEN % Item)
118 if Item:
119 RetList.append(Item)
120 return RetList
121
122 def IsValidCString(Str):
123 ValidString = re.compile(r'[_a-zA-Z][_0-9a-zA-Z]*$')
124 if not ValidString.match(Str):
125 return False
126 return True
127
128 def BuildOptionValue(PcdValue, GuidDict):
129 IsArray = False
130 if PcdValue.startswith('H'):
131 InputValue = PcdValue[1:]
132 elif PcdValue.startswith("L'") or PcdValue.startswith("'"):
133 InputValue = PcdValue
134 elif PcdValue.startswith('L'):
135 InputValue = 'L"' + PcdValue[1:] + '"'
136 else:
137 InputValue = PcdValue
138 if IsFieldValueAnArray(InputValue):
139 IsArray = True
140 if IsArray:
141 try:
142 PcdValue = ValueExpressionEx(InputValue, 'VOID*', GuidDict)(True)
143 except:
144 pass
145 return PcdValue
146
147 ## ReplaceExprMacro
148 #
149 def ReplaceExprMacro(String, Macros, ExceptionList = None):
150 StrList = SplitString(String)
151 for i, String in enumerate(StrList):
152 InQuote = False
153 if String.startswith('"'):
154 InQuote = True
155 MacroStartPos = String.find('$(')
156 if MacroStartPos < 0:
157 for Pcd in gPlatformPcds.keys():
158 if Pcd in String:
159 if Pcd not in gConditionalPcds:
160 gConditionalPcds.append(Pcd)
161 continue
162 RetStr = ''
163 while MacroStartPos >= 0:
164 RetStr = String[0:MacroStartPos]
165 MacroEndPos = String.find(')', MacroStartPos)
166 if MacroEndPos < 0:
167 raise BadExpression(ERR_MACRO_TOKEN % String[MacroStartPos:])
168 Macro = String[MacroStartPos+2:MacroEndPos]
169 if Macro not in Macros:
170 # From C reference manual:
171 # If an undefined macro name appears in the constant-expression of
172 # !if or !elif, it is replaced by the integer constant 0.
173 RetStr += '0'
174 elif not InQuote:
175 Tklst = RetStr.split()
176 if Tklst and Tklst[-1] in ['IN', 'in'] and ExceptionList and Macro not in ExceptionList:
177 raise BadExpression(ERR_IN_OPERAND)
178 # Make sure the macro in exception list is encapsulated by double quote
179 # For example: DEFINE ARCH = IA32 X64
180 # $(ARCH) is replaced with "IA32 X64"
181 if ExceptionList and Macro in ExceptionList:
182 RetStr += '"' + Macros[Macro] + '"'
183 elif Macros[Macro].strip():
184 RetStr += Macros[Macro]
185 else:
186 RetStr += '""'
187 else:
188 RetStr += Macros[Macro]
189 RetStr += String[MacroEndPos+1:]
190 String = RetStr
191 MacroStartPos = String.find('$(')
192 StrList[i] = RetStr
193 return ''.join(StrList)
194
195 # transfer int to string for in/not in expression
196 def IntToStr(Value):
197 StrList = []
198 while Value > 0:
199 StrList.append(chr(Value & 0xff))
200 Value = Value >> 8
201 Value = '"' + ''.join(StrList) + '"'
202 return Value
203
204 SupportedInMacroList = ['TARGET', 'TOOL_CHAIN_TAG', 'ARCH', 'FAMILY']
205
206 class ValueExpression(object):
207 # Logical operator mapping
208 LogicalOperators = {
209 '&&' : 'and', '||' : 'or',
210 '!' : 'not', 'AND': 'and',
211 'OR' : 'or' , 'NOT': 'not',
212 'XOR': '^' , 'xor': '^',
213 'EQ' : '==' , 'NE' : '!=',
214 'GT' : '>' , 'LT' : '<',
215 'GE' : '>=' , 'LE' : '<=',
216 'IN' : 'in'
217 }
218
219 NonLetterOpLst = ['+', '-', '*', '/', '%', '&', '|', '^', '~', '<<', '>>', '!', '=', '>', '<', '?', ':']
220
221 PcdPattern = re.compile(r'[_a-zA-Z][0-9A-Za-z_]*\.[_a-zA-Z][0-9A-Za-z_]*$')
222 HexPattern = re.compile(r'0[xX][0-9a-fA-F]+$')
223 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}')
224
225 SymbolPattern = re.compile("("
226 "\$\([A-Z][A-Z0-9_]*\)|\$\(\w+\.\w+\)|\w+\.\w+|"
227 "&&|\|\||!(?!=)|"
228 "(?<=\W)AND(?=\W)|(?<=\W)OR(?=\W)|(?<=\W)NOT(?=\W)|(?<=\W)XOR(?=\W)|"
229 "(?<=\W)EQ(?=\W)|(?<=\W)NE(?=\W)|(?<=\W)GT(?=\W)|(?<=\W)LT(?=\W)|(?<=\W)GE(?=\W)|(?<=\W)LE(?=\W)"
230 ")")
231
232 @staticmethod
233 def Eval(Operator, Oprand1, Oprand2 = None):
234 WrnExp = None
235
236 if Operator not in ["==", "!=", ">=", "<=", ">", "<", "in", "not in"] and \
237 (type(Oprand1) == type('') or type(Oprand2) == type('')):
238 raise BadExpression(ERR_STRING_EXPR % Operator)
239 if Operator in ['in', 'not in']:
240 if type(Oprand1) != type(''):
241 Oprand1 = IntToStr(Oprand1)
242 if type(Oprand2) != type(''):
243 Oprand2 = IntToStr(Oprand2)
244 TypeDict = {
245 type(0) : 0,
246 type(0L) : 0,
247 type('') : 1,
248 type(True) : 2
249 }
250
251 EvalStr = ''
252 if Operator in ["!", "NOT", "not"]:
253 if type(Oprand1) == type(''):
254 raise BadExpression(ERR_STRING_EXPR % Operator)
255 EvalStr = 'not Oprand1'
256 elif Operator in ["~"]:
257 if type(Oprand1) == type(''):
258 raise BadExpression(ERR_STRING_EXPR % Operator)
259 EvalStr = '~ Oprand1'
260 else:
261 if Operator in ["+", "-"] and (type(True) in [type(Oprand1), type(Oprand2)]):
262 # Boolean in '+'/'-' will be evaluated but raise warning
263 WrnExp = WrnExpression(WRN_BOOL_EXPR)
264 elif type('') in [type(Oprand1), type(Oprand2)] and type(Oprand1)!= type(Oprand2):
265 # == between string and number/boolean will always return False, != return True
266 if Operator == "==":
267 WrnExp = WrnExpression(WRN_EQCMP_STR_OTHERS)
268 WrnExp.result = False
269 raise WrnExp
270 elif Operator == "!=":
271 WrnExp = WrnExpression(WRN_NECMP_STR_OTHERS)
272 WrnExp.result = True
273 raise WrnExp
274 else:
275 raise BadExpression(ERR_RELCMP_STR_OTHERS % Operator)
276 elif TypeDict[type(Oprand1)] != TypeDict[type(Oprand2)]:
277 if Operator in ["==", "!=", ">=", "<=", ">", "<"] and set((TypeDict[type(Oprand1)], TypeDict[type(Oprand2)])) == set((TypeDict[type(True)], TypeDict[type(0)])):
278 # comparison between number and boolean is allowed
279 pass
280 elif Operator in ['&', '|', '^', "and", "or"] and set((TypeDict[type(Oprand1)], TypeDict[type(Oprand2)])) == set((TypeDict[type(True)], TypeDict[type(0)])):
281 # bitwise and logical operation between number and boolean is allowed
282 pass
283 else:
284 raise BadExpression(ERR_EXPR_TYPE)
285 if type(Oprand1) == type('') and type(Oprand2) == type(''):
286 if (Oprand1.startswith('L"') and not Oprand2.startswith('L"')) or \
287 (not Oprand1.startswith('L"') and Oprand2.startswith('L"')):
288 raise BadExpression(ERR_STRING_CMP % (Oprand1, Operator, Oprand2))
289 if 'in' in Operator and type(Oprand2) == type(''):
290 Oprand2 = Oprand2.split()
291 EvalStr = 'Oprand1 ' + Operator + ' Oprand2'
292
293 # Local symbols used by built in eval function
294 Dict = {
295 'Oprand1' : Oprand1,
296 'Oprand2' : Oprand2
297 }
298 try:
299 Val = eval(EvalStr, {}, Dict)
300 except Exception, Excpt:
301 raise BadExpression(str(Excpt))
302
303 if Operator in ['and', 'or']:
304 if Val:
305 Val = True
306 else:
307 Val = False
308
309 if WrnExp:
310 WrnExp.result = Val
311 raise WrnExp
312 return Val
313
314 def __init__(self, Expression, SymbolTable={}):
315 self._NoProcess = False
316 if type(Expression) != type(''):
317 self._Expr = Expression
318 self._NoProcess = True
319 return
320
321 self._Expr = ReplaceExprMacro(Expression.strip(),
322 SymbolTable,
323 SupportedInMacroList)
324
325 if not self._Expr.strip():
326 raise BadExpression(ERR_EMPTY_EXPR)
327
328 #
329 # The symbol table including PCD and macro mapping
330 #
331 self._Symb = copy.deepcopy(SymbolTable)
332 self._Symb.update(self.LogicalOperators)
333 self._Idx = 0
334 self._Len = len(self._Expr)
335 self._Token = ''
336 self._WarnExcept = None
337
338 # Literal token without any conversion
339 self._LiteralToken = ''
340
341 # Public entry for this class
342 # @param RealValue: False: only evaluate if the expression is true or false, used for conditional expression
343 # True : return the evaluated str(value), used for PCD value
344 #
345 # @return: True or False if RealValue is False
346 # Evaluated value of string format if RealValue is True
347 #
348 def __call__(self, RealValue=False, Depth=0):
349 if self._NoProcess:
350 return self._Expr
351
352 self._Depth = Depth
353
354 self._Expr = self._Expr.strip()
355 if RealValue and Depth == 0:
356 self._Token = self._Expr
357 if self.__IsNumberToken():
358 return self._Expr
359 Token = ''
360 try:
361 Token = self._GetToken()
362 except BadExpression:
363 pass
364 if type(Token) == type('') and Token.startswith('{') and Token.endswith('}') and self._Idx >= self._Len:
365 return self._Expr
366
367 self._Idx = 0
368 self._Token = ''
369
370 Val = self._ConExpr()
371 RealVal = Val
372 if type(Val) == type(''):
373 if Val == 'L""':
374 Val = False
375 elif not Val:
376 Val = False
377 RealVal = '""'
378 elif not Val.startswith('L"') and not Val.startswith('{') and not Val.startswith("L'"):
379 Val = True
380 RealVal = '"' + RealVal + '"'
381
382 # The expression has been parsed, but the end of expression is not reached
383 # It means the rest does not comply EBNF of <Expression>
384 if self._Idx != self._Len:
385 raise BadExpression(ERR_SNYTAX % self._Expr[self._Idx:])
386
387 if RealValue:
388 RetVal = str(RealVal)
389 elif Val:
390 RetVal = True
391 else:
392 RetVal = False
393
394 if self._WarnExcept:
395 self._WarnExcept.result = RetVal
396 raise self._WarnExcept
397 else:
398 return RetVal
399
400 # Template function to parse binary operators which have same precedence
401 # Expr [Operator Expr]*
402 def _ExprFuncTemplate(self, EvalFunc, OpLst):
403 Val = EvalFunc()
404 while self._IsOperator(OpLst):
405 Op = self._Token
406 if Op == '?':
407 Val2 = EvalFunc()
408 if self._IsOperator(':'):
409 Val3 = EvalFunc()
410 if Val:
411 Val = Val2
412 else:
413 Val = Val3
414 continue
415 try:
416 Val = self.Eval(Op, Val, EvalFunc())
417 except WrnExpression, Warn:
418 self._WarnExcept = Warn
419 Val = Warn.result
420 return Val
421 # A [? B]*
422 def _ConExpr(self):
423 return self._ExprFuncTemplate(self._OrExpr, ['?', ':'])
424
425 # A [|| B]*
426 def _OrExpr(self):
427 return self._ExprFuncTemplate(self._AndExpr, ["OR", "or", "||"])
428
429 # A [&& B]*
430 def _AndExpr(self):
431 return self._ExprFuncTemplate(self._BitOr, ["AND", "and", "&&"])
432
433 # A [ | B]*
434 def _BitOr(self):
435 return self._ExprFuncTemplate(self._BitXor, ["|"])
436
437 # A [ ^ B]*
438 def _BitXor(self):
439 return self._ExprFuncTemplate(self._BitAnd, ["XOR", "xor", "^"])
440
441 # A [ & B]*
442 def _BitAnd(self):
443 return self._ExprFuncTemplate(self._EqExpr, ["&"])
444
445 # A [ == B]*
446 def _EqExpr(self):
447 Val = self._RelExpr()
448 while self._IsOperator(["==", "!=", "EQ", "NE", "IN", "in", "!", "NOT", "not"]):
449 Op = self._Token
450 if Op in ["!", "NOT", "not"]:
451 if not self._IsOperator(["IN", "in"]):
452 raise BadExpression(ERR_REL_NOT_IN)
453 Op += ' ' + self._Token
454 try:
455 Val = self.Eval(Op, Val, self._RelExpr())
456 except WrnExpression, Warn:
457 self._WarnExcept = Warn
458 Val = Warn.result
459 return Val
460
461 # A [ > B]*
462 def _RelExpr(self):
463 return self._ExprFuncTemplate(self._ShiftExpr, ["<=", ">=", "<", ">", "LE", "GE", "LT", "GT"])
464
465 def _ShiftExpr(self):
466 return self._ExprFuncTemplate(self._AddExpr, ["<<", ">>"])
467
468 # A [ + B]*
469 def _AddExpr(self):
470 return self._ExprFuncTemplate(self._MulExpr, ["+", "-"])
471
472 # A [ * B]*
473 def _MulExpr(self):
474 return self._ExprFuncTemplate(self._UnaryExpr, ["*", "/", "%"])
475
476 # [!]*A
477 def _UnaryExpr(self):
478 if self._IsOperator(["!", "NOT", "not"]):
479 Val = self._UnaryExpr()
480 try:
481 return self.Eval('not', Val)
482 except WrnExpression, Warn:
483 self._WarnExcept = Warn
484 return Warn.result
485 if self._IsOperator(["~"]):
486 Val = self._UnaryExpr()
487 try:
488 return self.Eval('~', Val)
489 except WrnExpression, Warn:
490 self._WarnExcept = Warn
491 return Warn.result
492 return self._IdenExpr()
493
494 # Parse identifier or encapsulated expression
495 def _IdenExpr(self):
496 Tk = self._GetToken()
497 if Tk == '(':
498 Val = self._ConExpr()
499 try:
500 # _GetToken may also raise BadExpression
501 if self._GetToken() != ')':
502 raise BadExpression(ERR_MATCH)
503 except BadExpression:
504 raise BadExpression(ERR_MATCH)
505 return Val
506 return Tk
507
508 # Skip whitespace or tab
509 def __SkipWS(self):
510 for Char in self._Expr[self._Idx:]:
511 if Char not in ' \t':
512 break
513 self._Idx += 1
514
515 # Try to convert string to number
516 def __IsNumberToken(self):
517 Radix = 10
518 if self._Token.lower()[0:2] == '0x' and len(self._Token) > 2:
519 Radix = 16
520 if self._Token.startswith('"') or self._Token.startswith('L"'):
521 Flag = 0
522 for Index in range(len(self._Token)):
523 if self._Token[Index] in ['"']:
524 if self._Token[Index - 1] == '\\':
525 continue
526 Flag += 1
527 if Flag == 2 and self._Token.endswith('"'):
528 return True
529 if self._Token.startswith("'") or self._Token.startswith("L'"):
530 Flag = 0
531 for Index in range(len(self._Token)):
532 if self._Token[Index] in ["'"]:
533 if self._Token[Index - 1] == '\\':
534 continue
535 Flag += 1
536 if Flag == 2 and self._Token.endswith("'"):
537 return True
538 try:
539 self._Token = int(self._Token, Radix)
540 return True
541 except ValueError:
542 return False
543 except TypeError:
544 return False
545
546 # Parse array: {...}
547 def __GetArray(self):
548 Token = '{'
549 self._Idx += 1
550 self.__GetNList(True)
551 Token += self._LiteralToken
552 if self._Idx >= self._Len or self._Expr[self._Idx] != '}':
553 raise BadExpression(ERR_ARRAY_TOKEN % Token)
554 Token += '}'
555
556 # All whitespace and tabs in array are already stripped.
557 IsArray = IsGuid = False
558 if len(Token.split(',')) == 11 and len(Token.split(',{')) == 2 \
559 and len(Token.split('},')) == 1:
560 HexLen = [11,6,6,5,4,4,4,4,4,4,6]
561 HexList= Token.split(',')
562 if HexList[3].startswith('{') and \
563 not [Index for Index, Hex in enumerate(HexList) if len(Hex) > HexLen[Index]]:
564 IsGuid = True
565 if Token.lstrip('{').rstrip('}').find('{') == -1:
566 if not [Hex for Hex in Token.lstrip('{').rstrip('}').split(',') if len(Hex) > 4]:
567 IsArray = True
568 if not IsArray and not IsGuid:
569 raise BadExpression(ERR_ARRAY_TOKEN % Token)
570 self._Idx += 1
571 self._Token = self._LiteralToken = Token
572 return self._Token
573
574 # Parse string, the format must be: "..."
575 def __GetString(self):
576 Idx = self._Idx
577
578 # Skip left quote
579 self._Idx += 1
580
581 # Replace escape \\\", \"
582 if self._Expr[Idx] == '"':
583 Expr = self._Expr[self._Idx:].replace('\\\\', '//').replace('\\\"', '\\\'')
584 for Ch in Expr:
585 self._Idx += 1
586 if Ch == '"':
587 break
588 self._Token = self._LiteralToken = self._Expr[Idx:self._Idx]
589 if not self._Token.endswith('"'):
590 raise BadExpression(ERR_STRING_TOKEN % self._Token)
591 #Replace escape \\\', \'
592 elif self._Expr[Idx] == "'":
593 Expr = self._Expr[self._Idx:].replace('\\\\', '//').replace("\\\'", "\\\"")
594 for Ch in Expr:
595 self._Idx += 1
596 if Ch == "'":
597 break
598 self._Token = self._LiteralToken = self._Expr[Idx:self._Idx]
599 if not self._Token.endswith("'"):
600 raise BadExpression(ERR_STRING_TOKEN % self._Token)
601 self._Token = self._Token[1:-1]
602 return self._Token
603
604 # Get token that is comprised by alphanumeric, underscore or dot(used by PCD)
605 # @param IsAlphaOp: Indicate if parsing general token or script operator(EQ, NE...)
606 def __GetIdToken(self, IsAlphaOp = False):
607 IdToken = ''
608 for Ch in self._Expr[self._Idx:]:
609 if not self.__IsIdChar(Ch) or ('?' in self._Expr and Ch == ':'):
610 break
611 self._Idx += 1
612 IdToken += Ch
613
614 self._Token = self._LiteralToken = IdToken
615 if not IsAlphaOp:
616 self.__ResolveToken()
617 return self._Token
618
619 # Try to resolve token
620 def __ResolveToken(self):
621 if not self._Token:
622 raise BadExpression(ERR_EMPTY_TOKEN)
623
624 # PCD token
625 if self.PcdPattern.match(self._Token):
626 if self._Token not in self._Symb:
627 Ex = BadExpression(ERR_PCD_RESOLVE % self._Token)
628 Ex.Pcd = self._Token
629 raise Ex
630 self._Token = ValueExpression(self._Symb[self._Token], self._Symb)(True, self._Depth+1)
631 if type(self._Token) != type(''):
632 self._LiteralToken = hex(self._Token)
633 return
634
635 if self._Token.startswith('"'):
636 self._Token = self._Token[1:-1]
637 elif self._Token in ["FALSE", "false", "False"]:
638 self._Token = False
639 elif self._Token in ["TRUE", "true", "True"]:
640 self._Token = True
641 else:
642 self.__IsNumberToken()
643
644 def __GetNList(self, InArray=False):
645 self._GetSingleToken()
646 if not self.__IsHexLiteral():
647 if InArray:
648 raise BadExpression(ERR_ARRAY_ELE % self._Token)
649 return self._Token
650
651 self.__SkipWS()
652 Expr = self._Expr[self._Idx:]
653 if not Expr.startswith(','):
654 return self._Token
655
656 NList = self._LiteralToken
657 while Expr.startswith(','):
658 NList += ','
659 self._Idx += 1
660 self.__SkipWS()
661 self._GetSingleToken()
662 if not self.__IsHexLiteral():
663 raise BadExpression(ERR_ARRAY_ELE % self._Token)
664 NList += self._LiteralToken
665 self.__SkipWS()
666 Expr = self._Expr[self._Idx:]
667 self._Token = self._LiteralToken = NList
668 return self._Token
669
670 def __IsHexLiteral(self):
671 if self._LiteralToken.startswith('{') and \
672 self._LiteralToken.endswith('}'):
673 return True
674
675 if self.HexPattern.match(self._LiteralToken):
676 Token = self._LiteralToken[2:]
677 if not Token:
678 self._LiteralToken = '0x0'
679 else:
680 self._LiteralToken = '0x' + Token
681 return True
682 return False
683
684 def _GetToken(self):
685 return self.__GetNList()
686
687 @staticmethod
688 def __IsIdChar(Ch):
689 return Ch in '._:' or Ch.isalnum()
690
691 # Parse operand
692 def _GetSingleToken(self):
693 self.__SkipWS()
694 Expr = self._Expr[self._Idx:]
695 if Expr.startswith('L"'):
696 # Skip L
697 self._Idx += 1
698 UStr = self.__GetString()
699 self._Token = 'L"' + UStr + '"'
700 return self._Token
701 elif Expr.startswith("L'"):
702 # Skip L
703 self._Idx += 1
704 UStr = self.__GetString()
705 self._Token = "L'" + UStr + "'"
706 return self._Token
707 elif Expr.startswith("'"):
708 UStr = self.__GetString()
709 self._Token = "'" + UStr + "'"
710 return self._Token
711 elif Expr.startswith('UINT'):
712 Re = re.compile('(?:UINT8|UINT16|UINT32|UINT64)\((.+)\)')
713 try:
714 RetValue = Re.search(Expr).group(1)
715 except:
716 raise BadExpression('Invalid Expression %s' % Expr)
717 Idx = self._Idx
718 for Ch in Expr:
719 self._Idx += 1
720 if Ch == '(':
721 Prefix = self._Expr[Idx:self._Idx - 1]
722 Idx = self._Idx
723 if Ch == ')':
724 TmpValue = self._Expr[Idx :self._Idx - 1]
725 TmpValue = ValueExpression(TmpValue)(True)
726 TmpValue = '0x%x' % int(TmpValue) if type(TmpValue) != type('') else TmpValue
727 break
728 self._Token, Size = ParseFieldValue(Prefix + '(' + TmpValue + ')')
729 return self._Token
730
731 self._Token = ''
732 if Expr:
733 Ch = Expr[0]
734 Match = self.RegGuidPattern.match(Expr)
735 if Match and not Expr[Match.end():Match.end()+1].isalnum() \
736 and Expr[Match.end():Match.end()+1] != '_':
737 self._Idx += Match.end()
738 self._Token = ValueExpression(GuidStringToGuidStructureString(Expr[0:Match.end()]))(True, self._Depth+1)
739 return self._Token
740 elif self.__IsIdChar(Ch):
741 return self.__GetIdToken()
742 elif Ch == '"':
743 return self.__GetString()
744 elif Ch == '{':
745 return self.__GetArray()
746 elif Ch == '(' or Ch == ')':
747 self._Idx += 1
748 self._Token = Ch
749 return self._Token
750
751 raise BadExpression(ERR_VALID_TOKEN % Expr)
752
753 # Parse operator
754 def _GetOperator(self):
755 self.__SkipWS()
756 LegalOpLst = ['&&', '||', '!=', '==', '>=', '<='] + self.NonLetterOpLst + ['?',':']
757
758 self._Token = ''
759 Expr = self._Expr[self._Idx:]
760
761 # Reach end of expression
762 if not Expr:
763 return ''
764
765 # Script operator: LT, GT, LE, GE, EQ, NE, and, or, xor, not
766 if Expr[0].isalpha():
767 return self.__GetIdToken(True)
768
769 # Start to get regular operator: +, -, <, > ...
770 if Expr[0] not in self.NonLetterOpLst:
771 return ''
772
773 OpToken = ''
774 for Ch in Expr:
775 if Ch in self.NonLetterOpLst:
776 if '!' == Ch and OpToken:
777 break
778 self._Idx += 1
779 OpToken += Ch
780 else:
781 break
782
783 if OpToken not in LegalOpLst:
784 raise BadExpression(ERR_OPERATOR_UNSUPPORT % OpToken)
785 self._Token = OpToken
786 return OpToken
787
788 # Check if current token matches the operators given from OpList
789 def _IsOperator(self, OpList):
790 Idx = self._Idx
791 self._GetOperator()
792 if self._Token in OpList:
793 if self._Token in self.LogicalOperators:
794 self._Token = self.LogicalOperators[self._Token]
795 return True
796 self._Idx = Idx
797 return False
798
799 class ValueExpressionEx(ValueExpression):
800 def __init__(self, PcdValue, PcdType, SymbolTable={}):
801 ValueExpression.__init__(self, PcdValue, SymbolTable)
802 self.PcdValue = PcdValue
803 self.PcdType = PcdType
804
805 def __call__(self, RealValue=False, Depth=0):
806 PcdValue = self.PcdValue
807 try:
808 PcdValue = ValueExpression.__call__(self, RealValue, Depth)
809 if self.PcdType == 'VOID*' and (PcdValue.startswith("'") or PcdValue.startswith("L'")):
810 PcdValue, Size = ParseFieldValue(PcdValue)
811 PcdValueList = []
812 for I in range(Size):
813 PcdValueList.append('0x%02X'%(PcdValue & 0xff))
814 PcdValue = PcdValue >> 8
815 PcdValue = '{' + ','.join(PcdValueList) + '}'
816 elif self.PcdType in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN'] and (PcdValue.startswith("'") or \
817 PcdValue.startswith('"') or PcdValue.startswith("L'") or PcdValue.startswith('L"') or PcdValue.startswith('{')):
818 raise BadExpression
819 except WrnExpression, Value:
820 PcdValue = Value.result
821 except BadExpression, Value:
822 if self.PcdType in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN']:
823 PcdValue = PcdValue.strip()
824 if type(PcdValue) == type('') and PcdValue.startswith('{') and PcdValue.endswith('}'):
825 PcdValue = SplitPcdValueString(PcdValue[1:-1])
826 if type(PcdValue) == type([]):
827 TmpValue = 0
828 Size = 0
829 ValueType = ''
830 for Item in PcdValue:
831 Item = Item.strip()
832 if Item.startswith('UINT8'):
833 ItemSize = 1
834 ValueType = 'UINT8'
835 elif Item.startswith('UINT16'):
836 ItemSize = 2
837 ValueType = 'UINT16'
838 elif Item.startswith('UINT32'):
839 ItemSize = 4
840 ValueType = 'UINT32'
841 elif Item.startswith('UINT64'):
842 ItemSize = 8
843 ValueType = 'UINT64'
844 elif Item.startswith('"') or Item.startswith("'") or Item.startswith('L'):
845 ItemSize = 0
846 ValueType = 'VOID*'
847 else:
848 ItemSize = 0
849 ValueType = 'UINT8'
850 Item = ValueExpressionEx(Item, ValueType, self._Symb)(True)
851
852 if ItemSize == 0:
853 try:
854 tmpValue = int(Item, 16) if Item.upper().startswith('0X') else int(Item, 0)
855 if tmpValue > 255:
856 raise BadExpression("Byte array number %s should less than 0xFF." % Item)
857 except BadExpression, Value:
858 raise BadExpression(Value)
859 except ValueError:
860 pass
861 ItemValue, ItemSize = ParseFieldValue(Item)
862 else:
863 ItemValue = ParseFieldValue(Item)[0]
864
865 if type(ItemValue) == type(''):
866 ItemValue = int(ItemValue, 16) if ItemValue.startswith('0x') else int(ItemValue)
867
868 TmpValue = (ItemValue << (Size * 8)) | TmpValue
869 Size = Size + ItemSize
870 else:
871 try:
872 TmpValue, Size = ParseFieldValue(PcdValue)
873 except BadExpression, Value:
874 raise BadExpression("Type: %s, Value: %s, %s" % (self.PcdType, PcdValue, Value))
875 if type(TmpValue) == type(''):
876 try:
877 TmpValue = int(TmpValue)
878 except:
879 raise BadExpression(Value)
880 else:
881 PcdValue = '0x%0{}X'.format(Size) % (TmpValue)
882 if TmpValue < 0:
883 raise BadExpression('Type %s PCD Value is negative' % self.PcdType)
884 if self.PcdType == 'UINT8' and Size > 1:
885 raise BadExpression('Type %s PCD Value Size is Larger than 1 byte' % self.PcdType)
886 if self.PcdType == 'UINT16' and Size > 2:
887 raise BadExpression('Type %s PCD Value Size is Larger than 2 byte' % self.PcdType)
888 if self.PcdType == 'UINT32' and Size > 4:
889 raise BadExpression('Type %s PCD Value Size is Larger than 4 byte' % self.PcdType)
890 if self.PcdType == 'UINT64' and Size > 8:
891 raise BadExpression('Type %s PCD Value Size is Larger than 8 byte' % self.PcdType)
892 else:
893 try:
894 TmpValue = long(PcdValue)
895 TmpList = []
896 if TmpValue.bit_length() == 0:
897 PcdValue = '{0x00}'
898 else:
899 for I in range((TmpValue.bit_length() + 7) / 8):
900 TmpList.append('0x%02x' % ((TmpValue >> I * 8) & 0xff))
901 PcdValue = '{' + ', '.join(TmpList) + '}'
902 except:
903 if PcdValue.strip().startswith('{'):
904 PcdValueList = SplitPcdValueString(PcdValue.strip()[1:-1])
905 LabelDict = {}
906 NewPcdValueList = []
907 ReLabel = re.compile('LABEL\((\w+)\)')
908 ReOffset = re.compile('OFFSET_OF\((\w+)\)')
909 LabelOffset = 0
910 for Index, Item in enumerate(PcdValueList):
911 # compute byte offset of every LABEL
912 Item = Item.strip()
913 LabelList = ReLabel.findall(Item)
914 if LabelList:
915 for Label in LabelList:
916 if not IsValidCString(Label):
917 raise BadExpression('%s is not a valid c variable name' % Label)
918 if Label not in LabelDict.keys():
919 LabelDict[Label] = str(LabelOffset)
920 if Item.startswith('UINT8'):
921 LabelOffset = LabelOffset + 1
922 elif Item.startswith('UINT16'):
923 LabelOffset = LabelOffset + 2
924 elif Item.startswith('UINT32'):
925 LabelOffset = LabelOffset + 4
926 elif Item.startswith('UINT64'):
927 LabelOffset = LabelOffset + 8
928 else:
929 try:
930 ItemValue, ItemSize = ParseFieldValue(Item)
931 LabelOffset = LabelOffset + ItemSize
932 except:
933 LabelOffset = LabelOffset + 1
934
935 for Index, Item in enumerate(PcdValueList):
936 # for LABEL parse
937 Item = Item.strip()
938 try:
939 Item = ReLabel.sub('', Item)
940 except:
941 pass
942 try:
943 OffsetList = ReOffset.findall(Item)
944 except:
945 pass
946 for Offset in OffsetList:
947 if Offset in LabelDict.keys():
948 Re = re.compile('OFFSET_OF\(%s\)' % Offset)
949 Item = Re.sub(LabelDict[Offset], Item)
950 else:
951 raise BadExpression('%s not defined' % Offset)
952 NewPcdValueList.append(Item)
953
954 AllPcdValueList = []
955 for Item in NewPcdValueList:
956 Size = 0
957 ValueStr = ''
958 TokenSpaceGuidName = ''
959 if Item.startswith('GUID') and Item.endswith(')'):
960 try:
961 TokenSpaceGuidName = re.search('GUID\((\w+)\)', Item).group(1)
962 except:
963 pass
964 if TokenSpaceGuidName and TokenSpaceGuidName in self._Symb:
965 Item = 'GUID(' + self._Symb[TokenSpaceGuidName] + ')'
966 elif TokenSpaceGuidName:
967 raise BadExpression('%s not found in DEC file' % TokenSpaceGuidName)
968 Item, Size = ParseFieldValue(Item)
969 for Index in range(0, Size):
970 ValueStr = '0x%02X' % (int(Item) & 255)
971 Item >>= 8
972 AllPcdValueList.append(ValueStr)
973 continue
974 elif Item.startswith('DEVICE_PATH') and Item.endswith(')'):
975 Item, Size = ParseFieldValue(Item)
976 AllPcdValueList.append(Item[1:-1])
977 continue
978 else:
979 ValueType = ""
980 if Item.startswith('UINT8'):
981 ItemSize = 1
982 ValueType = "UINT8"
983 elif Item.startswith('UINT16'):
984 ItemSize = 2
985 ValueType = "UINT16"
986 elif Item.startswith('UINT32'):
987 ItemSize = 4
988 ValueType = "UINT32"
989 elif Item.startswith('UINT64'):
990 ItemSize = 8
991 ValueType = "UINT64"
992 else:
993 ItemSize = 0
994 if ValueType:
995 TmpValue = ValueExpressionEx(Item, ValueType, self._Symb)(True)
996 else:
997 TmpValue = ValueExpressionEx(Item, self.PcdType, self._Symb)(True)
998 Item = '0x%x' % TmpValue if type(TmpValue) != type('') else TmpValue
999 if ItemSize == 0:
1000 ItemValue, ItemSize = ParseFieldValue(Item)
1001 if not (Item.startswith('"') or Item.startswith('L') or Item.startswith('{')) and ItemSize > 1:
1002 raise BadExpression("Byte array number %s should less than 0xFF." % Item)
1003 else:
1004 ItemValue = ParseFieldValue(Item)[0]
1005 for I in range(0, ItemSize):
1006 ValueStr = '0x%02X' % (int(ItemValue) & 255)
1007 ItemValue >>= 8
1008 AllPcdValueList.append(ValueStr)
1009 Size += ItemSize
1010
1011 if Size > 0:
1012 PcdValue = '{' + ','.join(AllPcdValueList) + '}'
1013 else:
1014 raise BadExpression("Type: %s, Value: %s, %s"%(self.PcdType, PcdValue, Value))
1015
1016 if PcdValue == 'True':
1017 PcdValue = '1'
1018 if PcdValue == 'False':
1019 PcdValue = '0'
1020
1021 if RealValue:
1022 return PcdValue
1023
1024 if __name__ == '__main__':
1025 pass
1026 while True:
1027 input = raw_input('Input expr: ')
1028 if input in 'qQ':
1029 break
1030 try:
1031 print ValueExpression(input)(True)
1032 print ValueExpression(input)(False)
1033 except WrnExpression, Ex:
1034 print Ex.result
1035 print str(Ex)
1036 except Exception, Ex:
1037 print str(Ex)