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'
53 for i
, ch
in enumerate(String
):
54 if ch
== '"' and not InSingleQuote
:
55 if String
[i
- 1] != '\\':
56 InDoubleQuote
= not InDoubleQuote
65 elif ch
== "'" and not InDoubleQuote
:
66 if String
[i
- 1] != '\\':
67 InSingleQuote
= not InSingleQuote
77 if InSingleQuote
or InDoubleQuote
:
78 raise BadExpression(ERR_STRING_TOKEN
% Item
)
83 def SplitPcdValueString(String
):
84 # There might be escaped comma in GUID() or DEVICE_PATH() or " "
85 # or ' ' or L' ' or L" "
91 for i
, ch
in enumerate(String
):
98 raise BadExpression(ERR_STRING_TOKEN
% Item
)
99 if ch
== '"' and not InSingleQuote
:
100 if String
[i
-1] != '\\':
101 InDoubleQuote
= not InDoubleQuote
102 if ch
== "'" and not InDoubleQuote
:
103 if String
[i
-1] != '\\':
104 InSingleQuote
= not InSingleQuote
106 if InParenthesis
or InSingleQuote
or InDoubleQuote
:
114 if InSingleQuote
or InDoubleQuote
or InParenthesis
:
115 raise BadExpression(ERR_STRING_TOKEN
% Item
)
120 def IsValidCString(Str
):
121 ValidString
= re
.compile(r
'[_a-zA-Z][_0-9a-zA-Z]*$')
122 if not ValidString
.match(Str
):
126 def BuildOptionValue(PcdValue
, GuidDict
):
128 if PcdValue
.startswith('H'):
129 InputValue
= PcdValue
[1:]
130 elif PcdValue
.startswith("L'") or PcdValue
.startswith("'"):
131 InputValue
= PcdValue
132 elif PcdValue
.startswith('L'):
133 InputValue
= 'L"' + PcdValue
[1:] + '"'
135 InputValue
= PcdValue
136 if IsFieldValueAnArray(InputValue
):
140 PcdValue
= ValueExpressionEx(InputValue
, 'VOID*', GuidDict
)(True)
147 def ReplaceExprMacro(String
, Macros
, ExceptionList
= None):
148 StrList
= SplitString(String
)
149 for i
, String
in enumerate(StrList
):
151 if String
.startswith('"'):
153 MacroStartPos
= String
.find('$(')
154 if MacroStartPos
< 0:
155 for Pcd
in gPlatformPcds
.keys():
157 if Pcd
not in gConditionalPcds
:
158 gConditionalPcds
.append(Pcd
)
161 while MacroStartPos
>= 0:
162 RetStr
= String
[0:MacroStartPos
]
163 MacroEndPos
= String
.find(')', MacroStartPos
)
165 raise BadExpression(ERR_MACRO_TOKEN
% String
[MacroStartPos
:])
166 Macro
= String
[MacroStartPos
+2:MacroEndPos
]
167 if Macro
not in Macros
:
168 # From C reference manual:
169 # If an undefined macro name appears in the constant-expression of
170 # !if or !elif, it is replaced by the integer constant 0.
173 Tklst
= RetStr
.split()
174 if Tklst
and Tklst
[-1] in ['IN', 'in'] and ExceptionList
and Macro
not in ExceptionList
:
175 raise BadExpression(ERR_IN_OPERAND
)
176 # Make sure the macro in exception list is encapsulated by double quote
177 # For example: DEFINE ARCH = IA32 X64
178 # $(ARCH) is replaced with "IA32 X64"
179 if ExceptionList
and Macro
in ExceptionList
:
180 RetStr
+= '"' + Macros
[Macro
] + '"'
181 elif Macros
[Macro
].strip():
182 RetStr
+= Macros
[Macro
]
186 RetStr
+= Macros
[Macro
]
187 RetStr
+= String
[MacroEndPos
+1:]
189 MacroStartPos
= String
.find('$(')
191 return ''.join(StrList
)
193 # transfer int to string for in/not in expression
197 StrList
.append(chr(Value
& 0xff))
199 Value
= '"' + ''.join(StrList
) + '"'
202 SupportedInMacroList
= ['TARGET', 'TOOL_CHAIN_TAG', 'ARCH', 'FAMILY']
204 class ValueExpression(object):
205 # Logical operator mapping
207 '&&' : 'and', '||' : 'or',
208 '!' : 'not', 'AND': 'and',
209 'OR' : 'or' , 'NOT': 'not',
210 'XOR': '^' , 'xor': '^',
211 'EQ' : '==' , 'NE' : '!=',
212 'GT' : '>' , 'LT' : '<',
213 'GE' : '>=' , 'LE' : '<=',
217 NonLetterOpLst
= ['+', '-', '*', '/', '%', '&', '|', '^', '~', '<<', '>>', '!', '=', '>', '<', '?', ':']
219 PcdPattern
= re
.compile(r
'[_a-zA-Z][0-9A-Za-z_]*\.[_a-zA-Z][0-9A-Za-z_]*$')
220 HexPattern
= re
.compile(r
'0[xX][0-9a-fA-F]+$')
221 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}')
223 SymbolPattern
= re
.compile("("
224 "\$\([A-Z][A-Z0-9_]*\)|\$\(\w+\.\w+\)|\w+\.\w+|"
226 "(?<=\W)AND(?=\W)|(?<=\W)OR(?=\W)|(?<=\W)NOT(?=\W)|(?<=\W)XOR(?=\W)|"
227 "(?<=\W)EQ(?=\W)|(?<=\W)NE(?=\W)|(?<=\W)GT(?=\W)|(?<=\W)LT(?=\W)|(?<=\W)GE(?=\W)|(?<=\W)LE(?=\W)"
231 def Eval(Operator
, Oprand1
, Oprand2
= None):
234 if Operator
not in ["==", "!=", ">=", "<=", ">", "<", "in", "not in"] and \
235 (type(Oprand1
) == type('') or type(Oprand2
) == type('')):
236 raise BadExpression(ERR_STRING_EXPR
% Operator
)
237 if Operator
in ['in', 'not in']:
238 if type(Oprand1
) != type(''):
239 Oprand1
= IntToStr(Oprand1
)
240 if type(Oprand2
) != type(''):
241 Oprand2
= IntToStr(Oprand2
)
250 if Operator
in ["!", "NOT", "not"]:
251 if type(Oprand1
) == type(''):
252 raise BadExpression(ERR_STRING_EXPR
% Operator
)
253 EvalStr
= 'not Oprand1'
254 elif Operator
in ["~"]:
255 if type(Oprand1
) == type(''):
256 raise BadExpression(ERR_STRING_EXPR
% Operator
)
257 EvalStr
= '~ Oprand1'
259 if Operator
in ["+", "-"] and (type(True) in [type(Oprand1
), type(Oprand2
)]):
260 # Boolean in '+'/'-' will be evaluated but raise warning
261 WrnExp
= WrnExpression(WRN_BOOL_EXPR
)
262 elif type('') in [type(Oprand1
), type(Oprand2
)] and type(Oprand1
)!= type(Oprand2
):
263 # == between string and number/boolean will always return False, != return True
265 WrnExp
= WrnExpression(WRN_EQCMP_STR_OTHERS
)
266 WrnExp
.result
= False
268 elif Operator
== "!=":
269 WrnExp
= WrnExpression(WRN_NECMP_STR_OTHERS
)
273 raise BadExpression(ERR_RELCMP_STR_OTHERS
% Operator
)
274 elif TypeDict
[type(Oprand1
)] != TypeDict
[type(Oprand2
)]:
275 if Operator
in ["==", "!=", ">=", "<=", ">", "<"] and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
276 # comparison between number and boolean is allowed
278 elif Operator
in ['&', '|', '^', "and", "or"] and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
279 # bitwise and logical operation between number and boolean is allowed
282 raise BadExpression(ERR_EXPR_TYPE
)
283 if type(Oprand1
) == type('') and type(Oprand2
) == type(''):
284 if (Oprand1
.startswith('L"') and not Oprand2
.startswith('L"')) or \
285 (not Oprand1
.startswith('L"') and Oprand2
.startswith('L"')):
286 raise BadExpression(ERR_STRING_CMP
% (Oprand1
, Operator
, Oprand2
))
287 if 'in' in Operator
and type(Oprand2
) == type(''):
288 Oprand2
= Oprand2
.split()
289 EvalStr
= 'Oprand1 ' + Operator
+ ' Oprand2'
291 # Local symbols used by built in eval function
297 Val
= eval(EvalStr
, {}, Dict
)
298 except Exception, Excpt
:
299 raise BadExpression(str(Excpt
))
301 if Operator
in ['and', 'or']:
312 def __init__(self
, Expression
, SymbolTable
={}):
313 self
._NoProcess
= False
314 if type(Expression
) != type(''):
315 self
._Expr
= Expression
316 self
._NoProcess
= True
319 self
._Expr
= ReplaceExprMacro(Expression
.strip(),
321 SupportedInMacroList
)
323 if not self
._Expr
.strip():
324 raise BadExpression(ERR_EMPTY_EXPR
)
327 # The symbol table including PCD and macro mapping
329 self
._Symb
= copy
.deepcopy(SymbolTable
)
330 self
._Symb
.update(self
.LogicalOperators
)
332 self
._Len
= len(self
._Expr
)
334 self
._WarnExcept
= None
336 # Literal token without any conversion
337 self
._LiteralToken
= ''
339 # Public entry for this class
340 # @param RealValue: False: only evaluate if the expression is true or false, used for conditional expression
341 # True : return the evaluated str(value), used for PCD value
343 # @return: True or False if RealValue is False
344 # Evaluated value of string format if RealValue is True
346 def __call__(self
, RealValue
=False, Depth
=0):
352 self
._Expr
= self
._Expr
.strip()
353 if RealValue
and Depth
== 0:
354 self
._Token
= self
._Expr
355 if self
.__IsNumberToken
():
359 Token
= self
._GetToken
()
360 except BadExpression
:
362 if type(Token
) == type('') and Token
.startswith('{') and Token
.endswith('}') and self
._Idx
>= self
._Len
:
368 Val
= self
._ConExpr
()
370 if type(Val
) == type(''):
376 elif not Val
.startswith('L"') and not Val
.startswith('{') and not Val
.startswith("L'"):
378 RealVal
= '"' + RealVal
+ '"'
380 # The expression has been parsed, but the end of expression is not reached
381 # It means the rest does not comply EBNF of <Expression>
382 if self
._Idx
!= self
._Len
:
383 raise BadExpression(ERR_SNYTAX
% self
._Expr
[self
._Idx
:])
386 RetVal
= str(RealVal
)
393 self
._WarnExcept
.result
= RetVal
394 raise self
._WarnExcept
398 # Template function to parse binary operators which have same precedence
399 # Expr [Operator Expr]*
400 def _ExprFuncTemplate(self
, EvalFunc
, OpLst
):
402 while self
._IsOperator
(OpLst
):
406 if self
._IsOperator
(':'):
414 Val
= self
.Eval(Op
, Val
, EvalFunc())
415 except WrnExpression
, Warn
:
416 self
._WarnExcept
= Warn
421 return self
._ExprFuncTemplate
(self
._OrExpr
, ['?', ':'])
425 return self
._ExprFuncTemplate
(self
._AndExpr
, ["OR", "or", "||"])
429 return self
._ExprFuncTemplate
(self
._BitOr
, ["AND", "and", "&&"])
433 return self
._ExprFuncTemplate
(self
._BitXor
, ["|"])
437 return self
._ExprFuncTemplate
(self
._BitAnd
, ["XOR", "xor", "^"])
441 return self
._ExprFuncTemplate
(self
._EqExpr
, ["&"])
445 Val
= self
._RelExpr
()
446 while self
._IsOperator
(["==", "!=", "EQ", "NE", "IN", "in", "!", "NOT", "not"]):
448 if Op
in ["!", "NOT", "not"]:
449 if not self
._IsOperator
(["IN", "in"]):
450 raise BadExpression(ERR_REL_NOT_IN
)
451 Op
+= ' ' + self
._Token
453 Val
= self
.Eval(Op
, Val
, self
._RelExpr
())
454 except WrnExpression
, Warn
:
455 self
._WarnExcept
= Warn
461 return self
._ExprFuncTemplate
(self
._ShiftExpr
, ["<=", ">=", "<", ">", "LE", "GE", "LT", "GT"])
463 def _ShiftExpr(self
):
464 return self
._ExprFuncTemplate
(self
._AddExpr
, ["<<", ">>"])
468 return self
._ExprFuncTemplate
(self
._MulExpr
, ["+", "-"])
472 return self
._ExprFuncTemplate
(self
._UnaryExpr
, ["*", "/", "%"])
475 def _UnaryExpr(self
):
476 if self
._IsOperator
(["!", "NOT", "not"]):
477 Val
= self
._UnaryExpr
()
479 return self
.Eval('not', Val
)
480 except WrnExpression
, Warn
:
481 self
._WarnExcept
= Warn
483 if self
._IsOperator
(["~"]):
484 Val
= self
._UnaryExpr
()
486 return self
.Eval('~', Val
)
487 except WrnExpression
, Warn
:
488 self
._WarnExcept
= Warn
490 return self
._IdenExpr
()
492 # Parse identifier or encapsulated expression
494 Tk
= self
._GetToken
()
496 Val
= self
._ConExpr
()
498 # _GetToken may also raise BadExpression
499 if self
._GetToken
() != ')':
500 raise BadExpression(ERR_MATCH
)
501 except BadExpression
:
502 raise BadExpression(ERR_MATCH
)
506 # Skip whitespace or tab
508 for Char
in self
._Expr
[self
._Idx
:]:
509 if Char
not in ' \t':
513 # Try to convert string to number
514 def __IsNumberToken(self
):
516 if self
._Token
.lower()[0:2] == '0x' and len(self
._Token
) > 2:
518 if self
._Token
.startswith('"') or self
._Token
.startswith('L"'):
520 for Index
in range(len(self
._Token
)):
521 if self
._Token
[Index
] in ['"']:
522 if self
._Token
[Index
- 1] == '\\':
525 if Flag
== 2 and self
._Token
.endswith('"'):
527 if self
._Token
.startswith("'") or self
._Token
.startswith("L'"):
529 for Index
in range(len(self
._Token
)):
530 if self
._Token
[Index
] in ["'"]:
531 if self
._Token
[Index
- 1] == '\\':
534 if Flag
== 2 and self
._Token
.endswith("'"):
537 self
._Token
= int(self
._Token
, Radix
)
545 def __GetArray(self
):
548 self
.__GetNList
(True)
549 Token
+= self
._LiteralToken
550 if self
._Idx
>= self
._Len
or self
._Expr
[self
._Idx
] != '}':
551 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
554 # All whitespace and tabs in array are already stripped.
555 IsArray
= IsGuid
= False
556 if len(Token
.split(',')) == 11 and len(Token
.split(',{')) == 2 \
557 and len(Token
.split('},')) == 1:
558 HexLen
= [11,6,6,5,4,4,4,4,4,4,6]
559 HexList
= Token
.split(',')
560 if HexList
[3].startswith('{') and \
561 not [Index
for Index
, Hex
in enumerate(HexList
) if len(Hex
) > HexLen
[Index
]]:
563 if Token
.lstrip('{').rstrip('}').find('{') == -1:
564 if not [Hex
for Hex
in Token
.lstrip('{').rstrip('}').split(',') if len(Hex
) > 4]:
566 if not IsArray
and not IsGuid
:
567 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
569 self
._Token
= self
._LiteralToken
= Token
572 # Parse string, the format must be: "..."
573 def __GetString(self
):
579 # Replace escape \\\", \"
580 if self
._Expr
[Idx
] == '"':
581 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace('\\\"', '\\\'')
586 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
587 if not self
._Token
.endswith('"'):
588 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
589 #Replace escape \\\', \'
590 elif self
._Expr
[Idx
] == "'":
591 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace("\\\'", "\\\"")
596 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
597 if not self
._Token
.endswith("'"):
598 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
599 self
._Token
= self
._Token
[1:-1]
602 # Get token that is comprised by alphanumeric, underscore or dot(used by PCD)
603 # @param IsAlphaOp: Indicate if parsing general token or script operator(EQ, NE...)
604 def __GetIdToken(self
, IsAlphaOp
= False):
606 for Ch
in self
._Expr
[self
._Idx
:]:
607 if not self
.__IsIdChar
(Ch
) or ('?' in self
._Expr
and Ch
== ':'):
612 self
._Token
= self
._LiteralToken
= IdToken
614 self
.__ResolveToken
()
617 # Try to resolve token
618 def __ResolveToken(self
):
620 raise BadExpression(ERR_EMPTY_TOKEN
)
623 if self
.PcdPattern
.match(self
._Token
):
624 if self
._Token
not in self
._Symb
:
625 Ex
= BadExpression(ERR_PCD_RESOLVE
% self
._Token
)
628 self
._Token
= ValueExpression(self
._Symb
[self
._Token
], self
._Symb
)(True, self
._Depth
+1)
629 if type(self
._Token
) != type(''):
630 self
._LiteralToken
= hex(self
._Token
)
633 if self
._Token
.startswith('"'):
634 self
._Token
= self
._Token
[1:-1]
635 elif self
._Token
in ["FALSE", "false", "False"]:
637 elif self
._Token
in ["TRUE", "true", "True"]:
640 self
.__IsNumberToken
()
642 def __GetNList(self
, InArray
=False):
643 self
._GetSingleToken
()
644 if not self
.__IsHexLiteral
():
646 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
650 Expr
= self
._Expr
[self
._Idx
:]
651 if not Expr
.startswith(','):
654 NList
= self
._LiteralToken
655 while Expr
.startswith(','):
659 self
._GetSingleToken
()
660 if not self
.__IsHexLiteral
():
661 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
662 NList
+= self
._LiteralToken
664 Expr
= self
._Expr
[self
._Idx
:]
665 self
._Token
= self
._LiteralToken
= NList
668 def __IsHexLiteral(self
):
669 if self
._LiteralToken
.startswith('{') and \
670 self
._LiteralToken
.endswith('}'):
673 if self
.HexPattern
.match(self
._LiteralToken
):
674 Token
= self
._LiteralToken
[2:]
676 self
._LiteralToken
= '0x0'
678 self
._LiteralToken
= '0x' + Token
683 return self
.__GetNList
()
687 return Ch
in '._:' or Ch
.isalnum()
690 def _GetSingleToken(self
):
692 Expr
= self
._Expr
[self
._Idx
:]
693 if Expr
.startswith('L"'):
696 UStr
= self
.__GetString
()
697 self
._Token
= 'L"' + UStr
+ '"'
699 elif Expr
.startswith("L'"):
702 UStr
= self
.__GetString
()
703 self
._Token
= "L'" + UStr
+ "'"
705 elif Expr
.startswith("'"):
706 UStr
= self
.__GetString
()
707 self
._Token
= "'" + UStr
+ "'"
709 elif Expr
.startswith('UINT'):
710 Re
= re
.compile('(?:UINT8|UINT16|UINT32|UINT64)\((.+)\)')
712 RetValue
= Re
.search(Expr
).group(1)
714 raise BadExpression('Invalid Expression %s' % Expr
)
719 Prefix
= self
._Expr
[Idx
:self
._Idx
- 1]
722 TmpValue
= self
._Expr
[Idx
:self
._Idx
- 1]
723 TmpValue
= ValueExpression(TmpValue
)(True)
724 TmpValue
= '0x%x' % int(TmpValue
) if type(TmpValue
) != type('') else TmpValue
726 self
._Token
, Size
= ParseFieldValue(Prefix
+ '(' + TmpValue
+ ')')
732 Match
= self
.RegGuidPattern
.match(Expr
)
733 if Match
and not Expr
[Match
.end():Match
.end()+1].isalnum() \
734 and Expr
[Match
.end():Match
.end()+1] != '_':
735 self
._Idx
+= Match
.end()
736 self
._Token
= ValueExpression(GuidStringToGuidStructureString(Expr
[0:Match
.end()]))(True, self
._Depth
+1)
738 elif self
.__IsIdChar
(Ch
):
739 return self
.__GetIdToken
()
741 return self
.__GetString
()
743 return self
.__GetArray
()
744 elif Ch
== '(' or Ch
== ')':
749 raise BadExpression(ERR_VALID_TOKEN
% Expr
)
752 def _GetOperator(self
):
754 LegalOpLst
= ['&&', '||', '!=', '==', '>=', '<='] + self
.NonLetterOpLst
+ ['?',':']
757 Expr
= self
._Expr
[self
._Idx
:]
759 # Reach end of expression
763 # Script operator: LT, GT, LE, GE, EQ, NE, and, or, xor, not
764 if Expr
[0].isalpha():
765 return self
.__GetIdToken
(True)
767 # Start to get regular operator: +, -, <, > ...
768 if Expr
[0] not in self
.NonLetterOpLst
:
773 if Ch
in self
.NonLetterOpLst
:
774 if '!' == Ch
and OpToken
:
781 if OpToken
not in LegalOpLst
:
782 raise BadExpression(ERR_OPERATOR_UNSUPPORT
% OpToken
)
783 self
._Token
= OpToken
786 # Check if current token matches the operators given from OpList
787 def _IsOperator(self
, OpList
):
790 if self
._Token
in OpList
:
791 if self
._Token
in self
.LogicalOperators
:
792 self
._Token
= self
.LogicalOperators
[self
._Token
]
797 class ValueExpressionEx(ValueExpression
):
798 def __init__(self
, PcdValue
, PcdType
, SymbolTable
={}):
799 ValueExpression
.__init
__(self
, PcdValue
, SymbolTable
)
800 self
.PcdValue
= PcdValue
801 self
.PcdType
= PcdType
803 def __call__(self
, RealValue
=False, Depth
=0):
804 PcdValue
= self
.PcdValue
806 PcdValue
= ValueExpression
.__call
__(self
, RealValue
, Depth
)
807 if self
.PcdType
== 'VOID*' and (PcdValue
.startswith("'") or PcdValue
.startswith("L'")):
808 PcdValue
, Size
= ParseFieldValue(PcdValue
)
810 for I
in range(Size
):
811 PcdValueList
.append('0x%02X'%(PcdValue
& 0xff))
812 PcdValue
= PcdValue
>> 8
813 PcdValue
= '{' + ','.join(PcdValueList
) + '}'
814 elif self
.PcdType
in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN'] and (PcdValue
.startswith("'") or \
815 PcdValue
.startswith('"') or PcdValue
.startswith("L'") or PcdValue
.startswith('L"') or PcdValue
.startswith('{')):
817 except WrnExpression
, Value
:
818 PcdValue
= Value
.result
819 except BadExpression
, Value
:
820 if self
.PcdType
in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN']:
821 PcdValue
= PcdValue
.strip()
822 if type(PcdValue
) == type('') and PcdValue
.startswith('{') and PcdValue
.endswith('}'):
823 PcdValue
= SplitPcdValueString(PcdValue
[1:-1])
824 if type(PcdValue
) == type([]):
828 for Item
in PcdValue
:
830 if Item
.startswith('UINT8'):
833 elif Item
.startswith('UINT16'):
836 elif Item
.startswith('UINT32'):
839 elif Item
.startswith('UINT64'):
842 elif Item
.startswith('"') or Item
.startswith("'") or Item
.startswith('L'):
848 Item
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
852 tmpValue
= int(Item
, 16) if Item
.upper().startswith('0X') else int(Item
, 0)
854 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
855 except BadExpression
, Value
:
856 raise BadExpression(Value
)
859 ItemValue
, ItemSize
= ParseFieldValue(Item
)
861 ItemValue
= ParseFieldValue(Item
)[0]
863 if type(ItemValue
) == type(''):
864 ItemValue
= int(ItemValue
, 16) if ItemValue
.startswith('0x') else int(ItemValue
)
866 TmpValue
= (ItemValue
<< (Size
* 8)) | TmpValue
867 Size
= Size
+ ItemSize
870 TmpValue
, Size
= ParseFieldValue(PcdValue
)
871 except BadExpression
, Value
:
872 raise BadExpression("Type: %s, Value: %s, %s" % (self
.PcdType
, PcdValue
, Value
))
873 if type(TmpValue
) == type(''):
875 TmpValue
= int(TmpValue
)
877 raise BadExpression(Value
)
879 PcdValue
= '0x%0{}X'.format(Size
) % (TmpValue
)
881 raise BadExpression('Type %s PCD Value is negative' % self
.PcdType
)
882 if self
.PcdType
== 'UINT8' and Size
> 1:
883 raise BadExpression('Type %s PCD Value Size is Larger than 1 byte' % self
.PcdType
)
884 if self
.PcdType
== 'UINT16' and Size
> 2:
885 raise BadExpression('Type %s PCD Value Size is Larger than 2 byte' % self
.PcdType
)
886 if self
.PcdType
== 'UINT32' and Size
> 4:
887 raise BadExpression('Type %s PCD Value Size is Larger than 4 byte' % self
.PcdType
)
888 if self
.PcdType
== 'UINT64' and Size
> 8:
889 raise BadExpression('Type %s PCD Value Size is Larger than 8 byte' % self
.PcdType
)
892 TmpValue
= long(PcdValue
)
894 if TmpValue
.bit_length() == 0:
897 for I
in range((TmpValue
.bit_length() + 7) / 8):
898 TmpList
.append('0x%02x' % ((TmpValue
>> I
* 8) & 0xff))
899 PcdValue
= '{' + ', '.join(TmpList
) + '}'
901 if PcdValue
.strip().startswith('{'):
902 PcdValueList
= SplitPcdValueString(PcdValue
.strip()[1:-1])
905 ReLabel
= re
.compile('LABEL\((\w+)\)')
906 ReOffset
= re
.compile('OFFSET_OF\((\w+)\)')
908 for Index
, Item
in enumerate(PcdValueList
):
909 # compute byte offset of every LABEL
910 LabelList
= ReLabel
.findall(Item
)
911 Item
= ReLabel
.sub('', Item
)
914 for Label
in LabelList
:
915 if not IsValidCString(Label
):
916 raise BadExpression('%s is not a valid c variable name' % Label
)
917 if Label
not in LabelDict
.keys():
918 LabelDict
[Label
] = str(LabelOffset
)
919 if Item
.startswith('UINT8'):
920 LabelOffset
= LabelOffset
+ 1
921 elif Item
.startswith('UINT16'):
922 LabelOffset
= LabelOffset
+ 2
923 elif Item
.startswith('UINT32'):
924 LabelOffset
= LabelOffset
+ 4
925 elif Item
.startswith('UINT64'):
926 LabelOffset
= LabelOffset
+ 8
929 ItemValue
, ItemSize
= ParseFieldValue(Item
)
930 LabelOffset
= LabelOffset
+ ItemSize
932 LabelOffset
= LabelOffset
+ 1
934 for Index
, Item
in enumerate(PcdValueList
):
938 Item
= ReLabel
.sub('', Item
)
942 OffsetList
= ReOffset
.findall(Item
)
945 for Offset
in OffsetList
:
946 if Offset
in LabelDict
.keys():
947 Re
= re
.compile('OFFSET_OF\(%s\)' % Offset
)
948 Item
= Re
.sub(LabelDict
[Offset
], Item
)
950 raise BadExpression('%s not defined' % Offset
)
951 NewPcdValueList
.append(Item
)
954 for Item
in NewPcdValueList
:
957 TokenSpaceGuidName
= ''
958 if Item
.startswith('GUID') and Item
.endswith(')'):
960 TokenSpaceGuidName
= re
.search('GUID\((\w+)\)', Item
).group(1)
963 if TokenSpaceGuidName
and TokenSpaceGuidName
in self
._Symb
:
964 Item
= 'GUID(' + self
._Symb
[TokenSpaceGuidName
] + ')'
965 elif TokenSpaceGuidName
:
966 raise BadExpression('%s not found in DEC file' % TokenSpaceGuidName
)
967 Item
, Size
= ParseFieldValue(Item
)
968 for Index
in range(0, Size
):
969 ValueStr
= '0x%02X' % (int(Item
) & 255)
971 AllPcdValueList
.append(ValueStr
)
973 elif Item
.startswith('DEVICE_PATH') and Item
.endswith(')'):
974 Item
, Size
= ParseFieldValue(Item
)
975 AllPcdValueList
.append(Item
[1:-1])
979 if Item
.startswith('UINT8'):
982 elif Item
.startswith('UINT16'):
985 elif Item
.startswith('UINT32'):
988 elif Item
.startswith('UINT64'):
994 TmpValue
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
996 TmpValue
= ValueExpressionEx(Item
, self
.PcdType
, self
._Symb
)(True)
997 Item
= '0x%x' % TmpValue
if type(TmpValue
) != type('') else TmpValue
999 ItemValue
, ItemSize
= ParseFieldValue(Item
)
1000 if not (Item
.startswith('"') or Item
.startswith('L') or Item
.startswith('{')) and ItemSize
> 1:
1001 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
1003 ItemValue
= ParseFieldValue(Item
)[0]
1004 for I
in range(0, ItemSize
):
1005 ValueStr
= '0x%02X' % (int(ItemValue
) & 255)
1007 AllPcdValueList
.append(ValueStr
)
1011 PcdValue
= '{' + ','.join(AllPcdValueList
) + '}'
1013 raise BadExpression("Type: %s, Value: %s, %s"%(self
.PcdType
, PcdValue
, Value
))
1015 if PcdValue
== 'True':
1017 if PcdValue
== 'False':
1023 if __name__
== '__main__':
1026 input = raw_input('Input expr: ')
1030 print ValueExpression(input)(True)
1031 print ValueExpression(input)(False)
1032 except WrnExpression
, Ex
:
1035 except Exception, Ex
: