2 # This file is used to parse and evaluate expression in directive or PCD value.
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
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.
15 from Common
.GlobalData
import *
16 from CommonDataClass
.Exceptions
import BadExpression
17 from CommonDataClass
.Exceptions
import WrnExpression
18 from Misc
import GuidStringToGuidStructureString
, ParseFieldValue
19 import Common
.EdkLogger
as EdkLogger
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).'
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']
47 def SplitString(String
):
48 # There might be escaped quote: "abc\"def\\\"ghi", 'abc\'def\\\'ghi'
54 for i
, ch
in enumerate(Str
):
55 if ch
== '"' and not InSingleQuote
:
56 if Str
[i
- 1] != '\\':
57 InDoubleQuote
= not InDoubleQuote
66 elif ch
== "'" and not InDoubleQuote
:
67 if Str
[i
- 1] != '\\':
68 InSingleQuote
= not InSingleQuote
78 if InSingleQuote
or InDoubleQuote
:
79 raise BadExpression(ERR_STRING_TOKEN
% Item
)
84 def SplitPcdValueString(String
):
85 # There might be escaped comma in GUID() or DEVICE_PATH() or " "
86 # or ' ' or L' ' or L" "
93 for i
, ch
in enumerate(Str
):
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
108 if InParenthesis
or InSingleQuote
or InDoubleQuote
:
116 if InSingleQuote
or InDoubleQuote
or InParenthesis
:
117 raise BadExpression(ERR_STRING_TOKEN
% Item
)
124 def ReplaceExprMacro(String
, Macros
, ExceptionList
= None):
125 StrList
= SplitString(String
)
126 for i
, String
in enumerate(StrList
):
128 if String
.startswith('"'):
130 MacroStartPos
= String
.find('$(')
131 if MacroStartPos
< 0:
132 for Pcd
in gPlatformPcds
.keys():
134 if Pcd
not in gConditionalPcds
:
135 gConditionalPcds
.append(Pcd
)
138 while MacroStartPos
>= 0:
139 RetStr
= String
[0:MacroStartPos
]
140 MacroEndPos
= String
.find(')', MacroStartPos
)
142 raise BadExpression(ERR_MACRO_TOKEN
% String
[MacroStartPos
:])
143 Macro
= String
[MacroStartPos
+2:MacroEndPos
]
144 if Macro
not in Macros
:
145 # From C reference manual:
146 # If an undefined macro name appears in the constant-expression of
147 # !if or !elif, it is replaced by the integer constant 0.
150 Tklst
= RetStr
.split()
151 if Tklst
and Tklst
[-1] in ['IN', 'in'] and ExceptionList
and Macro
not in ExceptionList
:
152 raise BadExpression(ERR_IN_OPERAND
)
153 # Make sure the macro in exception list is encapsulated by double quote
154 # For example: DEFINE ARCH = IA32 X64
155 # $(ARCH) is replaced with "IA32 X64"
156 if ExceptionList
and Macro
in ExceptionList
:
157 RetStr
+= '"' + Macros
[Macro
] + '"'
158 elif Macros
[Macro
].strip():
159 RetStr
+= Macros
[Macro
]
163 RetStr
+= Macros
[Macro
]
164 RetStr
+= String
[MacroEndPos
+1:]
166 MacroStartPos
= String
.find('$(')
168 return ''.join(StrList
)
170 # transfer int to string for in/not in expression
174 StrList
.append(chr(Value
& 0xff))
176 Value
= '"' + ''.join(StrList
) + '"'
179 SupportedInMacroList
= ['TARGET', 'TOOL_CHAIN_TAG', 'ARCH', 'FAMILY']
181 class ValueExpression(object):
182 # Logical operator mapping
184 '&&' : 'and', '||' : 'or',
185 '!' : 'not', 'AND': 'and',
186 'OR' : 'or' , 'NOT': 'not',
187 'XOR': '^' , 'xor': '^',
188 'EQ' : '==' , 'NE' : '!=',
189 'GT' : '>' , 'LT' : '<',
190 'GE' : '>=' , 'LE' : '<=',
194 NonLetterOpLst
= ['+', '-', '*', '/', '%', '&', '|', '^', '~', '<<', '>>', '!', '=', '>', '<', '?', ':']
196 PcdPattern
= re
.compile(r
'[_a-zA-Z][0-9A-Za-z_]*\.[_a-zA-Z][0-9A-Za-z_]*$')
197 HexPattern
= re
.compile(r
'0[xX][0-9a-fA-F]+$')
198 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}')
200 SymbolPattern
= re
.compile("("
201 "\$\([A-Z][A-Z0-9_]*\)|\$\(\w+\.\w+\)|\w+\.\w+|"
203 "(?<=\W)AND(?=\W)|(?<=\W)OR(?=\W)|(?<=\W)NOT(?=\W)|(?<=\W)XOR(?=\W)|"
204 "(?<=\W)EQ(?=\W)|(?<=\W)NE(?=\W)|(?<=\W)GT(?=\W)|(?<=\W)LT(?=\W)|(?<=\W)GE(?=\W)|(?<=\W)LE(?=\W)"
208 def Eval(Operator
, Oprand1
, Oprand2
= None):
211 if Operator
not in ["==", "!=", ">=", "<=", ">", "<", "in", "not in"] and \
212 (type(Oprand1
) == type('') or type(Oprand2
) == type('')):
213 raise BadExpression(ERR_STRING_EXPR
% Operator
)
214 if Operator
in ['in', 'not in']:
215 if type(Oprand1
) != type(''):
216 Oprand1
= IntToStr(Oprand1
)
217 if type(Oprand2
) != type(''):
218 Oprand2
= IntToStr(Oprand2
)
227 if Operator
in ["!", "NOT", "not"]:
228 if type(Oprand1
) == type(''):
229 raise BadExpression(ERR_STRING_EXPR
% Operator
)
230 EvalStr
= 'not Oprand1'
231 elif Operator
in ["~"]:
232 if type(Oprand1
) == type(''):
233 raise BadExpression(ERR_STRING_EXPR
% Operator
)
234 EvalStr
= '~ Oprand1'
236 if Operator
in ["+", "-"] and (type(True) in [type(Oprand1
), type(Oprand2
)]):
237 # Boolean in '+'/'-' will be evaluated but raise warning
238 WrnExp
= WrnExpression(WRN_BOOL_EXPR
)
239 elif type('') in [type(Oprand1
), type(Oprand2
)] and type(Oprand1
)!= type(Oprand2
):
240 # == between string and number/boolean will always return False, != return True
242 WrnExp
= WrnExpression(WRN_EQCMP_STR_OTHERS
)
243 WrnExp
.result
= False
245 elif Operator
== "!=":
246 WrnExp
= WrnExpression(WRN_NECMP_STR_OTHERS
)
250 raise BadExpression(ERR_RELCMP_STR_OTHERS
% Operator
)
251 elif TypeDict
[type(Oprand1
)] != TypeDict
[type(Oprand2
)]:
252 if Operator
in ["==", "!=", ">=", "<=", ">", "<"] and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
253 # comparison between number and boolean is allowed
255 elif Operator
in ['&', '|', '^', "and", "or"] and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
256 # bitwise and logical operation between number and boolean is allowed
259 raise BadExpression(ERR_EXPR_TYPE
)
260 if type(Oprand1
) == type('') and type(Oprand2
) == type(''):
261 if (Oprand1
.startswith('L"') and not Oprand2
.startswith('L"')) or \
262 (not Oprand1
.startswith('L"') and Oprand2
.startswith('L"')):
263 raise BadExpression(ERR_STRING_CMP
% (Oprand1
, Operator
, Oprand2
))
264 if 'in' in Operator
and type(Oprand2
) == type(''):
265 Oprand2
= Oprand2
.split()
266 EvalStr
= 'Oprand1 ' + Operator
+ ' Oprand2'
268 # Local symbols used by built in eval function
274 Val
= eval(EvalStr
, {}, Dict
)
275 except Exception, Excpt
:
276 raise BadExpression(str(Excpt
))
278 if Operator
in ['and', 'or']:
289 def __init__(self
, Expression
, SymbolTable
={}):
290 self
._NoProcess
= False
291 if type(Expression
) != type(''):
292 self
._Expr
= Expression
293 self
._NoProcess
= True
296 self
._Expr
= ReplaceExprMacro(Expression
.strip(),
298 SupportedInMacroList
)
300 if not self
._Expr
.strip():
301 raise BadExpression(ERR_EMPTY_EXPR
)
304 # The symbol table including PCD and macro mapping
306 self
._Symb
= copy
.deepcopy(SymbolTable
)
307 self
._Symb
.update(self
.LogicalOperators
)
309 self
._Len
= len(self
._Expr
)
311 self
._WarnExcept
= None
313 # Literal token without any conversion
314 self
._LiteralToken
= ''
316 # Public entry for this class
317 # @param RealValue: False: only evaluate if the expression is true or false, used for conditional expression
318 # True : return the evaluated str(value), used for PCD value
320 # @return: True or False if RealValue is False
321 # Evaluated value of string format if RealValue is True
323 def __call__(self
, RealValue
=False, Depth
=0):
329 self
._Expr
= self
._Expr
.strip()
330 if RealValue
and Depth
== 0:
331 self
._Token
= self
._Expr
332 if self
.__IsNumberToken
():
336 Token
= self
._GetToken
()
337 except BadExpression
:
339 if type(Token
) == type('') and Token
.startswith('{') and Token
.endswith('}') and self
._Idx
>= self
._Len
:
345 Val
= self
._ConExpr
()
347 if type(Val
) == type(''):
353 elif not Val
.startswith('L"') and not Val
.startswith('{') and not Val
.startswith("L'"):
355 RealVal
= '"' + RealVal
+ '"'
357 # The expression has been parsed, but the end of expression is not reached
358 # It means the rest does not comply EBNF of <Expression>
359 if self
._Idx
!= self
._Len
:
360 raise BadExpression(ERR_SNYTAX
% self
._Expr
[self
._Idx
:])
363 RetVal
= str(RealVal
)
370 self
._WarnExcept
.result
= RetVal
371 raise self
._WarnExcept
375 # Template function to parse binary operators which have same precedence
376 # Expr [Operator Expr]*
377 def _ExprFuncTemplate(self
, EvalFunc
, OpLst
):
379 while self
._IsOperator
(OpLst
):
383 if self
._IsOperator
(':'):
391 Val
= self
.Eval(Op
, Val
, EvalFunc())
392 except WrnExpression
, Warn
:
393 self
._WarnExcept
= Warn
398 return self
._ExprFuncTemplate
(self
._OrExpr
, ['?', ':'])
402 return self
._ExprFuncTemplate
(self
._AndExpr
, ["OR", "or", "||"])
406 return self
._ExprFuncTemplate
(self
._BitOr
, ["AND", "and", "&&"])
410 return self
._ExprFuncTemplate
(self
._BitXor
, ["|"])
414 return self
._ExprFuncTemplate
(self
._BitAnd
, ["XOR", "xor", "^"])
418 return self
._ExprFuncTemplate
(self
._EqExpr
, ["&"])
422 Val
= self
._RelExpr
()
423 while self
._IsOperator
(["==", "!=", "EQ", "NE", "IN", "in", "!", "NOT", "not"]):
425 if Op
in ["!", "NOT", "not"]:
426 if not self
._IsOperator
(["IN", "in"]):
427 raise BadExpression(ERR_REL_NOT_IN
)
428 Op
+= ' ' + self
._Token
430 Val
= self
.Eval(Op
, Val
, self
._RelExpr
())
431 except WrnExpression
, Warn
:
432 self
._WarnExcept
= Warn
438 return self
._ExprFuncTemplate
(self
._ShiftExpr
, ["<=", ">=", "<", ">", "LE", "GE", "LT", "GT"])
440 def _ShiftExpr(self
):
441 return self
._ExprFuncTemplate
(self
._AddExpr
, ["<<", ">>"])
445 return self
._ExprFuncTemplate
(self
._MulExpr
, ["+", "-"])
449 return self
._ExprFuncTemplate
(self
._UnaryExpr
, ["*", "/", "%"])
452 def _UnaryExpr(self
):
453 if self
._IsOperator
(["!", "NOT", "not"]):
454 Val
= self
._UnaryExpr
()
456 return self
.Eval('not', Val
)
457 except WrnExpression
, Warn
:
458 self
._WarnExcept
= Warn
460 if self
._IsOperator
(["~"]):
461 Val
= self
._UnaryExpr
()
463 return self
.Eval('~', Val
)
464 except WrnExpression
, Warn
:
465 self
._WarnExcept
= Warn
467 return self
._IdenExpr
()
469 # Parse identifier or encapsulated expression
471 Tk
= self
._GetToken
()
473 Val
= self
._ConExpr
()
475 # _GetToken may also raise BadExpression
476 if self
._GetToken
() != ')':
477 raise BadExpression(ERR_MATCH
)
478 except BadExpression
:
479 raise BadExpression(ERR_MATCH
)
483 # Skip whitespace or tab
485 for Char
in self
._Expr
[self
._Idx
:]:
486 if Char
not in ' \t':
490 # Try to convert string to number
491 def __IsNumberToken(self
):
493 if self
._Token
.lower()[0:2] == '0x' and len(self
._Token
) > 2:
495 if self
._Token
.startswith('"') or self
._Token
.startswith('L"'):
497 for Index
in range(len(self
._Token
)):
498 if self
._Token
[Index
] in ['"']:
499 if self
._Token
[Index
- 1] == '\\':
502 if Flag
== 2 and self
._Token
.endswith('"'):
504 if self
._Token
.startswith("'") or self
._Token
.startswith("L'"):
506 for Index
in range(len(self
._Token
)):
507 if self
._Token
[Index
] in ["'"]:
508 if self
._Token
[Index
- 1] == '\\':
511 if Flag
== 2 and self
._Token
.endswith("'"):
514 self
._Token
= int(self
._Token
, Radix
)
522 def __GetArray(self
):
525 self
.__GetNList
(True)
526 Token
+= self
._LiteralToken
527 if self
._Idx
>= self
._Len
or self
._Expr
[self
._Idx
] != '}':
528 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
531 # All whitespace and tabs in array are already stripped.
532 IsArray
= IsGuid
= False
533 if len(Token
.split(',')) == 11 and len(Token
.split(',{')) == 2 \
534 and len(Token
.split('},')) == 1:
535 HexLen
= [11,6,6,5,4,4,4,4,4,4,6]
536 HexList
= Token
.split(',')
537 if HexList
[3].startswith('{') and \
538 not [Index
for Index
, Hex
in enumerate(HexList
) if len(Hex
) > HexLen
[Index
]]:
540 if Token
.lstrip('{').rstrip('}').find('{') == -1:
541 if not [Hex
for Hex
in Token
.lstrip('{').rstrip('}').split(',') if len(Hex
) > 4]:
543 if not IsArray
and not IsGuid
:
544 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
546 self
._Token
= self
._LiteralToken
= Token
549 # Parse string, the format must be: "..."
550 def __GetString(self
):
556 # Replace escape \\\", \"
557 if self
._Expr
[Idx
] == '"':
558 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace('\\\"', '\\\'')
563 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
564 if not self
._Token
.endswith('"'):
565 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
566 #Replace escape \\\', \'
567 elif self
._Expr
[Idx
] == "'":
568 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace("\\\'", "\\\"")
573 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
574 if not self
._Token
.endswith("'"):
575 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
576 self
._Token
= self
._Token
[1:-1]
579 # Get token that is comprised by alphanumeric, underscore or dot(used by PCD)
580 # @param IsAlphaOp: Indicate if parsing general token or script operator(EQ, NE...)
581 def __GetIdToken(self
, IsAlphaOp
= False):
583 for Ch
in self
._Expr
[self
._Idx
:]:
584 if not self
.__IsIdChar
(Ch
) or ('?' in self
._Expr
and Ch
== ':'):
589 self
._Token
= self
._LiteralToken
= IdToken
591 self
.__ResolveToken
()
594 # Try to resolve token
595 def __ResolveToken(self
):
597 raise BadExpression(ERR_EMPTY_TOKEN
)
600 if self
.PcdPattern
.match(self
._Token
):
601 if self
._Token
not in self
._Symb
:
602 Ex
= BadExpression(ERR_PCD_RESOLVE
% self
._Token
)
605 self
._Token
= ValueExpression(self
._Symb
[self
._Token
], self
._Symb
)(True, self
._Depth
+1)
606 if type(self
._Token
) != type(''):
607 self
._LiteralToken
= hex(self
._Token
)
610 if self
._Token
.startswith('"'):
611 self
._Token
= self
._Token
[1:-1]
612 elif self
._Token
in ["FALSE", "false", "False"]:
614 elif self
._Token
in ["TRUE", "true", "True"]:
617 self
.__IsNumberToken
()
619 def __GetNList(self
, InArray
=False):
620 self
._GetSingleToken
()
621 if not self
.__IsHexLiteral
():
623 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
627 Expr
= self
._Expr
[self
._Idx
:]
628 if not Expr
.startswith(','):
631 NList
= self
._LiteralToken
632 while Expr
.startswith(','):
636 self
._GetSingleToken
()
637 if not self
.__IsHexLiteral
():
638 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
639 NList
+= self
._LiteralToken
641 Expr
= self
._Expr
[self
._Idx
:]
642 self
._Token
= self
._LiteralToken
= NList
645 def __IsHexLiteral(self
):
646 if self
._LiteralToken
.startswith('{') and \
647 self
._LiteralToken
.endswith('}'):
650 if self
.HexPattern
.match(self
._LiteralToken
):
651 Token
= self
._LiteralToken
[2:]
653 self
._LiteralToken
= '0x0'
655 self
._LiteralToken
= '0x' + Token
660 return self
.__GetNList
()
664 return Ch
in '._:' or Ch
.isalnum()
667 def _GetSingleToken(self
):
669 Expr
= self
._Expr
[self
._Idx
:]
670 if Expr
.startswith('L"'):
673 UStr
= self
.__GetString
()
674 self
._Token
= 'L"' + UStr
+ '"'
676 elif Expr
.startswith("L'"):
679 UStr
= self
.__GetString
()
680 self
._Token
= "L'" + UStr
+ "'"
682 elif Expr
.startswith("'"):
683 UStr
= self
.__GetString
()
684 self
._Token
= "'" + UStr
+ "'"
686 elif Expr
.startswith('UINT'):
687 Re
= re
.compile('(?:UINT8|UINT16|UINT32|UINT64)\((.+)\)')
689 RetValue
= Re
.search(Expr
).group(1)
691 raise BadExpression('Invalid Expression %s' % Expr
)
696 Prefix
= self
._Expr
[Idx
:self
._Idx
- 1]
699 TmpValue
= self
._Expr
[Idx
:self
._Idx
- 1]
700 TmpValue
= ValueExpression(TmpValue
)(True)
701 TmpValue
= '0x%x' % int(TmpValue
) if type(TmpValue
) != type('') else TmpValue
703 self
._Token
, Size
= ParseFieldValue(Prefix
+ '(' + TmpValue
+ ')')
709 Match
= self
.RegGuidPattern
.match(Expr
)
710 if Match
and not Expr
[Match
.end():Match
.end()+1].isalnum() \
711 and Expr
[Match
.end():Match
.end()+1] != '_':
712 self
._Idx
+= Match
.end()
713 self
._Token
= ValueExpression(GuidStringToGuidStructureString(Expr
[0:Match
.end()]))(True, self
._Depth
+1)
715 elif self
.__IsIdChar
(Ch
):
716 return self
.__GetIdToken
()
718 return self
.__GetString
()
720 return self
.__GetArray
()
721 elif Ch
== '(' or Ch
== ')':
726 raise BadExpression(ERR_VALID_TOKEN
% Expr
)
729 def _GetOperator(self
):
731 LegalOpLst
= ['&&', '||', '!=', '==', '>=', '<='] + self
.NonLetterOpLst
+ ['?',':']
734 Expr
= self
._Expr
[self
._Idx
:]
736 # Reach end of expression
740 # Script operator: LT, GT, LE, GE, EQ, NE, and, or, xor, not
741 if Expr
[0].isalpha():
742 return self
.__GetIdToken
(True)
744 # Start to get regular operator: +, -, <, > ...
745 if Expr
[0] not in self
.NonLetterOpLst
:
750 if Ch
in self
.NonLetterOpLst
:
751 if '!' == Ch
and OpToken
:
758 if OpToken
not in LegalOpLst
:
759 raise BadExpression(ERR_OPERATOR_UNSUPPORT
% OpToken
)
760 self
._Token
= OpToken
763 # Check if current token matches the operators given from OpList
764 def _IsOperator(self
, OpList
):
767 if self
._Token
in OpList
:
768 if self
._Token
in self
.LogicalOperators
:
769 self
._Token
= self
.LogicalOperators
[self
._Token
]
774 class ValueExpressionEx(ValueExpression
):
775 def __init__(self
, PcdValue
, PcdType
, SymbolTable
={}):
776 ValueExpression
.__init
__(self
, PcdValue
, SymbolTable
)
777 self
.PcdValue
= PcdValue
778 self
.PcdType
= PcdType
780 def __call__(self
, RealValue
=False, Depth
=0):
781 PcdValue
= self
.PcdValue
783 PcdValue
= ValueExpression
.__call
__(self
, RealValue
, Depth
)
784 if self
.PcdType
== 'VOID*' and (PcdValue
.startswith("'") or PcdValue
.startswith("L'")):
785 PcdValue
, Size
= ParseFieldValue(PcdValue
)
787 for I
in range(Size
):
788 PcdValueList
.append('0x%02X'%(PcdValue
& 0xff))
789 PcdValue
= PcdValue
>> 8
790 PcdValue
= '{' + ','.join(PcdValueList
) + '}'
791 elif self
.PcdType
in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN'] and (PcdValue
.startswith("'") or \
792 PcdValue
.startswith('"') or PcdValue
.startswith("L'") or PcdValue
.startswith('L"') or PcdValue
.startswith('{')):
794 except WrnExpression
, Value
:
795 PcdValue
= Value
.result
796 except BadExpression
, Value
:
797 if self
.PcdType
in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN']:
798 PcdValue
= PcdValue
.strip()
799 if type(PcdValue
) == type('') and PcdValue
.startswith('{') and PcdValue
.endswith('}'):
800 PcdValue
= SplitPcdValueString(PcdValue
[1:-1])
801 if type(PcdValue
) == type([]):
805 for Item
in PcdValue
:
807 if Item
.startswith('UINT8'):
810 elif Item
.startswith('UINT16'):
813 elif Item
.startswith('UINT32'):
816 elif Item
.startswith('UINT64'):
819 elif Item
.startswith('"') or Item
.startswith("'") or Item
.startswith('L'):
825 Item
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
829 tmpValue
= int(Item
, 16) if Item
.upper().startswith('0X') else int(Item
, 0)
831 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
832 except BadExpression
, Value
:
833 raise BadExpression(Value
)
836 ItemValue
, ItemSize
= ParseFieldValue(Item
)
838 ItemValue
= ParseFieldValue(Item
)[0]
840 if type(ItemValue
) == type(''):
841 ItemValue
= int(ItemValue
, 16) if ItemValue
.startswith('0x') else int(ItemValue
)
843 TmpValue
= (ItemValue
<< (Size
* 8)) | TmpValue
844 Size
= Size
+ ItemSize
847 TmpValue
, Size
= ParseFieldValue(PcdValue
)
848 except BadExpression
, Value
:
849 raise BadExpression("Type: %s, Value: %s, %s" % (self
.PcdType
, PcdValue
, Value
))
850 if type(TmpValue
) == type(''):
852 TmpValue
= int(TmpValue
)
854 raise BadExpression(Value
)
856 PcdValue
= '0x%0{}X'.format(Size
) % (TmpValue
)
858 raise BadExpression('Type %s PCD Value is negative' % self
.PcdType
)
859 if self
.PcdType
== 'UINT8' and Size
> 1:
860 raise BadExpression('Type %s PCD Value Size is Larger than 1 byte' % self
.PcdType
)
861 if self
.PcdType
== 'UINT16' and Size
> 2:
862 raise BadExpression('Type %s PCD Value Size is Larger than 2 byte' % self
.PcdType
)
863 if self
.PcdType
== 'UINT32' and Size
> 4:
864 raise BadExpression('Type %s PCD Value Size is Larger than 4 byte' % self
.PcdType
)
865 if self
.PcdType
== 'UINT64' and Size
> 8:
866 raise BadExpression('Type %s PCD Value Size is Larger than 8 byte' % self
.PcdType
)
869 TmpValue
= long(PcdValue
)
871 if TmpValue
.bit_length() == 0:
874 for I
in range((TmpValue
.bit_length() + 7) / 8):
875 TmpList
.append('0x%02x' % ((TmpValue
>> I
* 8) & 0xff))
876 PcdValue
= '{' + ', '.join(TmpList
) + '}'
878 if PcdValue
.strip().startswith('{'):
879 PcdValueList
= SplitPcdValueString(PcdValue
.strip()[1:-1])
882 ReLabel
= re
.compile('LABEL\((\w+)\)')
883 ReOffset
= re
.compile('OFFSET_OF\((\w+)\)')
885 for Index
, Item
in enumerate(PcdValueList
):
886 # compute byte offset of every LABEL
889 LabelList
= ReLabel
.findall(Item
)
890 for Label
in LabelList
:
891 if Label
not in LabelDict
.keys():
892 LabelDict
[Label
] = str(LabelOffset
)
895 if Item
.startswith('UINT8'):
896 LabelOffset
= LabelOffset
+ 1
897 elif Item
.startswith('UINT16'):
898 LabelOffset
= LabelOffset
+ 2
899 elif Item
.startswith('UINT32'):
900 LabelOffset
= LabelOffset
+ 4
901 elif Item
.startswith('UINT64'):
902 LabelOffset
= LabelOffset
+ 8
905 ItemValue
, ItemSize
= ParseFieldValue(Item
)
906 LabelOffset
= LabelOffset
+ ItemSize
908 LabelOffset
= LabelOffset
+ 1
910 for Index
, Item
in enumerate(PcdValueList
):
914 Item
= ReLabel
.sub('', Item
)
918 OffsetList
= ReOffset
.findall(Item
)
921 for Offset
in OffsetList
:
922 if Offset
in LabelDict
.keys():
923 Re
= re
.compile('OFFSET_OF\(%s\)' % Offset
)
924 Item
= Re
.sub(LabelDict
[Offset
], Item
)
926 raise BadExpression('%s not defined' % Offset
)
927 NewPcdValueList
.append(Item
)
930 for Item
in NewPcdValueList
:
933 TokenSpaceGuidName
= ''
934 if Item
.startswith('GUID') and Item
.endswith(')'):
936 TokenSpaceGuidName
= re
.search('GUID\((\w+)\)', Item
).group(1)
939 if TokenSpaceGuidName
and TokenSpaceGuidName
in self
._Symb
:
940 Item
= 'GUID(' + self
._Symb
[TokenSpaceGuidName
] + ')'
941 elif TokenSpaceGuidName
:
942 raise BadExpression('%s not found in DEC file' % TokenSpaceGuidName
)
943 Item
, Size
= ParseFieldValue(Item
)
944 for Index
in range(0, Size
):
945 ValueStr
= '0x%02X' % (int(Item
) & 255)
947 AllPcdValueList
.append(ValueStr
)
949 elif Item
.startswith('DEVICE_PATH') and Item
.endswith(')'):
950 Item
, Size
= ParseFieldValue(Item
)
951 AllPcdValueList
.append(Item
[1:-1])
955 if Item
.startswith('UINT8'):
958 elif Item
.startswith('UINT16'):
961 elif Item
.startswith('UINT32'):
964 elif Item
.startswith('UINT64'):
970 TmpValue
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
972 TmpValue
= ValueExpressionEx(Item
, self
.PcdType
, self
._Symb
)(True)
973 Item
= '0x%x' % TmpValue
if type(TmpValue
) != type('') else TmpValue
975 ItemValue
, ItemSize
= ParseFieldValue(Item
)
976 if not (Item
.startswith('"') or Item
.startswith('L') or Item
.startswith('{')) and ItemSize
> 1:
977 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
979 ItemValue
= ParseFieldValue(Item
)[0]
980 for I
in range(0, ItemSize
):
981 ValueStr
= '0x%02X' % (int(ItemValue
) & 255)
983 AllPcdValueList
.append(ValueStr
)
987 PcdValue
= '{' + ','.join(AllPcdValueList
) + '}'
989 raise BadExpression("Type: %s, Value: %s, %s"%(self
.PcdType
, PcdValue
, Value
))
991 if PcdValue
== 'True':
993 if PcdValue
== 'False':
999 if __name__
== '__main__':
1002 input = raw_input('Input expr: ')
1006 print ValueExpression(input)(True)
1007 print ValueExpression(input)(False)
1008 except WrnExpression
, Ex
:
1011 except Exception, Ex
: