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 __future__
import print_function
16 from Common
.GlobalData
import *
17 from CommonDataClass
.Exceptions
import BadExpression
18 from CommonDataClass
.Exceptions
import WrnExpression
19 from Misc
import GuidStringToGuidStructureString
, ParseFieldValue
, IsFieldValueAnArray
20 import Common
.EdkLogger
as EdkLogger
22 from Common
.DataType
import *
24 ERR_STRING_EXPR
= 'This operator cannot be used in string expression: [%s].'
25 ERR_SNYTAX
= 'Syntax error, the rest of expression cannot be evaluated: [%s].'
26 ERR_MATCH
= 'No matching right parenthesis.'
27 ERR_STRING_TOKEN
= 'Bad string token: [%s].'
28 ERR_MACRO_TOKEN
= 'Bad macro token: [%s].'
29 ERR_EMPTY_TOKEN
= 'Empty token is not allowed.'
30 ERR_PCD_RESOLVE
= 'PCD token cannot be resolved: [%s].'
31 ERR_VALID_TOKEN
= 'No more valid token found from rest of string: [%s].'
32 ERR_EXPR_TYPE
= 'Different types found in expression.'
33 ERR_OPERATOR_UNSUPPORT
= 'Unsupported operator: [%s]'
34 ERR_REL_NOT_IN
= 'Expect "IN" after "not" operator.'
35 WRN_BOOL_EXPR
= 'Operand of boolean type cannot be used in arithmetic expression.'
36 WRN_EQCMP_STR_OTHERS
= '== Comparison between Operand of string type and Boolean/Number Type always return False.'
37 WRN_NECMP_STR_OTHERS
= '!= Comparison between Operand of string type and Boolean/Number Type always return True.'
38 ERR_RELCMP_STR_OTHERS
= 'Operator taking Operand of string type and Boolean/Number Type is not allowed: [%s].'
39 ERR_STRING_CMP
= 'Unicode string and general string cannot be compared: [%s %s %s]'
40 ERR_ARRAY_TOKEN
= 'Bad C array or C format GUID token: [%s].'
41 ERR_ARRAY_ELE
= 'This must be HEX value for NList or Array: [%s].'
42 ERR_EMPTY_EXPR
= 'Empty expression is not allowed.'
43 ERR_IN_OPERAND
= 'Macro after IN operator can only be: $(FAMILY), $(ARCH), $(TOOL_CHAIN_TAG) and $(TARGET).'
45 __ValidString
= re
.compile(r
'[_a-zA-Z][_0-9a-zA-Z]*$')
46 _ReLabel
= re
.compile('LABEL\((\w+)\)')
47 _ReOffset
= re
.compile('OFFSET_OF\((\w+)\)')
48 PcdPattern
= re
.compile(r
'[_a-zA-Z][0-9A-Za-z_]*\.[_a-zA-Z][0-9A-Za-z_]*$')
51 # Split string to list according double quote
52 # For example: abc"de\"f"ghi"jkl"mn will be: ['abc', '"de\"f"', 'ghi', '"jkl"', 'mn']
54 def SplitString(String
):
55 # There might be escaped quote: "abc\"def\\\"ghi", 'abc\'def\\\'ghi'
60 for i
, ch
in enumerate(String
):
61 if ch
== '"' and not InSingleQuote
:
62 if String
[i
- 1] != '\\':
63 InDoubleQuote
= not InDoubleQuote
72 elif ch
== "'" and not InDoubleQuote
:
73 if String
[i
- 1] != '\\':
74 InSingleQuote
= not InSingleQuote
84 if InSingleQuote
or InDoubleQuote
:
85 raise BadExpression(ERR_STRING_TOKEN
% Item
)
90 def SplitPcdValueString(String
):
91 # There might be escaped comma in GUID() or DEVICE_PATH() or " "
92 # or ' ' or L' ' or L" "
98 for i
, ch
in enumerate(String
):
105 raise BadExpression(ERR_STRING_TOKEN
% Item
)
106 elif ch
== '"' and not InSingleQuote
:
107 if String
[i
-1] != '\\':
108 InDoubleQuote
= not InDoubleQuote
109 elif ch
== "'" and not InDoubleQuote
:
110 if String
[i
-1] != '\\':
111 InSingleQuote
= not InSingleQuote
113 if InParenthesis
or InSingleQuote
or InDoubleQuote
:
121 if InSingleQuote
or InDoubleQuote
or InParenthesis
:
122 raise BadExpression(ERR_STRING_TOKEN
% Item
)
127 def IsValidCName(Str
):
128 return True if __ValidString
.match(Str
) else False
130 def BuildOptionValue(PcdValue
, GuidDict
):
131 if PcdValue
.startswith('H'):
132 InputValue
= PcdValue
[1:]
133 elif PcdValue
.startswith("L'") or PcdValue
.startswith("'"):
134 InputValue
= PcdValue
135 elif PcdValue
.startswith('L'):
136 InputValue
= 'L"' + PcdValue
[1:] + '"'
138 InputValue
= PcdValue
139 if IsFieldValueAnArray(InputValue
):
141 PcdValue
= ValueExpressionEx(InputValue
, TAB_VOID
, GuidDict
)(True)
148 def ReplaceExprMacro(String
, Macros
, ExceptionList
= None):
149 StrList
= SplitString(String
)
150 for i
, String
in enumerate(StrList
):
152 if String
.startswith('"'):
154 MacroStartPos
= String
.find('$(')
155 if MacroStartPos
< 0:
156 for Pcd
in gPlatformPcds
:
158 if Pcd
not in gConditionalPcds
:
159 gConditionalPcds
.append(Pcd
)
162 while MacroStartPos
>= 0:
163 RetStr
= String
[0:MacroStartPos
]
164 MacroEndPos
= String
.find(')', MacroStartPos
)
166 raise BadExpression(ERR_MACRO_TOKEN
% String
[MacroStartPos
:])
167 Macro
= String
[MacroStartPos
+2:MacroEndPos
]
168 if Macro
not in Macros
:
169 # From C reference manual:
170 # If an undefined macro name appears in the constant-expression of
171 # !if or !elif, it is replaced by the integer constant 0.
174 Tklst
= RetStr
.split()
175 if Tklst
and Tklst
[-1] in {'IN', 'in'} and ExceptionList
and Macro
not in ExceptionList
:
176 raise BadExpression(ERR_IN_OPERAND
)
177 # Make sure the macro in exception list is encapsulated by double quote
178 # For example: DEFINE ARCH = IA32 X64
179 # $(ARCH) is replaced with "IA32 X64"
180 if ExceptionList
and Macro
in ExceptionList
:
181 RetStr
+= '"' + Macros
[Macro
] + '"'
182 elif Macros
[Macro
].strip():
183 RetStr
+= Macros
[Macro
]
187 RetStr
+= Macros
[Macro
]
188 RetStr
+= String
[MacroEndPos
+1:]
190 MacroStartPos
= String
.find('$(')
192 return ''.join(StrList
)
194 # transfer int to string for in/not in expression
198 StrList
.append(chr(Value
& 0xff))
200 Value
= '"' + ''.join(StrList
) + '"'
203 SupportedInMacroList
= ['TARGET', 'TOOL_CHAIN_TAG', 'ARCH', 'FAMILY']
205 class BaseExpression(object):
206 def __init__(self
, *args
, **kwargs
):
207 super(BaseExpression
, self
).__init
__()
209 # Check if current token matches the operators given from parameter
210 def _IsOperator(self
, OpSet
):
213 if self
._Token
in OpSet
:
214 if self
._Token
in self
.LogicalOperators
:
215 self
._Token
= self
.LogicalOperators
[self
._Token
]
220 class ValueExpression(BaseExpression
):
221 # Logical operator mapping
223 '&&' : 'and', '||' : 'or',
224 '!' : 'not', 'AND': 'and',
225 'OR' : 'or' , 'NOT': 'not',
226 'XOR': '^' , 'xor': '^',
227 'EQ' : '==' , 'NE' : '!=',
228 'GT' : '>' , 'LT' : '<',
229 'GE' : '>=' , 'LE' : '<=',
233 NonLetterOpLst
= ['+', '-', '*', '/', '%', '&', '|', '^', '~', '<<', '>>', '!', '=', '>', '<', '?', ':']
236 SymbolPattern
= re
.compile("("
237 "\$\([A-Z][A-Z0-9_]*\)|\$\(\w+\.\w+\)|\w+\.\w+|"
239 "(?<=\W)AND(?=\W)|(?<=\W)OR(?=\W)|(?<=\W)NOT(?=\W)|(?<=\W)XOR(?=\W)|"
240 "(?<=\W)EQ(?=\W)|(?<=\W)NE(?=\W)|(?<=\W)GT(?=\W)|(?<=\W)LT(?=\W)|(?<=\W)GE(?=\W)|(?<=\W)LE(?=\W)"
244 def Eval(Operator
, Oprand1
, Oprand2
= None):
247 if Operator
not in {"==", "!=", ">=", "<=", ">", "<", "in", "not in"} and \
248 (isinstance(Oprand1
, type('')) or isinstance(Oprand2
, type(''))):
249 raise BadExpression(ERR_STRING_EXPR
% Operator
)
250 if Operator
in {'in', 'not in'}:
251 if not isinstance(Oprand1
, type('')):
252 Oprand1
= IntToStr(Oprand1
)
253 if not isinstance(Oprand2
, type('')):
254 Oprand2
= IntToStr(Oprand2
)
263 if Operator
in {"!", "NOT", "not"}:
264 if isinstance(Oprand1
, type('')):
265 raise BadExpression(ERR_STRING_EXPR
% Operator
)
266 EvalStr
= 'not Oprand1'
267 elif Operator
in {"~"}:
268 if isinstance(Oprand1
, type('')):
269 raise BadExpression(ERR_STRING_EXPR
% Operator
)
270 EvalStr
= '~ Oprand1'
272 if Operator
in {"+", "-"} and (type(True) in {type(Oprand1
), type(Oprand2
)}):
273 # Boolean in '+'/'-' will be evaluated but raise warning
274 WrnExp
= WrnExpression(WRN_BOOL_EXPR
)
275 elif type('') in {type(Oprand1
), type(Oprand2
)} and not isinstance(Oprand1
, type(Oprand2
)):
276 # == between string and number/boolean will always return False, != return True
278 WrnExp
= WrnExpression(WRN_EQCMP_STR_OTHERS
)
279 WrnExp
.result
= False
281 elif Operator
== "!=":
282 WrnExp
= WrnExpression(WRN_NECMP_STR_OTHERS
)
286 raise BadExpression(ERR_RELCMP_STR_OTHERS
% Operator
)
287 elif TypeDict
[type(Oprand1
)] != TypeDict
[type(Oprand2
)]:
288 if Operator
in {"==", "!=", ">=", "<=", ">", "<"} and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
289 # comparison between number and boolean is allowed
291 elif Operator
in {'&', '|', '^', "and", "or"} and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
292 # bitwise and logical operation between number and boolean is allowed
295 raise BadExpression(ERR_EXPR_TYPE
)
296 if isinstance(Oprand1
, type('')) and isinstance(Oprand2
, type('')):
297 if (Oprand1
.startswith('L"') and not Oprand2
.startswith('L"')) or \
298 (not Oprand1
.startswith('L"') and Oprand2
.startswith('L"')):
299 raise BadExpression(ERR_STRING_CMP
% (Oprand1
, Operator
, Oprand2
))
300 if 'in' in Operator
and isinstance(Oprand2
, type('')):
301 Oprand2
= Oprand2
.split()
302 EvalStr
= 'Oprand1 ' + Operator
+ ' Oprand2'
304 # Local symbols used by built in eval function
310 Val
= eval(EvalStr
, {}, Dict
)
311 except Exception as Excpt
:
312 raise BadExpression(str(Excpt
))
314 if Operator
in {'and', 'or'}:
325 def __init__(self
, Expression
, SymbolTable
={}):
326 super(ValueExpression
, self
).__init
__(self
, Expression
, SymbolTable
)
327 self
._NoProcess
= False
328 if not isinstance(Expression
, type('')):
329 self
._Expr
= Expression
330 self
._NoProcess
= True
333 self
._Expr
= ReplaceExprMacro(Expression
.strip(),
335 SupportedInMacroList
)
337 if not self
._Expr
.strip():
338 raise BadExpression(ERR_EMPTY_EXPR
)
341 # The symbol table including PCD and macro mapping
343 self
._Symb
= copy
.deepcopy(SymbolTable
)
344 self
._Symb
.update(self
.LogicalOperators
)
346 self
._Len
= len(self
._Expr
)
348 self
._WarnExcept
= None
350 # Literal token without any conversion
351 self
._LiteralToken
= ''
353 # Public entry for this class
354 # @param RealValue: False: only evaluate if the expression is true or false, used for conditional expression
355 # True : return the evaluated str(value), used for PCD value
357 # @return: True or False if RealValue is False
358 # Evaluated value of string format if RealValue is True
360 def __call__(self
, RealValue
=False, Depth
=0):
366 self
._Expr
= self
._Expr
.strip()
367 if RealValue
and Depth
== 0:
368 self
._Token
= self
._Expr
369 if self
.__IsNumberToken
():
373 Token
= self
._GetToken
()
374 except BadExpression
:
376 if isinstance(Token
, type('')) and Token
.startswith('{') and Token
.endswith('}') and self
._Idx
>= self
._Len
:
382 Val
= self
._ConExpr
()
384 if isinstance(Val
, type('')):
390 elif not Val
.startswith('L"') and not Val
.startswith('{') and not Val
.startswith("L'"):
392 RealVal
= '"' + RealVal
+ '"'
394 # The expression has been parsed, but the end of expression is not reached
395 # It means the rest does not comply EBNF of <Expression>
396 if self
._Idx
!= self
._Len
:
397 raise BadExpression(ERR_SNYTAX
% self
._Expr
[self
._Idx
:])
400 RetVal
= str(RealVal
)
407 self
._WarnExcept
.result
= RetVal
408 raise self
._WarnExcept
412 # Template function to parse binary operators which have same precedence
413 # Expr [Operator Expr]*
414 def _ExprFuncTemplate(self
, EvalFunc
, OpSet
):
416 while self
._IsOperator
(OpSet
):
420 if self
._IsOperator
({':'}):
428 Val
= self
.Eval(Op
, Val
, EvalFunc())
429 except WrnExpression
as Warn
:
430 self
._WarnExcept
= Warn
435 return self
._ExprFuncTemplate
(self
._OrExpr
, {'?', ':'})
439 return self
._ExprFuncTemplate
(self
._AndExpr
, {"OR", "or", "||"})
443 return self
._ExprFuncTemplate
(self
._BitOr
, {"AND", "and", "&&"})
447 return self
._ExprFuncTemplate
(self
._BitXor
, {"|"})
451 return self
._ExprFuncTemplate
(self
._BitAnd
, {"XOR", "xor", "^"})
455 return self
._ExprFuncTemplate
(self
._EqExpr
, {"&"})
459 Val
= self
._RelExpr
()
460 while self
._IsOperator
({"==", "!=", "EQ", "NE", "IN", "in", "!", "NOT", "not"}):
462 if Op
in {"!", "NOT", "not"}:
463 if not self
._IsOperator
({"IN", "in"}):
464 raise BadExpression(ERR_REL_NOT_IN
)
465 Op
+= ' ' + self
._Token
467 Val
= self
.Eval(Op
, Val
, self
._RelExpr
())
468 except WrnExpression
as Warn
:
469 self
._WarnExcept
= Warn
475 return self
._ExprFuncTemplate
(self
._ShiftExpr
, {"<=", ">=", "<", ">", "LE", "GE", "LT", "GT"})
477 def _ShiftExpr(self
):
478 return self
._ExprFuncTemplate
(self
._AddExpr
, {"<<", ">>"})
482 return self
._ExprFuncTemplate
(self
._MulExpr
, {"+", "-"})
486 return self
._ExprFuncTemplate
(self
._UnaryExpr
, {"*", "/", "%"})
489 def _UnaryExpr(self
):
490 if self
._IsOperator
({"!", "NOT", "not"}):
491 Val
= self
._UnaryExpr
()
493 return self
.Eval('not', Val
)
494 except WrnExpression
as Warn
:
495 self
._WarnExcept
= Warn
497 if self
._IsOperator
({"~"}):
498 Val
= self
._UnaryExpr
()
500 return self
.Eval('~', Val
)
501 except WrnExpression
as Warn
:
502 self
._WarnExcept
= Warn
504 return self
._IdenExpr
()
506 # Parse identifier or encapsulated expression
508 Tk
= self
._GetToken
()
510 Val
= self
._ConExpr
()
512 # _GetToken may also raise BadExpression
513 if self
._GetToken
() != ')':
514 raise BadExpression(ERR_MATCH
)
515 except BadExpression
:
516 raise BadExpression(ERR_MATCH
)
520 # Skip whitespace or tab
522 for Char
in self
._Expr
[self
._Idx
:]:
523 if Char
not in ' \t':
527 # Try to convert string to number
528 def __IsNumberToken(self
):
530 if self
._Token
.lower()[0:2] == '0x' and len(self
._Token
) > 2:
532 if self
._Token
.startswith('"') or self
._Token
.startswith('L"'):
534 for Index
in range(len(self
._Token
)):
535 if self
._Token
[Index
] in {'"'}:
536 if self
._Token
[Index
- 1] == '\\':
539 if Flag
== 2 and self
._Token
.endswith('"'):
541 if self
._Token
.startswith("'") or self
._Token
.startswith("L'"):
543 for Index
in range(len(self
._Token
)):
544 if self
._Token
[Index
] in {"'"}:
545 if self
._Token
[Index
- 1] == '\\':
548 if Flag
== 2 and self
._Token
.endswith("'"):
551 self
._Token
= int(self
._Token
, Radix
)
559 def __GetArray(self
):
562 self
.__GetNList
(True)
563 Token
+= self
._LiteralToken
564 if self
._Idx
>= self
._Len
or self
._Expr
[self
._Idx
] != '}':
565 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
568 # All whitespace and tabs in array are already stripped.
569 IsArray
= IsGuid
= False
570 if len(Token
.split(',')) == 11 and len(Token
.split(',{')) == 2 \
571 and len(Token
.split('},')) == 1:
572 HexLen
= [11, 6, 6, 5, 4, 4, 4, 4, 4, 4, 6]
573 HexList
= Token
.split(',')
574 if HexList
[3].startswith('{') and \
575 not [Index
for Index
, Hex
in enumerate(HexList
) if len(Hex
) > HexLen
[Index
]]:
577 if Token
.lstrip('{').rstrip('}').find('{') == -1:
578 if not [Hex
for Hex
in Token
.lstrip('{').rstrip('}').split(',') if len(Hex
) > 4]:
580 if not IsArray
and not IsGuid
:
581 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
583 self
._Token
= self
._LiteralToken
= Token
586 # Parse string, the format must be: "..."
587 def __GetString(self
):
593 # Replace escape \\\", \"
594 if self
._Expr
[Idx
] == '"':
595 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace('\\\"', '\\\'')
600 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
601 if not self
._Token
.endswith('"'):
602 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
603 #Replace escape \\\', \'
604 elif self
._Expr
[Idx
] == "'":
605 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace("\\\'", "\\\"")
610 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
611 if not self
._Token
.endswith("'"):
612 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
613 self
._Token
= self
._Token
[1:-1]
616 # Get token that is comprised by alphanumeric, underscore or dot(used by PCD)
617 # @param IsAlphaOp: Indicate if parsing general token or script operator(EQ, NE...)
618 def __GetIdToken(self
, IsAlphaOp
= False):
620 for Ch
in self
._Expr
[self
._Idx
:]:
621 if not self
.__IsIdChar
(Ch
) or ('?' in self
._Expr
and Ch
== ':'):
626 self
._Token
= self
._LiteralToken
= IdToken
628 self
.__ResolveToken
()
631 # Try to resolve token
632 def __ResolveToken(self
):
634 raise BadExpression(ERR_EMPTY_TOKEN
)
637 if PcdPattern
.match(self
._Token
):
638 if self
._Token
not in self
._Symb
:
639 Ex
= BadExpression(ERR_PCD_RESOLVE
% self
._Token
)
642 self
._Token
= ValueExpression(self
._Symb
[self
._Token
], self
._Symb
)(True, self
._Depth
+1)
643 if not isinstance(self
._Token
, type('')):
644 self
._LiteralToken
= hex(self
._Token
)
647 if self
._Token
.startswith('"'):
648 self
._Token
= self
._Token
[1:-1]
649 elif self
._Token
in {"FALSE", "false", "False"}:
651 elif self
._Token
in {"TRUE", "true", "True"}:
654 self
.__IsNumberToken
()
656 def __GetNList(self
, InArray
=False):
657 self
._GetSingleToken
()
658 if not self
.__IsHexLiteral
():
660 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
664 Expr
= self
._Expr
[self
._Idx
:]
665 if not Expr
.startswith(','):
668 NList
= self
._LiteralToken
669 while Expr
.startswith(','):
673 self
._GetSingleToken
()
674 if not self
.__IsHexLiteral
():
675 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
676 NList
+= self
._LiteralToken
678 Expr
= self
._Expr
[self
._Idx
:]
679 self
._Token
= self
._LiteralToken
= NList
682 def __IsHexLiteral(self
):
683 if self
._LiteralToken
.startswith('{') and \
684 self
._LiteralToken
.endswith('}'):
687 if gHexPattern
.match(self
._LiteralToken
):
688 Token
= self
._LiteralToken
[2:]
690 self
._LiteralToken
= '0x0'
692 self
._LiteralToken
= '0x' + Token
697 return self
.__GetNList
()
701 return Ch
in '._:' or Ch
.isalnum()
704 def _GetSingleToken(self
):
706 Expr
= self
._Expr
[self
._Idx
:]
707 if Expr
.startswith('L"'):
710 UStr
= self
.__GetString
()
711 self
._Token
= 'L"' + UStr
+ '"'
713 elif Expr
.startswith("L'"):
716 UStr
= self
.__GetString
()
717 self
._Token
= "L'" + UStr
+ "'"
719 elif Expr
.startswith("'"):
720 UStr
= self
.__GetString
()
721 self
._Token
= "'" + UStr
+ "'"
723 elif Expr
.startswith('UINT'):
724 Re
= re
.compile('(?:UINT8|UINT16|UINT32|UINT64)\((.+)\)')
726 RetValue
= Re
.search(Expr
).group(1)
728 raise BadExpression('Invalid Expression %s' % Expr
)
733 Prefix
= self
._Expr
[Idx
:self
._Idx
- 1]
736 TmpValue
= self
._Expr
[Idx
:self
._Idx
- 1]
737 TmpValue
= ValueExpression(TmpValue
)(True)
738 TmpValue
= '0x%x' % int(TmpValue
) if not isinstance(TmpValue
, type('')) else TmpValue
740 self
._Token
, Size
= ParseFieldValue(Prefix
+ '(' + TmpValue
+ ')')
746 Match
= gGuidPattern
.match(Expr
)
747 if Match
and not Expr
[Match
.end():Match
.end()+1].isalnum() \
748 and Expr
[Match
.end():Match
.end()+1] != '_':
749 self
._Idx
+= Match
.end()
750 self
._Token
= ValueExpression(GuidStringToGuidStructureString(Expr
[0:Match
.end()]))(True, self
._Depth
+1)
752 elif self
.__IsIdChar
(Ch
):
753 return self
.__GetIdToken
()
755 return self
.__GetString
()
757 return self
.__GetArray
()
758 elif Ch
== '(' or Ch
== ')':
763 raise BadExpression(ERR_VALID_TOKEN
% Expr
)
766 def _GetOperator(self
):
768 LegalOpLst
= ['&&', '||', '!=', '==', '>=', '<='] + self
.NonLetterOpLst
+ ['?', ':']
771 Expr
= self
._Expr
[self
._Idx
:]
773 # Reach end of expression
777 # Script operator: LT, GT, LE, GE, EQ, NE, and, or, xor, not
778 if Expr
[0].isalpha():
779 return self
.__GetIdToken
(True)
781 # Start to get regular operator: +, -, <, > ...
782 if Expr
[0] not in self
.NonLetterOpLst
:
787 if Ch
in self
.NonLetterOpLst
:
788 if '!' == Ch
and OpToken
:
795 if OpToken
not in LegalOpLst
:
796 raise BadExpression(ERR_OPERATOR_UNSUPPORT
% OpToken
)
797 self
._Token
= OpToken
800 class ValueExpressionEx(ValueExpression
):
801 def __init__(self
, PcdValue
, PcdType
, SymbolTable
={}):
802 ValueExpression
.__init
__(self
, PcdValue
, SymbolTable
)
803 self
.PcdValue
= PcdValue
804 self
.PcdType
= PcdType
806 def __call__(self
, RealValue
=False, Depth
=0):
807 PcdValue
= self
.PcdValue
809 PcdValue
= ValueExpression
.__call
__(self
, RealValue
, Depth
)
810 if self
.PcdType
== TAB_VOID
and (PcdValue
.startswith("'") or PcdValue
.startswith("L'")):
811 PcdValue
, Size
= ParseFieldValue(PcdValue
)
813 for I
in range(Size
):
814 PcdValueList
.append('0x%02X'%(PcdValue
& 0xff))
815 PcdValue
= PcdValue
>> 8
816 PcdValue
= '{' + ','.join(PcdValueList
) + '}'
817 elif self
.PcdType
in TAB_PCD_NUMERIC_TYPES
and (PcdValue
.startswith("'") or \
818 PcdValue
.startswith('"') or PcdValue
.startswith("L'") or PcdValue
.startswith('L"') or PcdValue
.startswith('{')):
820 except WrnExpression
as Value
:
821 PcdValue
= Value
.result
822 except BadExpression
as Value
:
823 if self
.PcdType
in TAB_PCD_NUMERIC_TYPES
:
824 PcdValue
= PcdValue
.strip()
825 if PcdValue
.startswith('{') and PcdValue
.endswith('}'):
826 PcdValue
= SplitPcdValueString(PcdValue
[1:-1])
827 if isinstance(PcdValue
, type([])):
831 for Item
in PcdValue
:
833 if Item
.startswith(TAB_UINT8
):
835 ValueType
= TAB_UINT8
836 elif Item
.startswith(TAB_UINT16
):
838 ValueType
= TAB_UINT16
839 elif Item
.startswith(TAB_UINT32
):
841 ValueType
= TAB_UINT32
842 elif Item
.startswith(TAB_UINT64
):
844 ValueType
= TAB_UINT64
845 elif Item
[0] in {'"', "'", 'L'}:
850 ValueType
= TAB_UINT8
851 Item
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
855 tmpValue
= int(Item
, 0)
857 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
858 except BadExpression
as Value
:
859 raise BadExpression(Value
)
862 ItemValue
, ItemSize
= ParseFieldValue(Item
)
864 ItemValue
= ParseFieldValue(Item
)[0]
866 if isinstance(ItemValue
, type('')):
867 ItemValue
= int(ItemValue
, 0)
869 TmpValue
= (ItemValue
<< (Size
* 8)) | TmpValue
870 Size
= Size
+ ItemSize
873 TmpValue
, Size
= ParseFieldValue(PcdValue
)
874 except BadExpression
as Value
:
875 raise BadExpression("Type: %s, Value: %s, %s" % (self
.PcdType
, PcdValue
, Value
))
876 if isinstance(TmpValue
, type('')):
878 TmpValue
= int(TmpValue
)
880 raise BadExpression(Value
)
882 PcdValue
= '0x%0{}X'.format(Size
) % (TmpValue
)
884 raise BadExpression('Type %s PCD Value is negative' % self
.PcdType
)
885 if self
.PcdType
== TAB_UINT8
and Size
> 1:
886 raise BadExpression('Type %s PCD Value Size is Larger than 1 byte' % self
.PcdType
)
887 if self
.PcdType
== TAB_UINT16
and Size
> 2:
888 raise BadExpression('Type %s PCD Value Size is Larger than 2 byte' % self
.PcdType
)
889 if self
.PcdType
== TAB_UINT32
and Size
> 4:
890 raise BadExpression('Type %s PCD Value Size is Larger than 4 byte' % self
.PcdType
)
891 if self
.PcdType
== TAB_UINT64
and Size
> 8:
892 raise BadExpression('Type %s PCD Value Size is Larger than 8 byte' % self
.PcdType
)
895 TmpValue
= long(PcdValue
)
897 if TmpValue
.bit_length() == 0:
900 for I
in range((TmpValue
.bit_length() + 7) / 8):
901 TmpList
.append('0x%02x' % ((TmpValue
>> I
* 8) & 0xff))
902 PcdValue
= '{' + ', '.join(TmpList
) + '}'
904 if PcdValue
.strip().startswith('{'):
905 PcdValueList
= SplitPcdValueString(PcdValue
.strip()[1:-1])
909 for Item
in PcdValueList
:
910 # compute byte offset of every LABEL
911 LabelList
= _ReLabel
.findall(Item
)
912 Item
= _ReLabel
.sub('', Item
)
915 for Label
in LabelList
:
916 if not IsValidCName(Label
):
917 raise BadExpression('%s is not a valid c variable name' % Label
)
918 if Label
not in LabelDict
:
919 LabelDict
[Label
] = str(LabelOffset
)
920 if Item
.startswith(TAB_UINT8
):
921 LabelOffset
= LabelOffset
+ 1
922 elif Item
.startswith(TAB_UINT16
):
923 LabelOffset
= LabelOffset
+ 2
924 elif Item
.startswith(TAB_UINT32
):
925 LabelOffset
= LabelOffset
+ 4
926 elif Item
.startswith(TAB_UINT64
):
927 LabelOffset
= LabelOffset
+ 8
930 ItemValue
, ItemSize
= ParseFieldValue(Item
)
931 LabelOffset
= LabelOffset
+ ItemSize
933 LabelOffset
= LabelOffset
+ 1
935 for Item
in PcdValueList
:
939 Item
= _ReLabel
.sub('', Item
)
943 OffsetList
= _ReOffset
.findall(Item
)
946 # replace each offset, except errors
947 for Offset
in OffsetList
:
949 Item
= Item
.replace('OFFSET_OF({})'.format(Offset
), LabelDict
[Offset
])
951 raise BadExpression('%s not defined' % Offset
)
953 NewPcdValueList
.append(Item
)
956 for Item
in NewPcdValueList
:
959 TokenSpaceGuidName
= ''
960 if Item
.startswith(TAB_GUID
) and Item
.endswith(')'):
962 TokenSpaceGuidName
= re
.search('GUID\((\w+)\)', Item
).group(1)
965 if TokenSpaceGuidName
and TokenSpaceGuidName
in self
._Symb
:
966 Item
= 'GUID(' + self
._Symb
[TokenSpaceGuidName
] + ')'
967 elif TokenSpaceGuidName
:
968 raise BadExpression('%s not found in DEC file' % TokenSpaceGuidName
)
969 Item
, Size
= ParseFieldValue(Item
)
970 for Index
in range(0, Size
):
971 ValueStr
= '0x%02X' % (int(Item
) & 255)
973 AllPcdValueList
.append(ValueStr
)
975 elif Item
.startswith('DEVICE_PATH') and Item
.endswith(')'):
976 Item
, Size
= ParseFieldValue(Item
)
977 AllPcdValueList
.append(Item
[1:-1])
981 if Item
.startswith(TAB_UINT8
):
983 ValueType
= TAB_UINT8
984 elif Item
.startswith(TAB_UINT16
):
986 ValueType
= TAB_UINT16
987 elif Item
.startswith(TAB_UINT32
):
989 ValueType
= TAB_UINT32
990 elif Item
.startswith(TAB_UINT64
):
992 ValueType
= TAB_UINT64
996 TmpValue
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
998 TmpValue
= ValueExpressionEx(Item
, self
.PcdType
, self
._Symb
)(True)
999 Item
= '0x%x' % TmpValue
if not isinstance(TmpValue
, type('')) else TmpValue
1001 ItemValue
, ItemSize
= ParseFieldValue(Item
)
1002 if Item
[0] not in {'"', 'L', '{'} and ItemSize
> 1:
1003 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
1005 ItemValue
= ParseFieldValue(Item
)[0]
1006 for I
in range(0, ItemSize
):
1007 ValueStr
= '0x%02X' % (int(ItemValue
) & 255)
1009 AllPcdValueList
.append(ValueStr
)
1013 PcdValue
= '{' + ','.join(AllPcdValueList
) + '}'
1015 raise BadExpression("Type: %s, Value: %s, %s"%(self
.PcdType
, PcdValue
, Value
))
1017 if PcdValue
== 'True':
1019 if PcdValue
== 'False':
1025 if __name__
== '__main__':
1028 input = raw_input('Input expr: ')
1032 print(ValueExpression(input)(True))
1033 print(ValueExpression(input)(False))
1034 except WrnExpression
as Ex
:
1037 except Exception as Ex
: