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
21 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
= 'The PCD should be FeatureFlag type or FixedAtBuild type: [%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
140 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
):
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
)
257 # For python2 long type
258 type(sys
.maxsize
+ 1) : 0,
264 if Operator
in {"!", "NOT", "not"}:
265 if isinstance(Oprand1
, type('')):
266 raise BadExpression(ERR_STRING_EXPR
% Operator
)
267 EvalStr
= 'not Oprand1'
268 elif Operator
in {"~"}:
269 if isinstance(Oprand1
, type('')):
270 raise BadExpression(ERR_STRING_EXPR
% Operator
)
271 EvalStr
= '~ Oprand1'
273 if Operator
in {"+", "-"} and (type(True) in {type(Oprand1
), type(Oprand2
)}):
274 # Boolean in '+'/'-' will be evaluated but raise warning
275 WrnExp
= WrnExpression(WRN_BOOL_EXPR
)
276 elif type('') in {type(Oprand1
), type(Oprand2
)} and not isinstance(Oprand1
, type(Oprand2
)):
277 # == between string and number/boolean will always return False, != return True
279 WrnExp
= WrnExpression(WRN_EQCMP_STR_OTHERS
)
280 WrnExp
.result
= False
282 elif Operator
== "!=":
283 WrnExp
= WrnExpression(WRN_NECMP_STR_OTHERS
)
287 raise BadExpression(ERR_RELCMP_STR_OTHERS
% Operator
)
288 elif TypeDict
[type(Oprand1
)] != TypeDict
[type(Oprand2
)]:
289 if Operator
in {"==", "!=", ">=", "<=", ">", "<"} and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
290 # comparison between number and boolean is allowed
292 elif Operator
in {'&', '|', '^', "and", "or"} and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
293 # bitwise and logical operation between number and boolean is allowed
296 raise BadExpression(ERR_EXPR_TYPE
)
297 if isinstance(Oprand1
, type('')) and isinstance(Oprand2
, type('')):
298 if (Oprand1
.startswith('L"') and not Oprand2
.startswith('L"')) or \
299 (not Oprand1
.startswith('L"') and Oprand2
.startswith('L"')):
300 raise BadExpression(ERR_STRING_CMP
% (Oprand1
, Operator
, Oprand2
))
301 if 'in' in Operator
and isinstance(Oprand2
, type('')):
302 Oprand2
= Oprand2
.split()
303 EvalStr
= 'Oprand1 ' + Operator
+ ' Oprand2'
305 # Local symbols used by built in eval function
311 Val
= eval(EvalStr
, {}, Dict
)
312 except Exception as Excpt
:
313 raise BadExpression(str(Excpt
))
315 if Operator
in {'and', 'or'}:
326 def __init__(self
, Expression
, SymbolTable
={}):
327 super().__init
__(self
, Expression
, SymbolTable
)
328 self
._NoProcess
= False
329 if not isinstance(Expression
, type('')):
330 self
._Expr
= Expression
331 self
._NoProcess
= True
334 self
._Expr
= ReplaceExprMacro(Expression
.strip(),
336 SupportedInMacroList
)
338 if not self
._Expr
.strip():
339 raise BadExpression(ERR_EMPTY_EXPR
)
342 # The symbol table including PCD and macro mapping
344 self
._Symb
= copy
.deepcopy(SymbolTable
)
345 self
._Symb
.update(self
.LogicalOperators
)
347 self
._Len
= len(self
._Expr
)
349 self
._WarnExcept
= None
351 # Literal token without any conversion
352 self
._LiteralToken
= ''
354 # Public entry for this class
355 # @param RealValue: False: only evaluate if the expression is true or false, used for conditional expression
356 # True : return the evaluated str(value), used for PCD value
358 # @return: True or False if RealValue is False
359 # Evaluated value of string format if RealValue is True
361 def __call__(self
, RealValue
=False, Depth
=0):
367 self
._Expr
= self
._Expr
.strip()
368 if RealValue
and Depth
== 0:
369 self
._Token
= self
._Expr
370 if self
.__IsNumberToken
():
374 Token
= self
._GetToken
()
375 except BadExpression
:
377 if isinstance(Token
, type('')) and Token
.startswith('{') and Token
.endswith('}') and self
._Idx
>= self
._Len
:
383 Val
= self
._ConExpr
()
385 if isinstance(Val
, type('')):
391 elif not Val
.startswith('L"') and not Val
.startswith('{') and not Val
.startswith("L'"):
393 RealVal
= '"' + RealVal
+ '"'
395 # The expression has been parsed, but the end of expression is not reached
396 # It means the rest does not comply EBNF of <Expression>
397 if self
._Idx
!= self
._Len
:
398 raise BadExpression(ERR_SNYTAX
% self
._Expr
[self
._Idx
:])
401 RetVal
= str(RealVal
)
408 self
._WarnExcept
.result
= RetVal
409 raise self
._WarnExcept
413 # Template function to parse binary operators which have same precedence
414 # Expr [Operator Expr]*
415 def _ExprFuncTemplate(self
, EvalFunc
, OpSet
):
417 while self
._IsOperator
(OpSet
):
421 if self
._IsOperator
({':'}):
429 Val
= self
.Eval(Op
, Val
, EvalFunc())
430 except WrnExpression
as Warn
:
431 self
._WarnExcept
= Warn
436 return self
._ExprFuncTemplate
(self
._OrExpr
, {'?', ':'})
440 return self
._ExprFuncTemplate
(self
._AndExpr
, {"OR", "or", "||"})
444 return self
._ExprFuncTemplate
(self
._BitOr
, {"AND", "and", "&&"})
448 return self
._ExprFuncTemplate
(self
._BitXor
, {"|"})
452 return self
._ExprFuncTemplate
(self
._BitAnd
, {"XOR", "xor", "^"})
456 return self
._ExprFuncTemplate
(self
._EqExpr
, {"&"})
460 Val
= self
._RelExpr
()
461 while self
._IsOperator
({"==", "!=", "EQ", "NE", "IN", "in", "!", "NOT", "not"}):
463 if Op
in {"!", "NOT", "not"}:
464 if not self
._IsOperator
({"IN", "in"}):
465 raise BadExpression(ERR_REL_NOT_IN
)
466 Op
+= ' ' + self
._Token
468 Val
= self
.Eval(Op
, Val
, self
._RelExpr
())
469 except WrnExpression
as Warn
:
470 self
._WarnExcept
= Warn
476 return self
._ExprFuncTemplate
(self
._ShiftExpr
, {"<=", ">=", "<", ">", "LE", "GE", "LT", "GT"})
478 def _ShiftExpr(self
):
479 return self
._ExprFuncTemplate
(self
._AddExpr
, {"<<", ">>"})
483 return self
._ExprFuncTemplate
(self
._MulExpr
, {"+", "-"})
487 return self
._ExprFuncTemplate
(self
._UnaryExpr
, {"*", "/", "%"})
490 def _UnaryExpr(self
):
491 if self
._IsOperator
({"!", "NOT", "not"}):
492 Val
= self
._UnaryExpr
()
494 return self
.Eval('not', Val
)
495 except WrnExpression
as Warn
:
496 self
._WarnExcept
= Warn
498 if self
._IsOperator
({"~"}):
499 Val
= self
._UnaryExpr
()
501 return self
.Eval('~', Val
)
502 except WrnExpression
as Warn
:
503 self
._WarnExcept
= Warn
505 return self
._IdenExpr
()
507 # Parse identifier or encapsulated expression
509 Tk
= self
._GetToken
()
511 Val
= self
._ConExpr
()
513 # _GetToken may also raise BadExpression
514 if self
._GetToken
() != ')':
515 raise BadExpression(ERR_MATCH
)
516 except BadExpression
:
517 raise BadExpression(ERR_MATCH
)
521 # Skip whitespace or tab
523 for Char
in self
._Expr
[self
._Idx
:]:
524 if Char
not in ' \t':
528 # Try to convert string to number
529 def __IsNumberToken(self
):
531 if self
._Token
.lower()[0:2] == '0x' and len(self
._Token
) > 2:
533 if self
._Token
.startswith('"') or self
._Token
.startswith('L"'):
535 for Index
in range(len(self
._Token
)):
536 if self
._Token
[Index
] in {'"'}:
537 if self
._Token
[Index
- 1] == '\\':
540 if Flag
== 2 and self
._Token
.endswith('"'):
542 if self
._Token
.startswith("'") or self
._Token
.startswith("L'"):
544 for Index
in range(len(self
._Token
)):
545 if self
._Token
[Index
] in {"'"}:
546 if self
._Token
[Index
- 1] == '\\':
549 if Flag
== 2 and self
._Token
.endswith("'"):
552 self
._Token
= int(self
._Token
, Radix
)
560 def __GetArray(self
):
563 self
.__GetNList
(True)
564 Token
+= self
._LiteralToken
565 if self
._Idx
>= self
._Len
or self
._Expr
[self
._Idx
] != '}':
566 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
569 # All whitespace and tabs in array are already stripped.
570 IsArray
= IsGuid
= False
571 if len(Token
.split(',')) == 11 and len(Token
.split(',{')) == 2 \
572 and len(Token
.split('},')) == 1:
573 HexLen
= [11, 6, 6, 5, 4, 4, 4, 4, 4, 4, 6]
574 HexList
= Token
.split(',')
575 if HexList
[3].startswith('{') and \
576 not [Index
for Index
, Hex
in enumerate(HexList
) if len(Hex
) > HexLen
[Index
]]:
578 if Token
.lstrip('{').rstrip('}').find('{') == -1:
579 if not [Hex
for Hex
in Token
.lstrip('{').rstrip('}').split(',') if len(Hex
) > 4]:
581 if not IsArray
and not IsGuid
:
582 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
584 self
._Token
= self
._LiteralToken
= Token
587 # Parse string, the format must be: "..."
588 def __GetString(self
):
594 # Replace escape \\\", \"
595 if self
._Expr
[Idx
] == '"':
596 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace('\\\"', '\\\'')
601 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
602 if not self
._Token
.endswith('"'):
603 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
604 #Replace escape \\\', \'
605 elif self
._Expr
[Idx
] == "'":
606 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace("\\\'", "\\\"")
611 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
612 if not self
._Token
.endswith("'"):
613 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
614 self
._Token
= self
._Token
[1:-1]
617 # Get token that is comprised by alphanumeric, underscore or dot(used by PCD)
618 # @param IsAlphaOp: Indicate if parsing general token or script operator(EQ, NE...)
619 def __GetIdToken(self
, IsAlphaOp
= False):
621 for Ch
in self
._Expr
[self
._Idx
:]:
622 if not self
.__IsIdChar
(Ch
) or ('?' in self
._Expr
and Ch
== ':'):
627 self
._Token
= self
._LiteralToken
= IdToken
629 self
.__ResolveToken
()
632 # Try to resolve token
633 def __ResolveToken(self
):
635 raise BadExpression(ERR_EMPTY_TOKEN
)
638 if PcdPattern
.match(self
._Token
):
639 if self
._Token
not in self
._Symb
:
640 Ex
= BadExpression(ERR_PCD_RESOLVE
% self
._Token
)
643 self
._Token
= ValueExpression(self
._Symb
[self
._Token
], self
._Symb
)(True, self
._Depth
+1)
644 if not isinstance(self
._Token
, type('')):
645 self
._LiteralToken
= hex(self
._Token
)
648 if self
._Token
.startswith('"'):
649 self
._Token
= self
._Token
[1:-1]
650 elif self
._Token
in {"FALSE", "false", "False"}:
652 elif self
._Token
in {"TRUE", "true", "True"}:
655 self
.__IsNumberToken
()
657 def __GetNList(self
, InArray
=False):
658 self
._GetSingleToken
()
659 if not self
.__IsHexLiteral
():
661 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
665 Expr
= self
._Expr
[self
._Idx
:]
666 if not Expr
.startswith(','):
669 NList
= self
._LiteralToken
670 while Expr
.startswith(','):
674 self
._GetSingleToken
()
675 if not self
.__IsHexLiteral
():
676 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
677 NList
+= self
._LiteralToken
679 Expr
= self
._Expr
[self
._Idx
:]
680 self
._Token
= self
._LiteralToken
= NList
683 def __IsHexLiteral(self
):
684 if self
._LiteralToken
.startswith('{') and \
685 self
._LiteralToken
.endswith('}'):
688 if gHexPattern
.match(self
._LiteralToken
):
689 Token
= self
._LiteralToken
[2:]
691 self
._LiteralToken
= '0x0'
693 self
._LiteralToken
= '0x' + Token
698 return self
.__GetNList
()
702 return Ch
in '._:' or Ch
.isalnum()
705 def _GetSingleToken(self
):
707 Expr
= self
._Expr
[self
._Idx
:]
708 if Expr
.startswith('L"'):
711 UStr
= self
.__GetString
()
712 self
._Token
= 'L"' + UStr
+ '"'
714 elif Expr
.startswith("L'"):
717 UStr
= self
.__GetString
()
718 self
._Token
= "L'" + UStr
+ "'"
720 elif Expr
.startswith("'"):
721 UStr
= self
.__GetString
()
722 self
._Token
= "'" + UStr
+ "'"
724 elif Expr
.startswith('UINT'):
725 Re
= re
.compile('(?:UINT8|UINT16|UINT32|UINT64)\((.+)\)')
727 RetValue
= Re
.search(Expr
).group(1)
729 raise BadExpression('Invalid Expression %s' % Expr
)
734 Prefix
= self
._Expr
[Idx
:self
._Idx
- 1]
737 TmpValue
= self
._Expr
[Idx
:self
._Idx
- 1]
738 TmpValue
= ValueExpression(TmpValue
)(True)
739 TmpValue
= '0x%x' % int(TmpValue
) if not isinstance(TmpValue
, type('')) else TmpValue
741 self
._Token
, Size
= ParseFieldValue(Prefix
+ '(' + TmpValue
+ ')')
747 Match
= gGuidPattern
.match(Expr
)
748 if Match
and not Expr
[Match
.end():Match
.end()+1].isalnum() \
749 and Expr
[Match
.end():Match
.end()+1] != '_':
750 self
._Idx
+= Match
.end()
751 self
._Token
= ValueExpression(GuidStringToGuidStructureString(Expr
[0:Match
.end()]))(True, self
._Depth
+1)
753 elif self
.__IsIdChar
(Ch
):
754 return self
.__GetIdToken
()
756 return self
.__GetString
()
758 return self
.__GetArray
()
759 elif Ch
== '(' or Ch
== ')':
764 raise BadExpression(ERR_VALID_TOKEN
% Expr
)
767 def _GetOperator(self
):
769 LegalOpLst
= ['&&', '||', '!=', '==', '>=', '<='] + self
.NonLetterOpLst
+ ['?', ':']
772 Expr
= self
._Expr
[self
._Idx
:]
774 # Reach end of expression
778 # Script operator: LT, GT, LE, GE, EQ, NE, and, or, xor, not
779 if Expr
[0].isalpha():
780 return self
.__GetIdToken
(True)
782 # Start to get regular operator: +, -, <, > ...
783 if Expr
[0] not in self
.NonLetterOpLst
:
788 if Ch
in self
.NonLetterOpLst
:
789 if Ch
in ['!', '~'] and OpToken
:
796 if OpToken
not in LegalOpLst
:
797 raise BadExpression(ERR_OPERATOR_UNSUPPORT
% OpToken
)
798 self
._Token
= OpToken
801 class ValueExpressionEx(ValueExpression
):
802 def __init__(self
, PcdValue
, PcdType
, SymbolTable
={}):
803 ValueExpression
.__init
__(self
, PcdValue
, SymbolTable
)
804 self
.PcdValue
= PcdValue
805 self
.PcdType
= PcdType
807 def __call__(self
, RealValue
=False, Depth
=0):
808 PcdValue
= self
.PcdValue
810 PcdValue
= ValueExpression
.__call
__(self
, RealValue
, Depth
)
811 if self
.PcdType
== TAB_VOID
and (PcdValue
.startswith("'") or PcdValue
.startswith("L'")):
812 PcdValue
, Size
= ParseFieldValue(PcdValue
)
814 for I
in range(Size
):
815 PcdValueList
.append('0x%02X'%(PcdValue
& 0xff))
816 PcdValue
= PcdValue
>> 8
817 PcdValue
= '{' + ','.join(PcdValueList
) + '}'
818 elif self
.PcdType
in TAB_PCD_NUMERIC_TYPES
and (PcdValue
.startswith("'") or \
819 PcdValue
.startswith('"') or PcdValue
.startswith("L'") or PcdValue
.startswith('L"') or PcdValue
.startswith('{')):
821 except WrnExpression
as Value
:
822 PcdValue
= Value
.result
823 except BadExpression
as Value
:
824 if self
.PcdType
in TAB_PCD_NUMERIC_TYPES
:
825 PcdValue
= PcdValue
.strip()
826 if PcdValue
.startswith('{') and PcdValue
.endswith('}'):
827 PcdValue
= SplitPcdValueString(PcdValue
[1:-1])
828 if isinstance(PcdValue
, type([])):
832 for Item
in PcdValue
:
834 if Item
.startswith(TAB_UINT8
):
836 ValueType
= TAB_UINT8
837 elif Item
.startswith(TAB_UINT16
):
839 ValueType
= TAB_UINT16
840 elif Item
.startswith(TAB_UINT32
):
842 ValueType
= TAB_UINT32
843 elif Item
.startswith(TAB_UINT64
):
845 ValueType
= TAB_UINT64
846 elif Item
[0] in {'"', "'", 'L'}:
851 ValueType
= TAB_UINT8
852 Item
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
856 tmpValue
= int(Item
, 0)
858 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
859 except BadExpression
as Value
:
860 raise BadExpression(Value
)
863 ItemValue
, ItemSize
= ParseFieldValue(Item
)
865 ItemValue
= ParseFieldValue(Item
)[0]
867 if isinstance(ItemValue
, type('')):
868 ItemValue
= int(ItemValue
, 0)
870 TmpValue
= (ItemValue
<< (Size
* 8)) | TmpValue
871 Size
= Size
+ ItemSize
874 TmpValue
, Size
= ParseFieldValue(PcdValue
)
875 except BadExpression
as Value
:
876 raise BadExpression("Type: %s, Value: %s, %s" % (self
.PcdType
, PcdValue
, Value
))
877 if isinstance(TmpValue
, type('')):
879 TmpValue
= int(TmpValue
)
881 raise BadExpression(Value
)
883 PcdValue
= '0x%0{}X'.format(Size
) % (TmpValue
)
885 raise BadExpression('Type %s PCD Value is negative' % self
.PcdType
)
886 if self
.PcdType
== TAB_UINT8
and Size
> 1:
887 raise BadExpression('Type %s PCD Value Size is Larger than 1 byte' % self
.PcdType
)
888 if self
.PcdType
== TAB_UINT16
and Size
> 2:
889 raise BadExpression('Type %s PCD Value Size is Larger than 2 byte' % self
.PcdType
)
890 if self
.PcdType
== TAB_UINT32
and Size
> 4:
891 raise BadExpression('Type %s PCD Value Size is Larger than 4 byte' % self
.PcdType
)
892 if self
.PcdType
== TAB_UINT64
and Size
> 8:
893 raise BadExpression('Type %s PCD Value Size is Larger than 8 byte' % self
.PcdType
)
896 TmpValue
= int(PcdValue
)
898 if TmpValue
.bit_length() == 0:
901 for I
in range((TmpValue
.bit_length() + 7) / 8):
902 TmpList
.append('0x%02x' % ((TmpValue
>> I
* 8) & 0xff))
903 PcdValue
= '{' + ', '.join(TmpList
) + '}'
905 if PcdValue
.strip().startswith('{'):
906 PcdValueList
= SplitPcdValueString(PcdValue
.strip()[1:-1])
910 for Item
in PcdValueList
:
911 # compute byte offset of every LABEL
912 LabelList
= _ReLabel
.findall(Item
)
913 Item
= _ReLabel
.sub('', Item
)
916 for Label
in LabelList
:
917 if not IsValidCName(Label
):
918 raise BadExpression('%s is not a valid c variable name' % Label
)
919 if Label
not in LabelDict
:
920 LabelDict
[Label
] = str(LabelOffset
)
921 if Item
.startswith(TAB_UINT8
):
922 LabelOffset
= LabelOffset
+ 1
923 elif Item
.startswith(TAB_UINT16
):
924 LabelOffset
= LabelOffset
+ 2
925 elif Item
.startswith(TAB_UINT32
):
926 LabelOffset
= LabelOffset
+ 4
927 elif Item
.startswith(TAB_UINT64
):
928 LabelOffset
= LabelOffset
+ 8
931 ItemValue
, ItemSize
= ParseFieldValue(Item
)
932 LabelOffset
= LabelOffset
+ ItemSize
934 LabelOffset
= LabelOffset
+ 1
936 for Item
in PcdValueList
:
940 Item
= _ReLabel
.sub('', Item
)
944 OffsetList
= _ReOffset
.findall(Item
)
947 # replace each offset, except errors
948 for Offset
in OffsetList
:
950 Item
= Item
.replace('OFFSET_OF({})'.format(Offset
), LabelDict
[Offset
])
952 raise BadExpression('%s not defined' % Offset
)
954 NewPcdValueList
.append(Item
)
957 for Item
in NewPcdValueList
:
960 TokenSpaceGuidName
= ''
961 if Item
.startswith(TAB_GUID
) and Item
.endswith(')'):
963 TokenSpaceGuidName
= re
.search('GUID\((\w+)\)', Item
).group(1)
966 if TokenSpaceGuidName
and TokenSpaceGuidName
in self
._Symb
:
967 Item
= 'GUID(' + self
._Symb
[TokenSpaceGuidName
] + ')'
968 elif TokenSpaceGuidName
:
969 raise BadExpression('%s not found in DEC file' % TokenSpaceGuidName
)
970 Item
, Size
= ParseFieldValue(Item
)
971 for Index
in range(0, Size
):
972 ValueStr
= '0x%02X' % (int(Item
) & 255)
974 AllPcdValueList
.append(ValueStr
)
976 elif Item
.startswith('DEVICE_PATH') and Item
.endswith(')'):
977 Item
, Size
= ParseFieldValue(Item
)
978 AllPcdValueList
.append(Item
[1:-1])
982 if Item
.startswith(TAB_UINT8
):
984 ValueType
= TAB_UINT8
985 elif Item
.startswith(TAB_UINT16
):
987 ValueType
= TAB_UINT16
988 elif Item
.startswith(TAB_UINT32
):
990 ValueType
= TAB_UINT32
991 elif Item
.startswith(TAB_UINT64
):
993 ValueType
= TAB_UINT64
997 TmpValue
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
999 TmpValue
= ValueExpressionEx(Item
, self
.PcdType
, self
._Symb
)(True)
1000 Item
= '0x%x' % TmpValue
if not isinstance(TmpValue
, type('')) else TmpValue
1002 ItemValue
, ItemSize
= ParseFieldValue(Item
)
1003 if Item
[0] not in {'"', 'L', '{'} and ItemSize
> 1:
1004 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
1006 ItemValue
= ParseFieldValue(Item
)[0]
1007 for I
in range(0, ItemSize
):
1008 ValueStr
= '0x%02X' % (int(ItemValue
) & 255)
1010 AllPcdValueList
.append(ValueStr
)
1014 PcdValue
= '{' + ','.join(AllPcdValueList
) + '}'
1016 raise BadExpression("Type: %s, Value: %s, %s"%(self
.PcdType
, PcdValue
, Value
))
1018 if PcdValue
== 'True':
1020 if PcdValue
== 'False':
1026 if __name__
== '__main__':
1029 input = input('Input expr: ')
1033 print(ValueExpression(input)(True))
1034 print(ValueExpression(input)(False))
1035 except WrnExpression
as Ex
:
1038 except Exception as Ex
: