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
, IsFieldValueAnArray
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
)
122 def IsValidCString(Str
):
123 ValidString
= re
.compile(r
'[_a-zA-Z][_0-9a-zA-Z]*$')
124 if not ValidString
.match(Str
):
128 def BuildOptionValue(PcdValue
, GuidDict
):
130 if PcdValue
.startswith('H'):
131 InputValue
= PcdValue
[1:]
132 elif PcdValue
.startswith("L'") or PcdValue
.startswith("'"):
133 InputValue
= PcdValue
134 elif PcdValue
.startswith('L'):
135 InputValue
= 'L"' + PcdValue
[1:] + '"'
137 InputValue
= PcdValue
138 if IsFieldValueAnArray(InputValue
):
142 PcdValue
= ValueExpressionEx(InputValue
, 'VOID*', GuidDict
)(True)
149 def ReplaceExprMacro(String
, Macros
, ExceptionList
= None):
150 StrList
= SplitString(String
)
151 for i
, String
in enumerate(StrList
):
153 if String
.startswith('"'):
155 MacroStartPos
= String
.find('$(')
156 if MacroStartPos
< 0:
157 for Pcd
in gPlatformPcds
.keys():
159 if Pcd
not in gConditionalPcds
:
160 gConditionalPcds
.append(Pcd
)
163 while MacroStartPos
>= 0:
164 RetStr
= String
[0:MacroStartPos
]
165 MacroEndPos
= String
.find(')', MacroStartPos
)
167 raise BadExpression(ERR_MACRO_TOKEN
% String
[MacroStartPos
:])
168 Macro
= String
[MacroStartPos
+2:MacroEndPos
]
169 if Macro
not in Macros
:
170 # From C reference manual:
171 # If an undefined macro name appears in the constant-expression of
172 # !if or !elif, it is replaced by the integer constant 0.
175 Tklst
= RetStr
.split()
176 if Tklst
and Tklst
[-1] in ['IN', 'in'] and ExceptionList
and Macro
not in ExceptionList
:
177 raise BadExpression(ERR_IN_OPERAND
)
178 # Make sure the macro in exception list is encapsulated by double quote
179 # For example: DEFINE ARCH = IA32 X64
180 # $(ARCH) is replaced with "IA32 X64"
181 if ExceptionList
and Macro
in ExceptionList
:
182 RetStr
+= '"' + Macros
[Macro
] + '"'
183 elif Macros
[Macro
].strip():
184 RetStr
+= Macros
[Macro
]
188 RetStr
+= Macros
[Macro
]
189 RetStr
+= String
[MacroEndPos
+1:]
191 MacroStartPos
= String
.find('$(')
193 return ''.join(StrList
)
195 # transfer int to string for in/not in expression
199 StrList
.append(chr(Value
& 0xff))
201 Value
= '"' + ''.join(StrList
) + '"'
204 SupportedInMacroList
= ['TARGET', 'TOOL_CHAIN_TAG', 'ARCH', 'FAMILY']
206 class ValueExpression(object):
207 # Logical operator mapping
209 '&&' : 'and', '||' : 'or',
210 '!' : 'not', 'AND': 'and',
211 'OR' : 'or' , 'NOT': 'not',
212 'XOR': '^' , 'xor': '^',
213 'EQ' : '==' , 'NE' : '!=',
214 'GT' : '>' , 'LT' : '<',
215 'GE' : '>=' , 'LE' : '<=',
219 NonLetterOpLst
= ['+', '-', '*', '/', '%', '&', '|', '^', '~', '<<', '>>', '!', '=', '>', '<', '?', ':']
221 PcdPattern
= re
.compile(r
'[_a-zA-Z][0-9A-Za-z_]*\.[_a-zA-Z][0-9A-Za-z_]*$')
222 HexPattern
= re
.compile(r
'0[xX][0-9a-fA-F]+$')
223 RegGuidPattern
= re
.compile(r
'[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}')
225 SymbolPattern
= re
.compile("("
226 "\$\([A-Z][A-Z0-9_]*\)|\$\(\w+\.\w+\)|\w+\.\w+|"
228 "(?<=\W)AND(?=\W)|(?<=\W)OR(?=\W)|(?<=\W)NOT(?=\W)|(?<=\W)XOR(?=\W)|"
229 "(?<=\W)EQ(?=\W)|(?<=\W)NE(?=\W)|(?<=\W)GT(?=\W)|(?<=\W)LT(?=\W)|(?<=\W)GE(?=\W)|(?<=\W)LE(?=\W)"
233 def Eval(Operator
, Oprand1
, Oprand2
= None):
236 if Operator
not in ["==", "!=", ">=", "<=", ">", "<", "in", "not in"] and \
237 (type(Oprand1
) == type('') or type(Oprand2
) == type('')):
238 raise BadExpression(ERR_STRING_EXPR
% Operator
)
239 if Operator
in ['in', 'not in']:
240 if type(Oprand1
) != type(''):
241 Oprand1
= IntToStr(Oprand1
)
242 if type(Oprand2
) != type(''):
243 Oprand2
= IntToStr(Oprand2
)
252 if Operator
in ["!", "NOT", "not"]:
253 if type(Oprand1
) == type(''):
254 raise BadExpression(ERR_STRING_EXPR
% Operator
)
255 EvalStr
= 'not Oprand1'
256 elif Operator
in ["~"]:
257 if type(Oprand1
) == type(''):
258 raise BadExpression(ERR_STRING_EXPR
% Operator
)
259 EvalStr
= '~ Oprand1'
261 if Operator
in ["+", "-"] and (type(True) in [type(Oprand1
), type(Oprand2
)]):
262 # Boolean in '+'/'-' will be evaluated but raise warning
263 WrnExp
= WrnExpression(WRN_BOOL_EXPR
)
264 elif type('') in [type(Oprand1
), type(Oprand2
)] and type(Oprand1
)!= type(Oprand2
):
265 # == between string and number/boolean will always return False, != return True
267 WrnExp
= WrnExpression(WRN_EQCMP_STR_OTHERS
)
268 WrnExp
.result
= False
270 elif Operator
== "!=":
271 WrnExp
= WrnExpression(WRN_NECMP_STR_OTHERS
)
275 raise BadExpression(ERR_RELCMP_STR_OTHERS
% Operator
)
276 elif TypeDict
[type(Oprand1
)] != TypeDict
[type(Oprand2
)]:
277 if Operator
in ["==", "!=", ">=", "<=", ">", "<"] and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
278 # comparison between number and boolean is allowed
280 elif Operator
in ['&', '|', '^', "and", "or"] and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
281 # bitwise and logical operation between number and boolean is allowed
284 raise BadExpression(ERR_EXPR_TYPE
)
285 if type(Oprand1
) == type('') and type(Oprand2
) == type(''):
286 if (Oprand1
.startswith('L"') and not Oprand2
.startswith('L"')) or \
287 (not Oprand1
.startswith('L"') and Oprand2
.startswith('L"')):
288 raise BadExpression(ERR_STRING_CMP
% (Oprand1
, Operator
, Oprand2
))
289 if 'in' in Operator
and type(Oprand2
) == type(''):
290 Oprand2
= Oprand2
.split()
291 EvalStr
= 'Oprand1 ' + Operator
+ ' Oprand2'
293 # Local symbols used by built in eval function
299 Val
= eval(EvalStr
, {}, Dict
)
300 except Exception, Excpt
:
301 raise BadExpression(str(Excpt
))
303 if Operator
in ['and', 'or']:
314 def __init__(self
, Expression
, SymbolTable
={}):
315 self
._NoProcess
= False
316 if type(Expression
) != type(''):
317 self
._Expr
= Expression
318 self
._NoProcess
= True
321 self
._Expr
= ReplaceExprMacro(Expression
.strip(),
323 SupportedInMacroList
)
325 if not self
._Expr
.strip():
326 raise BadExpression(ERR_EMPTY_EXPR
)
329 # The symbol table including PCD and macro mapping
331 self
._Symb
= copy
.deepcopy(SymbolTable
)
332 self
._Symb
.update(self
.LogicalOperators
)
334 self
._Len
= len(self
._Expr
)
336 self
._WarnExcept
= None
338 # Literal token without any conversion
339 self
._LiteralToken
= ''
341 # Public entry for this class
342 # @param RealValue: False: only evaluate if the expression is true or false, used for conditional expression
343 # True : return the evaluated str(value), used for PCD value
345 # @return: True or False if RealValue is False
346 # Evaluated value of string format if RealValue is True
348 def __call__(self
, RealValue
=False, Depth
=0):
354 self
._Expr
= self
._Expr
.strip()
355 if RealValue
and Depth
== 0:
356 self
._Token
= self
._Expr
357 if self
.__IsNumberToken
():
361 Token
= self
._GetToken
()
362 except BadExpression
:
364 if type(Token
) == type('') and Token
.startswith('{') and Token
.endswith('}') and self
._Idx
>= self
._Len
:
370 Val
= self
._ConExpr
()
372 if type(Val
) == type(''):
378 elif not Val
.startswith('L"') and not Val
.startswith('{') and not Val
.startswith("L'"):
380 RealVal
= '"' + RealVal
+ '"'
382 # The expression has been parsed, but the end of expression is not reached
383 # It means the rest does not comply EBNF of <Expression>
384 if self
._Idx
!= self
._Len
:
385 raise BadExpression(ERR_SNYTAX
% self
._Expr
[self
._Idx
:])
388 RetVal
= str(RealVal
)
395 self
._WarnExcept
.result
= RetVal
396 raise self
._WarnExcept
400 # Template function to parse binary operators which have same precedence
401 # Expr [Operator Expr]*
402 def _ExprFuncTemplate(self
, EvalFunc
, OpLst
):
404 while self
._IsOperator
(OpLst
):
408 if self
._IsOperator
(':'):
416 Val
= self
.Eval(Op
, Val
, EvalFunc())
417 except WrnExpression
, Warn
:
418 self
._WarnExcept
= Warn
423 return self
._ExprFuncTemplate
(self
._OrExpr
, ['?', ':'])
427 return self
._ExprFuncTemplate
(self
._AndExpr
, ["OR", "or", "||"])
431 return self
._ExprFuncTemplate
(self
._BitOr
, ["AND", "and", "&&"])
435 return self
._ExprFuncTemplate
(self
._BitXor
, ["|"])
439 return self
._ExprFuncTemplate
(self
._BitAnd
, ["XOR", "xor", "^"])
443 return self
._ExprFuncTemplate
(self
._EqExpr
, ["&"])
447 Val
= self
._RelExpr
()
448 while self
._IsOperator
(["==", "!=", "EQ", "NE", "IN", "in", "!", "NOT", "not"]):
450 if Op
in ["!", "NOT", "not"]:
451 if not self
._IsOperator
(["IN", "in"]):
452 raise BadExpression(ERR_REL_NOT_IN
)
453 Op
+= ' ' + self
._Token
455 Val
= self
.Eval(Op
, Val
, self
._RelExpr
())
456 except WrnExpression
, Warn
:
457 self
._WarnExcept
= Warn
463 return self
._ExprFuncTemplate
(self
._ShiftExpr
, ["<=", ">=", "<", ">", "LE", "GE", "LT", "GT"])
465 def _ShiftExpr(self
):
466 return self
._ExprFuncTemplate
(self
._AddExpr
, ["<<", ">>"])
470 return self
._ExprFuncTemplate
(self
._MulExpr
, ["+", "-"])
474 return self
._ExprFuncTemplate
(self
._UnaryExpr
, ["*", "/", "%"])
477 def _UnaryExpr(self
):
478 if self
._IsOperator
(["!", "NOT", "not"]):
479 Val
= self
._UnaryExpr
()
481 return self
.Eval('not', Val
)
482 except WrnExpression
, Warn
:
483 self
._WarnExcept
= Warn
485 if self
._IsOperator
(["~"]):
486 Val
= self
._UnaryExpr
()
488 return self
.Eval('~', Val
)
489 except WrnExpression
, Warn
:
490 self
._WarnExcept
= Warn
492 return self
._IdenExpr
()
494 # Parse identifier or encapsulated expression
496 Tk
= self
._GetToken
()
498 Val
= self
._ConExpr
()
500 # _GetToken may also raise BadExpression
501 if self
._GetToken
() != ')':
502 raise BadExpression(ERR_MATCH
)
503 except BadExpression
:
504 raise BadExpression(ERR_MATCH
)
508 # Skip whitespace or tab
510 for Char
in self
._Expr
[self
._Idx
:]:
511 if Char
not in ' \t':
515 # Try to convert string to number
516 def __IsNumberToken(self
):
518 if self
._Token
.lower()[0:2] == '0x' and len(self
._Token
) > 2:
520 if self
._Token
.startswith('"') or self
._Token
.startswith('L"'):
522 for Index
in range(len(self
._Token
)):
523 if self
._Token
[Index
] in ['"']:
524 if self
._Token
[Index
- 1] == '\\':
527 if Flag
== 2 and self
._Token
.endswith('"'):
529 if self
._Token
.startswith("'") or self
._Token
.startswith("L'"):
531 for Index
in range(len(self
._Token
)):
532 if self
._Token
[Index
] in ["'"]:
533 if self
._Token
[Index
- 1] == '\\':
536 if Flag
== 2 and self
._Token
.endswith("'"):
539 self
._Token
= int(self
._Token
, Radix
)
547 def __GetArray(self
):
550 self
.__GetNList
(True)
551 Token
+= self
._LiteralToken
552 if self
._Idx
>= self
._Len
or self
._Expr
[self
._Idx
] != '}':
553 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
556 # All whitespace and tabs in array are already stripped.
557 IsArray
= IsGuid
= False
558 if len(Token
.split(',')) == 11 and len(Token
.split(',{')) == 2 \
559 and len(Token
.split('},')) == 1:
560 HexLen
= [11,6,6,5,4,4,4,4,4,4,6]
561 HexList
= Token
.split(',')
562 if HexList
[3].startswith('{') and \
563 not [Index
for Index
, Hex
in enumerate(HexList
) if len(Hex
) > HexLen
[Index
]]:
565 if Token
.lstrip('{').rstrip('}').find('{') == -1:
566 if not [Hex
for Hex
in Token
.lstrip('{').rstrip('}').split(',') if len(Hex
) > 4]:
568 if not IsArray
and not IsGuid
:
569 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
571 self
._Token
= self
._LiteralToken
= Token
574 # Parse string, the format must be: "..."
575 def __GetString(self
):
581 # Replace escape \\\", \"
582 if self
._Expr
[Idx
] == '"':
583 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace('\\\"', '\\\'')
588 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
589 if not self
._Token
.endswith('"'):
590 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
591 #Replace escape \\\', \'
592 elif self
._Expr
[Idx
] == "'":
593 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace("\\\'", "\\\"")
598 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
599 if not self
._Token
.endswith("'"):
600 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
601 self
._Token
= self
._Token
[1:-1]
604 # Get token that is comprised by alphanumeric, underscore or dot(used by PCD)
605 # @param IsAlphaOp: Indicate if parsing general token or script operator(EQ, NE...)
606 def __GetIdToken(self
, IsAlphaOp
= False):
608 for Ch
in self
._Expr
[self
._Idx
:]:
609 if not self
.__IsIdChar
(Ch
) or ('?' in self
._Expr
and Ch
== ':'):
614 self
._Token
= self
._LiteralToken
= IdToken
616 self
.__ResolveToken
()
619 # Try to resolve token
620 def __ResolveToken(self
):
622 raise BadExpression(ERR_EMPTY_TOKEN
)
625 if self
.PcdPattern
.match(self
._Token
):
626 if self
._Token
not in self
._Symb
:
627 Ex
= BadExpression(ERR_PCD_RESOLVE
% self
._Token
)
630 self
._Token
= ValueExpression(self
._Symb
[self
._Token
], self
._Symb
)(True, self
._Depth
+1)
631 if type(self
._Token
) != type(''):
632 self
._LiteralToken
= hex(self
._Token
)
635 if self
._Token
.startswith('"'):
636 self
._Token
= self
._Token
[1:-1]
637 elif self
._Token
in ["FALSE", "false", "False"]:
639 elif self
._Token
in ["TRUE", "true", "True"]:
642 self
.__IsNumberToken
()
644 def __GetNList(self
, InArray
=False):
645 self
._GetSingleToken
()
646 if not self
.__IsHexLiteral
():
648 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
652 Expr
= self
._Expr
[self
._Idx
:]
653 if not Expr
.startswith(','):
656 NList
= self
._LiteralToken
657 while Expr
.startswith(','):
661 self
._GetSingleToken
()
662 if not self
.__IsHexLiteral
():
663 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
664 NList
+= self
._LiteralToken
666 Expr
= self
._Expr
[self
._Idx
:]
667 self
._Token
= self
._LiteralToken
= NList
670 def __IsHexLiteral(self
):
671 if self
._LiteralToken
.startswith('{') and \
672 self
._LiteralToken
.endswith('}'):
675 if self
.HexPattern
.match(self
._LiteralToken
):
676 Token
= self
._LiteralToken
[2:]
678 self
._LiteralToken
= '0x0'
680 self
._LiteralToken
= '0x' + Token
685 return self
.__GetNList
()
689 return Ch
in '._:' or Ch
.isalnum()
692 def _GetSingleToken(self
):
694 Expr
= self
._Expr
[self
._Idx
:]
695 if Expr
.startswith('L"'):
698 UStr
= self
.__GetString
()
699 self
._Token
= 'L"' + UStr
+ '"'
701 elif Expr
.startswith("L'"):
704 UStr
= self
.__GetString
()
705 self
._Token
= "L'" + UStr
+ "'"
707 elif Expr
.startswith("'"):
708 UStr
= self
.__GetString
()
709 self
._Token
= "'" + UStr
+ "'"
711 elif Expr
.startswith('UINT'):
712 Re
= re
.compile('(?:UINT8|UINT16|UINT32|UINT64)\((.+)\)')
714 RetValue
= Re
.search(Expr
).group(1)
716 raise BadExpression('Invalid Expression %s' % Expr
)
721 Prefix
= self
._Expr
[Idx
:self
._Idx
- 1]
724 TmpValue
= self
._Expr
[Idx
:self
._Idx
- 1]
725 TmpValue
= ValueExpression(TmpValue
)(True)
726 TmpValue
= '0x%x' % int(TmpValue
) if type(TmpValue
) != type('') else TmpValue
728 self
._Token
, Size
= ParseFieldValue(Prefix
+ '(' + TmpValue
+ ')')
734 Match
= self
.RegGuidPattern
.match(Expr
)
735 if Match
and not Expr
[Match
.end():Match
.end()+1].isalnum() \
736 and Expr
[Match
.end():Match
.end()+1] != '_':
737 self
._Idx
+= Match
.end()
738 self
._Token
= ValueExpression(GuidStringToGuidStructureString(Expr
[0:Match
.end()]))(True, self
._Depth
+1)
740 elif self
.__IsIdChar
(Ch
):
741 return self
.__GetIdToken
()
743 return self
.__GetString
()
745 return self
.__GetArray
()
746 elif Ch
== '(' or Ch
== ')':
751 raise BadExpression(ERR_VALID_TOKEN
% Expr
)
754 def _GetOperator(self
):
756 LegalOpLst
= ['&&', '||', '!=', '==', '>=', '<='] + self
.NonLetterOpLst
+ ['?',':']
759 Expr
= self
._Expr
[self
._Idx
:]
761 # Reach end of expression
765 # Script operator: LT, GT, LE, GE, EQ, NE, and, or, xor, not
766 if Expr
[0].isalpha():
767 return self
.__GetIdToken
(True)
769 # Start to get regular operator: +, -, <, > ...
770 if Expr
[0] not in self
.NonLetterOpLst
:
775 if Ch
in self
.NonLetterOpLst
:
776 if '!' == Ch
and OpToken
:
783 if OpToken
not in LegalOpLst
:
784 raise BadExpression(ERR_OPERATOR_UNSUPPORT
% OpToken
)
785 self
._Token
= OpToken
788 # Check if current token matches the operators given from OpList
789 def _IsOperator(self
, OpList
):
792 if self
._Token
in OpList
:
793 if self
._Token
in self
.LogicalOperators
:
794 self
._Token
= self
.LogicalOperators
[self
._Token
]
799 class ValueExpressionEx(ValueExpression
):
800 def __init__(self
, PcdValue
, PcdType
, SymbolTable
={}):
801 ValueExpression
.__init
__(self
, PcdValue
, SymbolTable
)
802 self
.PcdValue
= PcdValue
803 self
.PcdType
= PcdType
805 def __call__(self
, RealValue
=False, Depth
=0):
806 PcdValue
= self
.PcdValue
808 PcdValue
= ValueExpression
.__call
__(self
, RealValue
, Depth
)
809 if self
.PcdType
== 'VOID*' and (PcdValue
.startswith("'") or PcdValue
.startswith("L'")):
810 PcdValue
, Size
= ParseFieldValue(PcdValue
)
812 for I
in range(Size
):
813 PcdValueList
.append('0x%02X'%(PcdValue
& 0xff))
814 PcdValue
= PcdValue
>> 8
815 PcdValue
= '{' + ','.join(PcdValueList
) + '}'
816 elif self
.PcdType
in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN'] and (PcdValue
.startswith("'") or \
817 PcdValue
.startswith('"') or PcdValue
.startswith("L'") or PcdValue
.startswith('L"') or PcdValue
.startswith('{')):
819 except WrnExpression
, Value
:
820 PcdValue
= Value
.result
821 except BadExpression
, Value
:
822 if self
.PcdType
in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN']:
823 PcdValue
= PcdValue
.strip()
824 if type(PcdValue
) == type('') and PcdValue
.startswith('{') and PcdValue
.endswith('}'):
825 PcdValue
= SplitPcdValueString(PcdValue
[1:-1])
826 if type(PcdValue
) == type([]):
830 for Item
in PcdValue
:
832 if Item
.startswith('UINT8'):
835 elif Item
.startswith('UINT16'):
838 elif Item
.startswith('UINT32'):
841 elif Item
.startswith('UINT64'):
844 elif Item
.startswith('"') or Item
.startswith("'") or Item
.startswith('L'):
850 Item
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
854 tmpValue
= int(Item
, 16) if Item
.upper().startswith('0X') else int(Item
, 0)
856 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
857 except BadExpression
, Value
:
858 raise BadExpression(Value
)
861 ItemValue
, ItemSize
= ParseFieldValue(Item
)
863 ItemValue
= ParseFieldValue(Item
)[0]
865 if type(ItemValue
) == type(''):
866 ItemValue
= int(ItemValue
, 16) if ItemValue
.startswith('0x') else int(ItemValue
)
868 TmpValue
= (ItemValue
<< (Size
* 8)) | TmpValue
869 Size
= Size
+ ItemSize
872 TmpValue
, Size
= ParseFieldValue(PcdValue
)
873 except BadExpression
, Value
:
874 raise BadExpression("Type: %s, Value: %s, %s" % (self
.PcdType
, PcdValue
, Value
))
875 if type(TmpValue
) == type(''):
877 TmpValue
= int(TmpValue
)
879 raise BadExpression(Value
)
881 PcdValue
= '0x%0{}X'.format(Size
) % (TmpValue
)
883 raise BadExpression('Type %s PCD Value is negative' % self
.PcdType
)
884 if self
.PcdType
== 'UINT8' and Size
> 1:
885 raise BadExpression('Type %s PCD Value Size is Larger than 1 byte' % self
.PcdType
)
886 if self
.PcdType
== 'UINT16' and Size
> 2:
887 raise BadExpression('Type %s PCD Value Size is Larger than 2 byte' % self
.PcdType
)
888 if self
.PcdType
== 'UINT32' and Size
> 4:
889 raise BadExpression('Type %s PCD Value Size is Larger than 4 byte' % self
.PcdType
)
890 if self
.PcdType
== 'UINT64' and Size
> 8:
891 raise BadExpression('Type %s PCD Value Size is Larger than 8 byte' % self
.PcdType
)
894 TmpValue
= long(PcdValue
)
896 if TmpValue
.bit_length() == 0:
899 for I
in range((TmpValue
.bit_length() + 7) / 8):
900 TmpList
.append('0x%02x' % ((TmpValue
>> I
* 8) & 0xff))
901 PcdValue
= '{' + ', '.join(TmpList
) + '}'
903 if PcdValue
.strip().startswith('{'):
904 PcdValueList
= SplitPcdValueString(PcdValue
.strip()[1:-1])
907 ReLabel
= re
.compile('LABEL\((\w+)\)')
908 ReOffset
= re
.compile('OFFSET_OF\((\w+)\)')
910 for Index
, Item
in enumerate(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 IsValidCString(Label
):
918 raise BadExpression('%s is not a valid c variable name' % Label
)
919 if Label
not in LabelDict
.keys():
920 LabelDict
[Label
] = str(LabelOffset
)
921 if Item
.startswith('UINT8'):
922 LabelOffset
= LabelOffset
+ 1
923 elif Item
.startswith('UINT16'):
924 LabelOffset
= LabelOffset
+ 2
925 elif Item
.startswith('UINT32'):
926 LabelOffset
= LabelOffset
+ 4
927 elif Item
.startswith('UINT64'):
928 LabelOffset
= LabelOffset
+ 8
931 ItemValue
, ItemSize
= ParseFieldValue(Item
)
932 LabelOffset
= LabelOffset
+ ItemSize
934 LabelOffset
= LabelOffset
+ 1
936 for Index
, Item
in enumerate(PcdValueList
):
940 Item
= ReLabel
.sub('', Item
)
944 OffsetList
= ReOffset
.findall(Item
)
947 for Offset
in OffsetList
:
948 if Offset
in LabelDict
.keys():
949 Re
= re
.compile('OFFSET_OF\(%s\)' % Offset
)
950 Item
= Re
.sub(LabelDict
[Offset
], Item
)
952 raise BadExpression('%s not defined' % Offset
)
953 NewPcdValueList
.append(Item
)
956 for Item
in NewPcdValueList
:
959 TokenSpaceGuidName
= ''
960 if Item
.startswith('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('UINT8'):
984 elif Item
.startswith('UINT16'):
987 elif Item
.startswith('UINT32'):
990 elif Item
.startswith('UINT64'):
996 TmpValue
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
998 TmpValue
= ValueExpressionEx(Item
, self
.PcdType
, self
._Symb
)(True)
999 Item
= '0x%x' % TmpValue
if type(TmpValue
) != type('') else TmpValue
1001 ItemValue
, ItemSize
= ParseFieldValue(Item
)
1002 if not (Item
.startswith('"') or Item
.startswith('L') or Item
.startswith('{')) 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
, Ex
:
1037 except Exception, Ex
: