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).'
43 __ValidString
= re
.compile(r
'[_a-zA-Z][_0-9a-zA-Z]*$')
44 _ReLabel
= re
.compile('LABEL\((\w+)\)')
45 _ReOffset
= re
.compile('OFFSET_OF\((\w+)\)')
46 PcdPattern
= re
.compile(r
'[_a-zA-Z][0-9A-Za-z_]*\.[_a-zA-Z][0-9A-Za-z_]*$')
49 # Split string to list according double quote
50 # For example: abc"de\"f"ghi"jkl"mn will be: ['abc', '"de\"f"', 'ghi', '"jkl"', 'mn']
52 def SplitString(String
):
53 # There might be escaped quote: "abc\"def\\\"ghi", 'abc\'def\\\'ghi'
58 for i
, ch
in enumerate(String
):
59 if ch
== '"' and not InSingleQuote
:
60 if String
[i
- 1] != '\\':
61 InDoubleQuote
= not InDoubleQuote
70 elif ch
== "'" and not InDoubleQuote
:
71 if String
[i
- 1] != '\\':
72 InSingleQuote
= not InSingleQuote
82 if InSingleQuote
or InDoubleQuote
:
83 raise BadExpression(ERR_STRING_TOKEN
% Item
)
88 def SplitPcdValueString(String
):
89 # There might be escaped comma in GUID() or DEVICE_PATH() or " "
90 # or ' ' or L' ' or L" "
96 for i
, ch
in enumerate(String
):
103 raise BadExpression(ERR_STRING_TOKEN
% Item
)
104 elif ch
== '"' and not InSingleQuote
:
105 if String
[i
-1] != '\\':
106 InDoubleQuote
= not InDoubleQuote
107 elif ch
== "'" and not InDoubleQuote
:
108 if String
[i
-1] != '\\':
109 InSingleQuote
= not InSingleQuote
111 if InParenthesis
or InSingleQuote
or InDoubleQuote
:
119 if InSingleQuote
or InDoubleQuote
or InParenthesis
:
120 raise BadExpression(ERR_STRING_TOKEN
% Item
)
125 def IsValidCName(Str
):
126 return True if __ValidString
.match(Str
) else False
128 def BuildOptionValue(PcdValue
, GuidDict
):
129 if PcdValue
.startswith('H'):
130 InputValue
= PcdValue
[1:]
131 elif PcdValue
.startswith("L'") or PcdValue
.startswith("'"):
132 InputValue
= PcdValue
133 elif PcdValue
.startswith('L'):
134 InputValue
= 'L"' + PcdValue
[1:] + '"'
136 InputValue
= PcdValue
137 if IsFieldValueAnArray(InputValue
):
139 PcdValue
= ValueExpressionEx(InputValue
, 'VOID*', GuidDict
)(True)
146 def ReplaceExprMacro(String
, Macros
, ExceptionList
= None):
147 StrList
= SplitString(String
)
148 for i
, String
in enumerate(StrList
):
150 if String
.startswith('"'):
152 MacroStartPos
= String
.find('$(')
153 if MacroStartPos
< 0:
154 for Pcd
in gPlatformPcds
.keys():
156 if Pcd
not in gConditionalPcds
:
157 gConditionalPcds
.append(Pcd
)
160 while MacroStartPos
>= 0:
161 RetStr
= String
[0:MacroStartPos
]
162 MacroEndPos
= String
.find(')', MacroStartPos
)
164 raise BadExpression(ERR_MACRO_TOKEN
% String
[MacroStartPos
:])
165 Macro
= String
[MacroStartPos
+2:MacroEndPos
]
166 if Macro
not in Macros
:
167 # From C reference manual:
168 # If an undefined macro name appears in the constant-expression of
169 # !if or !elif, it is replaced by the integer constant 0.
172 Tklst
= RetStr
.split()
173 if Tklst
and Tklst
[-1] in ['IN', 'in'] and ExceptionList
and Macro
not in ExceptionList
:
174 raise BadExpression(ERR_IN_OPERAND
)
175 # Make sure the macro in exception list is encapsulated by double quote
176 # For example: DEFINE ARCH = IA32 X64
177 # $(ARCH) is replaced with "IA32 X64"
178 if ExceptionList
and Macro
in ExceptionList
:
179 RetStr
+= '"' + Macros
[Macro
] + '"'
180 elif Macros
[Macro
].strip():
181 RetStr
+= Macros
[Macro
]
185 RetStr
+= Macros
[Macro
]
186 RetStr
+= String
[MacroEndPos
+1:]
188 MacroStartPos
= String
.find('$(')
190 return ''.join(StrList
)
192 # transfer int to string for in/not in expression
196 StrList
.append(chr(Value
& 0xff))
198 Value
= '"' + ''.join(StrList
) + '"'
201 SupportedInMacroList
= ['TARGET', 'TOOL_CHAIN_TAG', 'ARCH', 'FAMILY']
203 class ValueExpression(object):
204 # Logical operator mapping
206 '&&' : 'and', '||' : 'or',
207 '!' : 'not', 'AND': 'and',
208 'OR' : 'or' , 'NOT': 'not',
209 'XOR': '^' , 'xor': '^',
210 'EQ' : '==' , 'NE' : '!=',
211 'GT' : '>' , 'LT' : '<',
212 'GE' : '>=' , 'LE' : '<=',
216 NonLetterOpLst
= ['+', '-', '*', '/', '%', '&', '|', '^', '~', '<<', '>>', '!', '=', '>', '<', '?', ':']
219 SymbolPattern
= re
.compile("("
220 "\$\([A-Z][A-Z0-9_]*\)|\$\(\w+\.\w+\)|\w+\.\w+|"
222 "(?<=\W)AND(?=\W)|(?<=\W)OR(?=\W)|(?<=\W)NOT(?=\W)|(?<=\W)XOR(?=\W)|"
223 "(?<=\W)EQ(?=\W)|(?<=\W)NE(?=\W)|(?<=\W)GT(?=\W)|(?<=\W)LT(?=\W)|(?<=\W)GE(?=\W)|(?<=\W)LE(?=\W)"
227 def Eval(Operator
, Oprand1
, Oprand2
= None):
230 if Operator
not in ["==", "!=", ">=", "<=", ">", "<", "in", "not in"] and \
231 (type(Oprand1
) == type('') or type(Oprand2
) == type('')):
232 raise BadExpression(ERR_STRING_EXPR
% Operator
)
233 if Operator
in ['in', 'not in']:
234 if type(Oprand1
) != type(''):
235 Oprand1
= IntToStr(Oprand1
)
236 if type(Oprand2
) != type(''):
237 Oprand2
= IntToStr(Oprand2
)
246 if Operator
in ["!", "NOT", "not"]:
247 if type(Oprand1
) == type(''):
248 raise BadExpression(ERR_STRING_EXPR
% Operator
)
249 EvalStr
= 'not Oprand1'
250 elif Operator
in ["~"]:
251 if type(Oprand1
) == type(''):
252 raise BadExpression(ERR_STRING_EXPR
% Operator
)
253 EvalStr
= '~ Oprand1'
255 if Operator
in ["+", "-"] and (type(True) in [type(Oprand1
), type(Oprand2
)]):
256 # Boolean in '+'/'-' will be evaluated but raise warning
257 WrnExp
= WrnExpression(WRN_BOOL_EXPR
)
258 elif type('') in [type(Oprand1
), type(Oprand2
)] and type(Oprand1
)!= type(Oprand2
):
259 # == between string and number/boolean will always return False, != return True
261 WrnExp
= WrnExpression(WRN_EQCMP_STR_OTHERS
)
262 WrnExp
.result
= False
264 elif Operator
== "!=":
265 WrnExp
= WrnExpression(WRN_NECMP_STR_OTHERS
)
269 raise BadExpression(ERR_RELCMP_STR_OTHERS
% Operator
)
270 elif TypeDict
[type(Oprand1
)] != TypeDict
[type(Oprand2
)]:
271 if Operator
in ["==", "!=", ">=", "<=", ">", "<"] and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
272 # comparison between number and boolean is allowed
274 elif Operator
in ['&', '|', '^', "and", "or"] and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
275 # bitwise and logical operation between number and boolean is allowed
278 raise BadExpression(ERR_EXPR_TYPE
)
279 if type(Oprand1
) == type('') and type(Oprand2
) == type(''):
280 if (Oprand1
.startswith('L"') and not Oprand2
.startswith('L"')) or \
281 (not Oprand1
.startswith('L"') and Oprand2
.startswith('L"')):
282 raise BadExpression(ERR_STRING_CMP
% (Oprand1
, Operator
, Oprand2
))
283 if 'in' in Operator
and type(Oprand2
) == type(''):
284 Oprand2
= Oprand2
.split()
285 EvalStr
= 'Oprand1 ' + Operator
+ ' Oprand2'
287 # Local symbols used by built in eval function
293 Val
= eval(EvalStr
, {}, Dict
)
294 except Exception, Excpt
:
295 raise BadExpression(str(Excpt
))
297 if Operator
in ['and', 'or']:
308 def __init__(self
, Expression
, SymbolTable
={}):
309 self
._NoProcess
= False
310 if type(Expression
) != type(''):
311 self
._Expr
= Expression
312 self
._NoProcess
= True
315 self
._Expr
= ReplaceExprMacro(Expression
.strip(),
317 SupportedInMacroList
)
319 if not self
._Expr
.strip():
320 raise BadExpression(ERR_EMPTY_EXPR
)
323 # The symbol table including PCD and macro mapping
325 self
._Symb
= copy
.deepcopy(SymbolTable
)
326 self
._Symb
.update(self
.LogicalOperators
)
328 self
._Len
= len(self
._Expr
)
330 self
._WarnExcept
= None
332 # Literal token without any conversion
333 self
._LiteralToken
= ''
335 # Public entry for this class
336 # @param RealValue: False: only evaluate if the expression is true or false, used for conditional expression
337 # True : return the evaluated str(value), used for PCD value
339 # @return: True or False if RealValue is False
340 # Evaluated value of string format if RealValue is True
342 def __call__(self
, RealValue
=False, Depth
=0):
348 self
._Expr
= self
._Expr
.strip()
349 if RealValue
and Depth
== 0:
350 self
._Token
= self
._Expr
351 if self
.__IsNumberToken
():
355 Token
= self
._GetToken
()
356 except BadExpression
:
358 if type(Token
) == type('') and Token
.startswith('{') and Token
.endswith('}') and self
._Idx
>= self
._Len
:
364 Val
= self
._ConExpr
()
366 if type(Val
) == type(''):
372 elif not Val
.startswith('L"') and not Val
.startswith('{') and not Val
.startswith("L'"):
374 RealVal
= '"' + RealVal
+ '"'
376 # The expression has been parsed, but the end of expression is not reached
377 # It means the rest does not comply EBNF of <Expression>
378 if self
._Idx
!= self
._Len
:
379 raise BadExpression(ERR_SNYTAX
% self
._Expr
[self
._Idx
:])
382 RetVal
= str(RealVal
)
389 self
._WarnExcept
.result
= RetVal
390 raise self
._WarnExcept
394 # Template function to parse binary operators which have same precedence
395 # Expr [Operator Expr]*
396 def _ExprFuncTemplate(self
, EvalFunc
, OpLst
):
398 while self
._IsOperator
(OpLst
):
402 if self
._IsOperator
(':'):
410 Val
= self
.Eval(Op
, Val
, EvalFunc())
411 except WrnExpression
, Warn
:
412 self
._WarnExcept
= Warn
417 return self
._ExprFuncTemplate
(self
._OrExpr
, ['?', ':'])
421 return self
._ExprFuncTemplate
(self
._AndExpr
, ["OR", "or", "||"])
425 return self
._ExprFuncTemplate
(self
._BitOr
, ["AND", "and", "&&"])
429 return self
._ExprFuncTemplate
(self
._BitXor
, ["|"])
433 return self
._ExprFuncTemplate
(self
._BitAnd
, ["XOR", "xor", "^"])
437 return self
._ExprFuncTemplate
(self
._EqExpr
, ["&"])
441 Val
= self
._RelExpr
()
442 while self
._IsOperator
(["==", "!=", "EQ", "NE", "IN", "in", "!", "NOT", "not"]):
444 if Op
in ["!", "NOT", "not"]:
445 if not self
._IsOperator
(["IN", "in"]):
446 raise BadExpression(ERR_REL_NOT_IN
)
447 Op
+= ' ' + self
._Token
449 Val
= self
.Eval(Op
, Val
, self
._RelExpr
())
450 except WrnExpression
, Warn
:
451 self
._WarnExcept
= Warn
457 return self
._ExprFuncTemplate
(self
._ShiftExpr
, ["<=", ">=", "<", ">", "LE", "GE", "LT", "GT"])
459 def _ShiftExpr(self
):
460 return self
._ExprFuncTemplate
(self
._AddExpr
, ["<<", ">>"])
464 return self
._ExprFuncTemplate
(self
._MulExpr
, ["+", "-"])
468 return self
._ExprFuncTemplate
(self
._UnaryExpr
, ["*", "/", "%"])
471 def _UnaryExpr(self
):
472 if self
._IsOperator
(["!", "NOT", "not"]):
473 Val
= self
._UnaryExpr
()
475 return self
.Eval('not', Val
)
476 except WrnExpression
, Warn
:
477 self
._WarnExcept
= Warn
479 if self
._IsOperator
(["~"]):
480 Val
= self
._UnaryExpr
()
482 return self
.Eval('~', Val
)
483 except WrnExpression
, Warn
:
484 self
._WarnExcept
= Warn
486 return self
._IdenExpr
()
488 # Parse identifier or encapsulated expression
490 Tk
= self
._GetToken
()
492 Val
= self
._ConExpr
()
494 # _GetToken may also raise BadExpression
495 if self
._GetToken
() != ')':
496 raise BadExpression(ERR_MATCH
)
497 except BadExpression
:
498 raise BadExpression(ERR_MATCH
)
502 # Skip whitespace or tab
504 for Char
in self
._Expr
[self
._Idx
:]:
505 if Char
not in ' \t':
509 # Try to convert string to number
510 def __IsNumberToken(self
):
512 if self
._Token
.lower()[0:2] == '0x' and len(self
._Token
) > 2:
514 if self
._Token
.startswith('"') or self
._Token
.startswith('L"'):
516 for Index
in range(len(self
._Token
)):
517 if self
._Token
[Index
] in ['"']:
518 if self
._Token
[Index
- 1] == '\\':
521 if Flag
== 2 and self
._Token
.endswith('"'):
523 if self
._Token
.startswith("'") or self
._Token
.startswith("L'"):
525 for Index
in range(len(self
._Token
)):
526 if self
._Token
[Index
] in ["'"]:
527 if self
._Token
[Index
- 1] == '\\':
530 if Flag
== 2 and self
._Token
.endswith("'"):
533 self
._Token
= int(self
._Token
, Radix
)
541 def __GetArray(self
):
544 self
.__GetNList
(True)
545 Token
+= self
._LiteralToken
546 if self
._Idx
>= self
._Len
or self
._Expr
[self
._Idx
] != '}':
547 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
550 # All whitespace and tabs in array are already stripped.
551 IsArray
= IsGuid
= False
552 if len(Token
.split(',')) == 11 and len(Token
.split(',{')) == 2 \
553 and len(Token
.split('},')) == 1:
554 HexLen
= [11,6,6,5,4,4,4,4,4,4,6]
555 HexList
= Token
.split(',')
556 if HexList
[3].startswith('{') and \
557 not [Index
for Index
, Hex
in enumerate(HexList
) if len(Hex
) > HexLen
[Index
]]:
559 if Token
.lstrip('{').rstrip('}').find('{') == -1:
560 if not [Hex
for Hex
in Token
.lstrip('{').rstrip('}').split(',') if len(Hex
) > 4]:
562 if not IsArray
and not IsGuid
:
563 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
565 self
._Token
= self
._LiteralToken
= Token
568 # Parse string, the format must be: "..."
569 def __GetString(self
):
575 # Replace escape \\\", \"
576 if self
._Expr
[Idx
] == '"':
577 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace('\\\"', '\\\'')
582 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
583 if not self
._Token
.endswith('"'):
584 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
585 #Replace escape \\\', \'
586 elif self
._Expr
[Idx
] == "'":
587 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace("\\\'", "\\\"")
592 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
593 if not self
._Token
.endswith("'"):
594 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
595 self
._Token
= self
._Token
[1:-1]
598 # Get token that is comprised by alphanumeric, underscore or dot(used by PCD)
599 # @param IsAlphaOp: Indicate if parsing general token or script operator(EQ, NE...)
600 def __GetIdToken(self
, IsAlphaOp
= False):
602 for Ch
in self
._Expr
[self
._Idx
:]:
603 if not self
.__IsIdChar
(Ch
) or ('?' in self
._Expr
and Ch
== ':'):
608 self
._Token
= self
._LiteralToken
= IdToken
610 self
.__ResolveToken
()
613 # Try to resolve token
614 def __ResolveToken(self
):
616 raise BadExpression(ERR_EMPTY_TOKEN
)
619 if PcdPattern
.match(self
._Token
):
620 if self
._Token
not in self
._Symb
:
621 Ex
= BadExpression(ERR_PCD_RESOLVE
% self
._Token
)
624 self
._Token
= ValueExpression(self
._Symb
[self
._Token
], self
._Symb
)(True, self
._Depth
+1)
625 if type(self
._Token
) != type(''):
626 self
._LiteralToken
= hex(self
._Token
)
629 if self
._Token
.startswith('"'):
630 self
._Token
= self
._Token
[1:-1]
631 elif self
._Token
in ["FALSE", "false", "False"]:
633 elif self
._Token
in ["TRUE", "true", "True"]:
636 self
.__IsNumberToken
()
638 def __GetNList(self
, InArray
=False):
639 self
._GetSingleToken
()
640 if not self
.__IsHexLiteral
():
642 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
646 Expr
= self
._Expr
[self
._Idx
:]
647 if not Expr
.startswith(','):
650 NList
= self
._LiteralToken
651 while Expr
.startswith(','):
655 self
._GetSingleToken
()
656 if not self
.__IsHexLiteral
():
657 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
658 NList
+= self
._LiteralToken
660 Expr
= self
._Expr
[self
._Idx
:]
661 self
._Token
= self
._LiteralToken
= NList
664 def __IsHexLiteral(self
):
665 if self
._LiteralToken
.startswith('{') and \
666 self
._LiteralToken
.endswith('}'):
669 if gHexPattern
.match(self
._LiteralToken
):
670 Token
= self
._LiteralToken
[2:]
672 self
._LiteralToken
= '0x0'
674 self
._LiteralToken
= '0x' + Token
679 return self
.__GetNList
()
683 return Ch
in '._:' or Ch
.isalnum()
686 def _GetSingleToken(self
):
688 Expr
= self
._Expr
[self
._Idx
:]
689 if Expr
.startswith('L"'):
692 UStr
= self
.__GetString
()
693 self
._Token
= 'L"' + UStr
+ '"'
695 elif Expr
.startswith("L'"):
698 UStr
= self
.__GetString
()
699 self
._Token
= "L'" + UStr
+ "'"
701 elif Expr
.startswith("'"):
702 UStr
= self
.__GetString
()
703 self
._Token
= "'" + UStr
+ "'"
705 elif Expr
.startswith('UINT'):
706 Re
= re
.compile('(?:UINT8|UINT16|UINT32|UINT64)\((.+)\)')
708 RetValue
= Re
.search(Expr
).group(1)
710 raise BadExpression('Invalid Expression %s' % Expr
)
715 Prefix
= self
._Expr
[Idx
:self
._Idx
- 1]
718 TmpValue
= self
._Expr
[Idx
:self
._Idx
- 1]
719 TmpValue
= ValueExpression(TmpValue
)(True)
720 TmpValue
= '0x%x' % int(TmpValue
) if type(TmpValue
) != type('') else TmpValue
722 self
._Token
, Size
= ParseFieldValue(Prefix
+ '(' + TmpValue
+ ')')
728 Match
= gGuidPattern
.match(Expr
)
729 if Match
and not Expr
[Match
.end():Match
.end()+1].isalnum() \
730 and Expr
[Match
.end():Match
.end()+1] != '_':
731 self
._Idx
+= Match
.end()
732 self
._Token
= ValueExpression(GuidStringToGuidStructureString(Expr
[0:Match
.end()]))(True, self
._Depth
+1)
734 elif self
.__IsIdChar
(Ch
):
735 return self
.__GetIdToken
()
737 return self
.__GetString
()
739 return self
.__GetArray
()
740 elif Ch
== '(' or Ch
== ')':
745 raise BadExpression(ERR_VALID_TOKEN
% Expr
)
748 def _GetOperator(self
):
750 LegalOpLst
= ['&&', '||', '!=', '==', '>=', '<='] + self
.NonLetterOpLst
+ ['?',':']
753 Expr
= self
._Expr
[self
._Idx
:]
755 # Reach end of expression
759 # Script operator: LT, GT, LE, GE, EQ, NE, and, or, xor, not
760 if Expr
[0].isalpha():
761 return self
.__GetIdToken
(True)
763 # Start to get regular operator: +, -, <, > ...
764 if Expr
[0] not in self
.NonLetterOpLst
:
769 if Ch
in self
.NonLetterOpLst
:
770 if '!' == Ch
and OpToken
:
777 if OpToken
not in LegalOpLst
:
778 raise BadExpression(ERR_OPERATOR_UNSUPPORT
% OpToken
)
779 self
._Token
= OpToken
782 # Check if current token matches the operators given from OpList
783 def _IsOperator(self
, OpList
):
786 if self
._Token
in OpList
:
787 if self
._Token
in self
.LogicalOperators
:
788 self
._Token
= self
.LogicalOperators
[self
._Token
]
793 class ValueExpressionEx(ValueExpression
):
794 def __init__(self
, PcdValue
, PcdType
, SymbolTable
={}):
795 ValueExpression
.__init
__(self
, PcdValue
, SymbolTable
)
796 self
.PcdValue
= PcdValue
797 self
.PcdType
= PcdType
799 def __call__(self
, RealValue
=False, Depth
=0):
800 PcdValue
= self
.PcdValue
802 PcdValue
= ValueExpression
.__call
__(self
, RealValue
, Depth
)
803 if self
.PcdType
== 'VOID*' and (PcdValue
.startswith("'") or PcdValue
.startswith("L'")):
804 PcdValue
, Size
= ParseFieldValue(PcdValue
)
806 for I
in range(Size
):
807 PcdValueList
.append('0x%02X'%(PcdValue
& 0xff))
808 PcdValue
= PcdValue
>> 8
809 PcdValue
= '{' + ','.join(PcdValueList
) + '}'
810 elif self
.PcdType
in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN'] and (PcdValue
.startswith("'") or \
811 PcdValue
.startswith('"') or PcdValue
.startswith("L'") or PcdValue
.startswith('L"') or PcdValue
.startswith('{')):
813 except WrnExpression
, Value
:
814 PcdValue
= Value
.result
815 except BadExpression
, Value
:
816 if self
.PcdType
in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN']:
817 PcdValue
= PcdValue
.strip()
818 if type(PcdValue
) == type('') and PcdValue
.startswith('{') and PcdValue
.endswith('}'):
819 PcdValue
= SplitPcdValueString(PcdValue
[1:-1])
820 if type(PcdValue
) == type([]):
824 for Item
in PcdValue
:
826 if Item
.startswith('UINT8'):
829 elif Item
.startswith('UINT16'):
832 elif Item
.startswith('UINT32'):
835 elif Item
.startswith('UINT64'):
838 elif Item
[0] in ['"',"'",'L']:
844 Item
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
848 tmpValue
= int(Item
, 0)
850 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
851 except BadExpression
, Value
:
852 raise BadExpression(Value
)
855 ItemValue
, ItemSize
= ParseFieldValue(Item
)
857 ItemValue
= ParseFieldValue(Item
)[0]
859 if type(ItemValue
) == type(''):
860 ItemValue
= int(ItemValue
, 0)
862 TmpValue
= (ItemValue
<< (Size
* 8)) | TmpValue
863 Size
= Size
+ ItemSize
866 TmpValue
, Size
= ParseFieldValue(PcdValue
)
867 except BadExpression
, Value
:
868 raise BadExpression("Type: %s, Value: %s, %s" % (self
.PcdType
, PcdValue
, Value
))
869 if type(TmpValue
) == type(''):
871 TmpValue
= int(TmpValue
)
873 raise BadExpression(Value
)
875 PcdValue
= '0x%0{}X'.format(Size
) % (TmpValue
)
877 raise BadExpression('Type %s PCD Value is negative' % self
.PcdType
)
878 if self
.PcdType
== 'UINT8' and Size
> 1:
879 raise BadExpression('Type %s PCD Value Size is Larger than 1 byte' % self
.PcdType
)
880 if self
.PcdType
== 'UINT16' and Size
> 2:
881 raise BadExpression('Type %s PCD Value Size is Larger than 2 byte' % self
.PcdType
)
882 if self
.PcdType
== 'UINT32' and Size
> 4:
883 raise BadExpression('Type %s PCD Value Size is Larger than 4 byte' % self
.PcdType
)
884 if self
.PcdType
== 'UINT64' and Size
> 8:
885 raise BadExpression('Type %s PCD Value Size is Larger than 8 byte' % self
.PcdType
)
888 TmpValue
= long(PcdValue
)
890 if TmpValue
.bit_length() == 0:
893 for I
in range((TmpValue
.bit_length() + 7) / 8):
894 TmpList
.append('0x%02x' % ((TmpValue
>> I
* 8) & 0xff))
895 PcdValue
= '{' + ', '.join(TmpList
) + '}'
897 if PcdValue
.strip().startswith('{'):
898 PcdValueList
= SplitPcdValueString(PcdValue
.strip()[1:-1])
902 for Item
in PcdValueList
:
903 # compute byte offset of every LABEL
904 LabelList
= _ReLabel
.findall(Item
)
905 Item
= _ReLabel
.sub('', Item
)
908 for Label
in LabelList
:
909 if not IsValidCName(Label
):
910 raise BadExpression('%s is not a valid c variable name' % Label
)
911 if Label
not in LabelDict
.keys():
912 LabelDict
[Label
] = str(LabelOffset
)
913 if Item
.startswith('UINT8'):
914 LabelOffset
= LabelOffset
+ 1
915 elif Item
.startswith('UINT16'):
916 LabelOffset
= LabelOffset
+ 2
917 elif Item
.startswith('UINT32'):
918 LabelOffset
= LabelOffset
+ 4
919 elif Item
.startswith('UINT64'):
920 LabelOffset
= LabelOffset
+ 8
923 ItemValue
, ItemSize
= ParseFieldValue(Item
)
924 LabelOffset
= LabelOffset
+ ItemSize
926 LabelOffset
= LabelOffset
+ 1
928 for Item
in PcdValueList
:
932 Item
= _ReLabel
.sub('', Item
)
936 OffsetList
= _ReOffset
.findall(Item
)
939 # replace each offset, except errors
940 for Offset
in OffsetList
:
942 Item
= Item
.replace('OFFSET_OF({})'.format(Offset
),LabelDict
[Offset
])
944 raise BadExpression('%s not defined' % Offset
)
946 NewPcdValueList
.append(Item
)
949 for Item
in NewPcdValueList
:
952 TokenSpaceGuidName
= ''
953 if Item
.startswith('GUID') and Item
.endswith(')'):
955 TokenSpaceGuidName
= re
.search('GUID\((\w+)\)', Item
).group(1)
958 if TokenSpaceGuidName
and TokenSpaceGuidName
in self
._Symb
:
959 Item
= 'GUID(' + self
._Symb
[TokenSpaceGuidName
] + ')'
960 elif TokenSpaceGuidName
:
961 raise BadExpression('%s not found in DEC file' % TokenSpaceGuidName
)
962 Item
, Size
= ParseFieldValue(Item
)
963 for Index
in range(0, Size
):
964 ValueStr
= '0x%02X' % (int(Item
) & 255)
966 AllPcdValueList
.append(ValueStr
)
968 elif Item
.startswith('DEVICE_PATH') and Item
.endswith(')'):
969 Item
, Size
= ParseFieldValue(Item
)
970 AllPcdValueList
.append(Item
[1:-1])
974 if Item
.startswith('UINT8'):
977 elif Item
.startswith('UINT16'):
980 elif Item
.startswith('UINT32'):
983 elif Item
.startswith('UINT64'):
989 TmpValue
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
991 TmpValue
= ValueExpressionEx(Item
, self
.PcdType
, self
._Symb
)(True)
992 Item
= '0x%x' % TmpValue
if type(TmpValue
) != type('') else TmpValue
994 ItemValue
, ItemSize
= ParseFieldValue(Item
)
995 if Item
[0] not in ['"','L','{'] and ItemSize
> 1:
996 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
998 ItemValue
= ParseFieldValue(Item
)[0]
999 for I
in range(0, ItemSize
):
1000 ValueStr
= '0x%02X' % (int(ItemValue
) & 255)
1002 AllPcdValueList
.append(ValueStr
)
1006 PcdValue
= '{' + ','.join(AllPcdValueList
) + '}'
1008 raise BadExpression("Type: %s, Value: %s, %s"%(self
.PcdType
, PcdValue
, Value
))
1010 if PcdValue
== 'True':
1012 if PcdValue
== 'False':
1018 if __name__
== '__main__':
1021 input = raw_input('Input expr: ')
1025 print ValueExpression(input)(True)
1026 print ValueExpression(input)(False)
1027 except WrnExpression
, Ex
:
1030 except Exception, Ex
: