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"
49 Str
= String
.replace('\\\\', '//').replace('\\\"', '\\\'')
53 for i
, ch
in enumerate(Str
):
66 raise BadExpression(ERR_STRING_TOKEN
% Item
)
71 def SplitPcdValueString(String
):
72 # There might be escaped comma in GUID() or DEVICE_PATH() or " "
73 # or ' ' or L' ' or L" "
80 for i
, ch
in enumerate(Str
):
87 raise BadExpression(ERR_STRING_TOKEN
% Item
)
88 if ch
== '"' and not InSingleQuote
:
89 if String
[i
-1] != '\\':
90 InDoubleQuote
= not InDoubleQuote
91 if ch
== "'" and not InDoubleQuote
:
92 if String
[i
-1] != '\\':
93 InSingleQuote
= not InSingleQuote
95 if InParenthesis
or InSingleQuote
or InDoubleQuote
:
103 if InSingleQuote
or InDoubleQuote
or InParenthesis
:
104 raise BadExpression(ERR_STRING_TOKEN
% Item
)
111 def ReplaceExprMacro(String
, Macros
, ExceptionList
= None):
112 StrList
= SplitString(String
)
113 for i
, String
in enumerate(StrList
):
115 if String
.startswith('"'):
117 MacroStartPos
= String
.find('$(')
118 if MacroStartPos
< 0:
119 for Pcd
in gPlatformPcds
.keys():
121 if Pcd
not in gConditionalPcds
:
122 gConditionalPcds
.append(Pcd
)
125 while MacroStartPos
>= 0:
126 RetStr
= String
[0:MacroStartPos
]
127 MacroEndPos
= String
.find(')', MacroStartPos
)
129 raise BadExpression(ERR_MACRO_TOKEN
% String
[MacroStartPos
:])
130 Macro
= String
[MacroStartPos
+2:MacroEndPos
]
131 if Macro
not in Macros
:
132 # From C reference manual:
133 # If an undefined macro name appears in the constant-expression of
134 # !if or !elif, it is replaced by the integer constant 0.
137 Tklst
= RetStr
.split()
138 if Tklst
and Tklst
[-1] in ['IN', 'in'] and ExceptionList
and Macro
not in ExceptionList
:
139 raise BadExpression(ERR_IN_OPERAND
)
140 # Make sure the macro in exception list is encapsulated by double quote
141 # For example: DEFINE ARCH = IA32 X64
142 # $(ARCH) is replaced with "IA32 X64"
143 if ExceptionList
and Macro
in ExceptionList
:
144 RetStr
+= '"' + Macros
[Macro
] + '"'
145 elif Macros
[Macro
].strip():
146 RetStr
+= Macros
[Macro
]
150 RetStr
+= Macros
[Macro
]
151 RetStr
+= String
[MacroEndPos
+1:]
153 MacroStartPos
= String
.find('$(')
155 return ''.join(StrList
)
157 # transfer int to string for in/not in expression
161 StrList
.append(chr(Value
& 0xff))
163 Value
= '"' + ''.join(StrList
) + '"'
166 SupportedInMacroList
= ['TARGET', 'TOOL_CHAIN_TAG', 'ARCH', 'FAMILY']
168 class ValueExpression(object):
169 # Logical operator mapping
171 '&&' : 'and', '||' : 'or',
172 '!' : 'not', 'AND': 'and',
173 'OR' : 'or' , 'NOT': 'not',
174 'XOR': '^' , 'xor': '^',
175 'EQ' : '==' , 'NE' : '!=',
176 'GT' : '>' , 'LT' : '<',
177 'GE' : '>=' , 'LE' : '<=',
181 NonLetterOpLst
= ['+', '-', '*', '/', '%', '&', '|', '^', '~', '<<', '>>', '!', '=', '>', '<', '?', ':']
183 PcdPattern
= re
.compile(r
'[_a-zA-Z][0-9A-Za-z_]*\.[_a-zA-Z][0-9A-Za-z_]*$')
184 HexPattern
= re
.compile(r
'0[xX][0-9a-fA-F]+$')
185 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}')
187 SymbolPattern
= re
.compile("("
188 "\$\([A-Z][A-Z0-9_]*\)|\$\(\w+\.\w+\)|\w+\.\w+|"
190 "(?<=\W)AND(?=\W)|(?<=\W)OR(?=\W)|(?<=\W)NOT(?=\W)|(?<=\W)XOR(?=\W)|"
191 "(?<=\W)EQ(?=\W)|(?<=\W)NE(?=\W)|(?<=\W)GT(?=\W)|(?<=\W)LT(?=\W)|(?<=\W)GE(?=\W)|(?<=\W)LE(?=\W)"
195 def Eval(Operator
, Oprand1
, Oprand2
= None):
198 if Operator
not in ["==", "!=", ">=", "<=", ">", "<", "in", "not in"] and \
199 (type(Oprand1
) == type('') or type(Oprand2
) == type('')):
200 raise BadExpression(ERR_STRING_EXPR
% Operator
)
201 if Operator
in ['in', 'not in']:
202 if type(Oprand1
) != type(''):
203 Oprand1
= IntToStr(Oprand1
)
204 if type(Oprand2
) != type(''):
205 Oprand2
= IntToStr(Oprand2
)
214 if Operator
in ["!", "NOT", "not"]:
215 if type(Oprand1
) == type(''):
216 raise BadExpression(ERR_STRING_EXPR
% Operator
)
217 EvalStr
= 'not Oprand1'
218 elif Operator
in ["~"]:
219 if type(Oprand1
) == type(''):
220 raise BadExpression(ERR_STRING_EXPR
% Operator
)
221 EvalStr
= '~ Oprand1'
223 if Operator
in ["+", "-"] and (type(True) in [type(Oprand1
), type(Oprand2
)]):
224 # Boolean in '+'/'-' will be evaluated but raise warning
225 WrnExp
= WrnExpression(WRN_BOOL_EXPR
)
226 elif type('') in [type(Oprand1
), type(Oprand2
)] and type(Oprand1
)!= type(Oprand2
):
227 # == between string and number/boolean will always return False, != return True
229 WrnExp
= WrnExpression(WRN_EQCMP_STR_OTHERS
)
230 WrnExp
.result
= False
232 elif Operator
== "!=":
233 WrnExp
= WrnExpression(WRN_NECMP_STR_OTHERS
)
237 raise BadExpression(ERR_RELCMP_STR_OTHERS
% Operator
)
238 elif TypeDict
[type(Oprand1
)] != TypeDict
[type(Oprand2
)]:
239 if Operator
in ["==", "!=", ">=", "<=", ">", "<"] and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
240 # comparison between number and boolean is allowed
242 elif Operator
in ['&', '|', '^', "and", "or"] and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
243 # bitwise and logical operation between number and boolean is allowed
246 raise BadExpression(ERR_EXPR_TYPE
)
247 if type(Oprand1
) == type('') and type(Oprand2
) == type(''):
248 if (Oprand1
.startswith('L"') and not Oprand2
.startswith('L"')) or \
249 (not Oprand1
.startswith('L"') and Oprand2
.startswith('L"')):
250 raise BadExpression(ERR_STRING_CMP
% (Oprand1
, Operator
, Oprand2
))
251 if 'in' in Operator
and type(Oprand2
) == type(''):
252 Oprand2
= Oprand2
.split()
253 EvalStr
= 'Oprand1 ' + Operator
+ ' Oprand2'
255 # Local symbols used by built in eval function
261 Val
= eval(EvalStr
, {}, Dict
)
262 except Exception, Excpt
:
263 raise BadExpression(str(Excpt
))
265 if Operator
in ['and', 'or']:
276 def __init__(self
, Expression
, SymbolTable
={}):
277 self
._NoProcess
= False
278 if type(Expression
) != type(''):
279 self
._Expr
= Expression
280 self
._NoProcess
= True
283 self
._Expr
= ReplaceExprMacro(Expression
.strip(),
285 SupportedInMacroList
)
287 if not self
._Expr
.strip():
288 raise BadExpression(ERR_EMPTY_EXPR
)
291 # The symbol table including PCD and macro mapping
293 self
._Symb
= copy
.deepcopy(SymbolTable
)
294 self
._Symb
.update(self
.LogicalOperators
)
296 self
._Len
= len(self
._Expr
)
298 self
._WarnExcept
= None
300 # Literal token without any conversion
301 self
._LiteralToken
= ''
303 # Public entry for this class
304 # @param RealValue: False: only evaluate if the expression is true or false, used for conditional expression
305 # True : return the evaluated str(value), used for PCD value
307 # @return: True or False if RealValue is False
308 # Evaluated value of string format if RealValue is True
310 def __call__(self
, RealValue
=False, Depth
=0):
316 self
._Expr
= self
._Expr
.strip()
317 if RealValue
and Depth
== 0:
318 self
._Token
= self
._Expr
319 if self
.__IsNumberToken
():
323 Token
= self
._GetToken
()
324 except BadExpression
:
326 if type(Token
) == type('') and Token
.startswith('{') and Token
.endswith('}') and self
._Idx
>= self
._Len
:
332 Val
= self
._ConExpr
()
334 if type(Val
) == type(''):
340 elif not Val
.startswith('L"') and not Val
.startswith('{') and not Val
.startswith("L'"):
342 RealVal
= '"' + RealVal
+ '"'
344 # The expression has been parsed, but the end of expression is not reached
345 # It means the rest does not comply EBNF of <Expression>
346 if self
._Idx
!= self
._Len
:
347 raise BadExpression(ERR_SNYTAX
% self
._Expr
[self
._Idx
:])
350 RetVal
= str(RealVal
)
357 self
._WarnExcept
.result
= RetVal
358 raise self
._WarnExcept
362 # Template function to parse binary operators which have same precedence
363 # Expr [Operator Expr]*
364 def _ExprFuncTemplate(self
, EvalFunc
, OpLst
):
366 while self
._IsOperator
(OpLst
):
370 if self
._IsOperator
(':'):
378 Val
= self
.Eval(Op
, Val
, EvalFunc())
379 except WrnExpression
, Warn
:
380 self
._WarnExcept
= Warn
385 return self
._ExprFuncTemplate
(self
._OrExpr
, ['?', ':'])
389 return self
._ExprFuncTemplate
(self
._AndExpr
, ["OR", "or", "||"])
393 return self
._ExprFuncTemplate
(self
._BitOr
, ["AND", "and", "&&"])
397 return self
._ExprFuncTemplate
(self
._BitXor
, ["|"])
401 return self
._ExprFuncTemplate
(self
._BitAnd
, ["XOR", "xor", "^"])
405 return self
._ExprFuncTemplate
(self
._EqExpr
, ["&"])
409 Val
= self
._RelExpr
()
410 while self
._IsOperator
(["==", "!=", "EQ", "NE", "IN", "in", "!", "NOT", "not"]):
412 if Op
in ["!", "NOT", "not"]:
413 if not self
._IsOperator
(["IN", "in"]):
414 raise BadExpression(ERR_REL_NOT_IN
)
415 Op
+= ' ' + self
._Token
417 Val
= self
.Eval(Op
, Val
, self
._RelExpr
())
418 except WrnExpression
, Warn
:
419 self
._WarnExcept
= Warn
425 return self
._ExprFuncTemplate
(self
._ShiftExpr
, ["<=", ">=", "<", ">", "LE", "GE", "LT", "GT"])
427 def _ShiftExpr(self
):
428 return self
._ExprFuncTemplate
(self
._AddExpr
, ["<<", ">>"])
432 return self
._ExprFuncTemplate
(self
._MulExpr
, ["+", "-"])
436 return self
._ExprFuncTemplate
(self
._UnaryExpr
, ["*", "/", "%"])
439 def _UnaryExpr(self
):
440 if self
._IsOperator
(["!", "NOT", "not"]):
441 Val
= self
._UnaryExpr
()
443 return self
.Eval('not', Val
)
444 except WrnExpression
, Warn
:
445 self
._WarnExcept
= Warn
447 if self
._IsOperator
(["~"]):
448 Val
= self
._UnaryExpr
()
450 return self
.Eval('~', Val
)
451 except WrnExpression
, Warn
:
452 self
._WarnExcept
= Warn
454 return self
._IdenExpr
()
456 # Parse identifier or encapsulated expression
458 Tk
= self
._GetToken
()
460 Val
= self
._ConExpr
()
462 # _GetToken may also raise BadExpression
463 if self
._GetToken
() != ')':
464 raise BadExpression(ERR_MATCH
)
465 except BadExpression
:
466 raise BadExpression(ERR_MATCH
)
470 # Skip whitespace or tab
472 for Char
in self
._Expr
[self
._Idx
:]:
473 if Char
not in ' \t':
477 # Try to convert string to number
478 def __IsNumberToken(self
):
480 if self
._Token
.lower()[0:2] == '0x' and len(self
._Token
) > 2:
482 if self
._Token
.startswith('"') or self
._Token
.startswith('L"'):
484 for Index
in range(len(self
._Token
)):
485 if self
._Token
[Index
] in ['"']:
487 if Flag
== 2 and self
._Token
.endswith('"'):
489 if self
._Token
.startswith("'") or self
._Token
.startswith("L'"):
491 for Index
in range(len(self
._Token
)):
492 if self
._Token
[Index
] in ["'"]:
494 if Flag
== 2 and self
._Token
.endswith("'"):
497 self
._Token
= int(self
._Token
, Radix
)
505 def __GetArray(self
):
508 self
.__GetNList
(True)
509 Token
+= self
._LiteralToken
510 if self
._Idx
>= self
._Len
or self
._Expr
[self
._Idx
] != '}':
511 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
514 # All whitespace and tabs in array are already stripped.
515 IsArray
= IsGuid
= False
516 if len(Token
.split(',')) == 11 and len(Token
.split(',{')) == 2 \
517 and len(Token
.split('},')) == 1:
518 HexLen
= [11,6,6,5,4,4,4,4,4,4,6]
519 HexList
= Token
.split(',')
520 if HexList
[3].startswith('{') and \
521 not [Index
for Index
, Hex
in enumerate(HexList
) if len(Hex
) > HexLen
[Index
]]:
523 if Token
.lstrip('{').rstrip('}').find('{') == -1:
524 if not [Hex
for Hex
in Token
.lstrip('{').rstrip('}').split(',') if len(Hex
) > 4]:
526 if not IsArray
and not IsGuid
:
527 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
529 self
._Token
= self
._LiteralToken
= Token
532 # Parse string, the format must be: "..."
533 def __GetString(self
):
539 # Replace escape \\\", \"
540 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace('\\\"', '\\\'')
543 if Ch
== '"' or Ch
== "'":
545 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
546 if self
._Token
.startswith('"') and not self
._Token
.endswith('"'):
547 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
548 if self
._Token
.startswith("'") and not self
._Token
.endswith("'"):
549 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
550 self
._Token
= self
._Token
[1:-1]
553 # Get token that is comprised by alphanumeric, underscore or dot(used by PCD)
554 # @param IsAlphaOp: Indicate if parsing general token or script operator(EQ, NE...)
555 def __GetIdToken(self
, IsAlphaOp
= False):
557 for Ch
in self
._Expr
[self
._Idx
:]:
558 if not self
.__IsIdChar
(Ch
) or ('?' in self
._Expr
and Ch
== ':'):
563 self
._Token
= self
._LiteralToken
= IdToken
565 self
.__ResolveToken
()
568 # Try to resolve token
569 def __ResolveToken(self
):
571 raise BadExpression(ERR_EMPTY_TOKEN
)
574 if self
.PcdPattern
.match(self
._Token
):
575 if self
._Token
not in self
._Symb
:
576 Ex
= BadExpression(ERR_PCD_RESOLVE
% self
._Token
)
579 self
._Token
= ValueExpression(self
._Symb
[self
._Token
], self
._Symb
)(True, self
._Depth
+1)
580 if type(self
._Token
) != type(''):
581 self
._LiteralToken
= hex(self
._Token
)
584 if self
._Token
.startswith('"'):
585 self
._Token
= self
._Token
[1:-1]
586 elif self
._Token
in ["FALSE", "false", "False"]:
588 elif self
._Token
in ["TRUE", "true", "True"]:
591 self
.__IsNumberToken
()
593 def __GetNList(self
, InArray
=False):
594 self
._GetSingleToken
()
595 if not self
.__IsHexLiteral
():
597 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
601 Expr
= self
._Expr
[self
._Idx
:]
602 if not Expr
.startswith(','):
605 NList
= self
._LiteralToken
606 while Expr
.startswith(','):
610 self
._GetSingleToken
()
611 if not self
.__IsHexLiteral
():
612 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
613 NList
+= self
._LiteralToken
615 Expr
= self
._Expr
[self
._Idx
:]
616 self
._Token
= self
._LiteralToken
= NList
619 def __IsHexLiteral(self
):
620 if self
._LiteralToken
.startswith('{') and \
621 self
._LiteralToken
.endswith('}'):
624 if self
.HexPattern
.match(self
._LiteralToken
):
625 Token
= self
._LiteralToken
[2:]
627 self
._LiteralToken
= '0x0'
629 self
._LiteralToken
= '0x' + Token
634 return self
.__GetNList
()
638 return Ch
in '._:' or Ch
.isalnum()
641 def _GetSingleToken(self
):
643 Expr
= self
._Expr
[self
._Idx
:]
644 if Expr
.startswith('L"'):
647 UStr
= self
.__GetString
()
648 self
._Token
= 'L"' + UStr
+ '"'
650 elif Expr
.startswith("L'"):
653 UStr
= self
.__GetString
()
654 self
._Token
= "L'" + UStr
+ "'"
656 elif Expr
.startswith("'"):
657 UStr
= self
.__GetString
()
658 self
._Token
= "'" + UStr
+ "'"
660 elif Expr
.startswith('UINT'):
661 Re
= re
.compile('(?:UINT8|UINT16|UINT32|UINT64)\((.+)\)')
663 RetValue
= Re
.search(Expr
).group(1)
665 raise BadExpression('Invalid Expression %s' % Expr
)
670 Prefix
= self
._Expr
[Idx
:self
._Idx
- 1]
673 TmpValue
= self
._Expr
[Idx
:self
._Idx
- 1]
674 TmpValue
= ValueExpression(TmpValue
)(True)
675 TmpValue
= '0x%x' % int(TmpValue
) if type(TmpValue
) != type('') else TmpValue
677 self
._Token
, Size
= ParseFieldValue(Prefix
+ '(' + TmpValue
+ ')')
683 Match
= self
.RegGuidPattern
.match(Expr
)
684 if Match
and not Expr
[Match
.end():Match
.end()+1].isalnum() \
685 and Expr
[Match
.end():Match
.end()+1] != '_':
686 self
._Idx
+= Match
.end()
687 self
._Token
= ValueExpression(GuidStringToGuidStructureString(Expr
[0:Match
.end()]))(True, self
._Depth
+1)
689 elif self
.__IsIdChar
(Ch
):
690 return self
.__GetIdToken
()
692 return self
.__GetString
()
694 return self
.__GetArray
()
695 elif Ch
== '(' or Ch
== ')':
700 raise BadExpression(ERR_VALID_TOKEN
% Expr
)
703 def _GetOperator(self
):
705 LegalOpLst
= ['&&', '||', '!=', '==', '>=', '<='] + self
.NonLetterOpLst
+ ['?',':']
708 Expr
= self
._Expr
[self
._Idx
:]
710 # Reach end of expression
714 # Script operator: LT, GT, LE, GE, EQ, NE, and, or, xor, not
715 if Expr
[0].isalpha():
716 return self
.__GetIdToken
(True)
718 # Start to get regular operator: +, -, <, > ...
719 if Expr
[0] not in self
.NonLetterOpLst
:
724 if Ch
in self
.NonLetterOpLst
:
725 if '!' == Ch
and OpToken
:
732 if OpToken
not in LegalOpLst
:
733 raise BadExpression(ERR_OPERATOR_UNSUPPORT
% OpToken
)
734 self
._Token
= OpToken
737 # Check if current token matches the operators given from OpList
738 def _IsOperator(self
, OpList
):
741 if self
._Token
in OpList
:
742 if self
._Token
in self
.LogicalOperators
:
743 self
._Token
= self
.LogicalOperators
[self
._Token
]
748 class ValueExpressionEx(ValueExpression
):
749 def __init__(self
, PcdValue
, PcdType
, SymbolTable
={}):
750 ValueExpression
.__init
__(self
, PcdValue
, SymbolTable
)
751 self
.PcdValue
= PcdValue
752 self
.PcdType
= PcdType
754 def __call__(self
, RealValue
=False, Depth
=0):
755 PcdValue
= self
.PcdValue
757 PcdValue
= ValueExpression
.__call
__(self
, RealValue
, Depth
)
758 if self
.PcdType
== 'VOID*' and (PcdValue
.startswith("'") or PcdValue
.startswith("L'")):
759 PcdValue
, Size
= ParseFieldValue(PcdValue
)
761 for I
in range(Size
):
762 PcdValueList
.append('0x%02X'%(PcdValue
& 0xff))
763 PcdValue
= PcdValue
>> 8
764 PcdValue
= '{' + ','.join(PcdValueList
) + '}'
765 elif self
.PcdType
in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN'] and (PcdValue
.startswith("'") or \
766 PcdValue
.startswith('"') or PcdValue
.startswith("L'") or PcdValue
.startswith('L"') or PcdValue
.startswith('{')):
768 except WrnExpression
, Value
:
769 PcdValue
= Value
.result
770 except BadExpression
, Value
:
771 if self
.PcdType
in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN']:
772 PcdValue
= PcdValue
.strip()
773 if type(PcdValue
) == type('') and PcdValue
.startswith('{') and PcdValue
.endswith('}'):
774 PcdValue
= SplitPcdValueString(PcdValue
[1:-1])
775 if type(PcdValue
) == type([]):
779 for Item
in PcdValue
:
781 if Item
.startswith('UINT8'):
784 elif Item
.startswith('UINT16'):
787 elif Item
.startswith('UINT32'):
790 elif Item
.startswith('UINT64'):
793 elif Item
.startswith('"') or Item
.startswith("'") or Item
.startswith('L'):
799 Item
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
803 tmpValue
= int(Item
, 16) if Item
.upper().startswith('0X') else int(Item
, 0)
805 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
806 except BadExpression
, Value
:
807 raise BadExpression(Value
)
810 ItemValue
, ItemSize
= ParseFieldValue(Item
)
812 ItemValue
= ParseFieldValue(Item
)[0]
814 if type(ItemValue
) == type(''):
815 ItemValue
= int(ItemValue
, 16) if ItemValue
.startswith('0x') else int(ItemValue
)
817 TmpValue
= (ItemValue
<< (Size
* 8)) | TmpValue
818 Size
= Size
+ ItemSize
821 TmpValue
, Size
= ParseFieldValue(PcdValue
)
822 except BadExpression
, Value
:
823 raise BadExpression("Type: %s, Value: %s, %s" % (self
.PcdType
, PcdValue
, Value
))
824 if type(TmpValue
) == type(''):
826 TmpValue
= int(TmpValue
)
828 raise BadExpression(Value
)
830 PcdValue
= '0x%0{}X'.format(Size
) % (TmpValue
)
832 raise BadExpression('Type %s PCD Value is negative' % self
.PcdType
)
833 if self
.PcdType
== 'UINT8' and Size
> 1:
834 raise BadExpression('Type %s PCD Value Size is Larger than 1 byte' % self
.PcdType
)
835 if self
.PcdType
== 'UINT16' and Size
> 2:
836 raise BadExpression('Type %s PCD Value Size is Larger than 2 byte' % self
.PcdType
)
837 if self
.PcdType
== 'UINT32' and Size
> 4:
838 raise BadExpression('Type %s PCD Value Size is Larger than 4 byte' % self
.PcdType
)
839 if self
.PcdType
== 'UINT64' and Size
> 8:
840 raise BadExpression('Type %s PCD Value Size is Larger than 8 byte' % self
.PcdType
)
843 TmpValue
= long(PcdValue
)
845 if TmpValue
.bit_length() == 0:
848 for I
in range((TmpValue
.bit_length() + 7) / 8):
849 TmpList
.append('0x%02x' % ((TmpValue
>> I
* 8) & 0xff))
850 PcdValue
= '{' + ', '.join(TmpList
) + '}'
852 if PcdValue
.strip().startswith('{'):
853 PcdValueList
= SplitPcdValueString(PcdValue
.strip()[1:-1])
856 ReLabel
= re
.compile('LABEL\((\w+)\)')
857 ReOffset
= re
.compile('OFFSET_OF\((\w+)\)')
859 for Index
, Item
in enumerate(PcdValueList
):
860 # compute byte offset of every LABEL
863 LabelList
= ReLabel
.findall(Item
)
864 for Label
in LabelList
:
865 if Label
not in LabelDict
.keys():
866 LabelDict
[Label
] = str(LabelOffset
)
869 if Item
.startswith('UINT8'):
870 LabelOffset
= LabelOffset
+ 1
871 elif Item
.startswith('UINT16'):
872 LabelOffset
= LabelOffset
+ 2
873 elif Item
.startswith('UINT32'):
874 LabelOffset
= LabelOffset
+ 4
875 elif Item
.startswith('UINT64'):
876 LabelOffset
= LabelOffset
+ 8
879 ItemValue
, ItemSize
= ParseFieldValue(Item
)
880 LabelOffset
= LabelOffset
+ ItemSize
882 LabelOffset
= LabelOffset
+ 1
884 for Index
, Item
in enumerate(PcdValueList
):
888 Item
= ReLabel
.sub('', Item
)
892 OffsetList
= ReOffset
.findall(Item
)
895 for Offset
in OffsetList
:
896 if Offset
in LabelDict
.keys():
897 Re
= re
.compile('OFFSET_OF\(%s\)' % Offset
)
898 Item
= Re
.sub(LabelDict
[Offset
], Item
)
900 raise BadExpression('%s not defined' % Offset
)
901 NewPcdValueList
.append(Item
)
904 for Item
in NewPcdValueList
:
907 TokenSpaceGuidName
= ''
908 if Item
.startswith('GUID') and Item
.endswith(')'):
910 TokenSpaceGuidName
= re
.search('GUID\((\w+)\)', Item
).group(1)
913 if TokenSpaceGuidName
and TokenSpaceGuidName
in self
._Symb
:
914 Item
= 'GUID(' + self
._Symb
[TokenSpaceGuidName
] + ')'
915 elif TokenSpaceGuidName
:
916 raise BadExpression('%s not found in DEC file' % TokenSpaceGuidName
)
917 Item
, Size
= ParseFieldValue(Item
)
918 for Index
in range(0, Size
):
919 ValueStr
= '0x%02X' % (int(Item
) & 255)
921 AllPcdValueList
.append(ValueStr
)
923 elif Item
.startswith('DEVICE_PATH') and Item
.endswith(')'):
924 Item
, Size
= ParseFieldValue(Item
)
925 AllPcdValueList
.append(Item
[1:-1])
929 if Item
.startswith('UINT8'):
932 elif Item
.startswith('UINT16'):
935 elif Item
.startswith('UINT32'):
938 elif Item
.startswith('UINT64'):
944 TmpValue
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
946 TmpValue
= ValueExpressionEx(Item
, self
.PcdType
, self
._Symb
)(True)
947 Item
= '0x%x' % TmpValue
if type(TmpValue
) != type('') else TmpValue
949 ItemValue
, ItemSize
= ParseFieldValue(Item
)
950 if not (Item
.startswith('"') or Item
.startswith('L') or Item
.startswith('{')) and ItemSize
> 1:
951 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
953 ItemValue
= ParseFieldValue(Item
)[0]
954 for I
in range(0, ItemSize
):
955 ValueStr
= '0x%02X' % (int(ItemValue
) & 255)
957 AllPcdValueList
.append(ValueStr
)
961 PcdValue
= '{' + ','.join(AllPcdValueList
) + '}'
963 raise BadExpression("Type: %s, Value: %s, %s"%(self
.PcdType
, PcdValue
, Value
))
965 if PcdValue
== 'True':
967 if PcdValue
== 'False':
973 if __name__
== '__main__':
976 input = raw_input('Input expr: ')
980 print ValueExpression(input)(True)
981 print ValueExpression(input)(False)
982 except WrnExpression
, Ex
:
985 except Exception, Ex
: