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]*$')
46 # Split string to list according double quote
47 # For example: abc"de\"f"ghi"jkl"mn will be: ['abc', '"de\"f"', 'ghi', '"jkl"', 'mn']
49 def SplitString(String
):
50 # There might be escaped quote: "abc\"def\\\"ghi", 'abc\'def\\\'ghi'
55 for i
, ch
in enumerate(String
):
56 if ch
== '"' and not InSingleQuote
:
57 if String
[i
- 1] != '\\':
58 InDoubleQuote
= not InDoubleQuote
67 elif ch
== "'" and not InDoubleQuote
:
68 if String
[i
- 1] != '\\':
69 InSingleQuote
= not InSingleQuote
79 if InSingleQuote
or InDoubleQuote
:
80 raise BadExpression(ERR_STRING_TOKEN
% Item
)
85 def SplitPcdValueString(String
):
86 # There might be escaped comma in GUID() or DEVICE_PATH() or " "
87 # or ' ' or L' ' or L" "
93 for i
, ch
in enumerate(String
):
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 IsValidCName(Str
):
123 return True if __ValidString
.match(Str
) else False
125 def BuildOptionValue(PcdValue
, GuidDict
):
127 if PcdValue
.startswith('H'):
128 InputValue
= PcdValue
[1:]
129 elif PcdValue
.startswith("L'") or PcdValue
.startswith("'"):
130 InputValue
= PcdValue
131 elif PcdValue
.startswith('L'):
132 InputValue
= 'L"' + PcdValue
[1:] + '"'
134 InputValue
= PcdValue
135 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
= ['+', '-', '*', '/', '%', '&', '|', '^', '~', '<<', '>>', '!', '=', '>', '<', '?', ':']
218 PcdPattern
= re
.compile(r
'[_a-zA-Z][0-9A-Za-z_]*\.[_a-zA-Z][0-9A-Za-z_]*$')
219 HexPattern
= re
.compile(r
'0[xX][0-9a-fA-F]+$')
220 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}')
222 SymbolPattern
= re
.compile("("
223 "\$\([A-Z][A-Z0-9_]*\)|\$\(\w+\.\w+\)|\w+\.\w+|"
225 "(?<=\W)AND(?=\W)|(?<=\W)OR(?=\W)|(?<=\W)NOT(?=\W)|(?<=\W)XOR(?=\W)|"
226 "(?<=\W)EQ(?=\W)|(?<=\W)NE(?=\W)|(?<=\W)GT(?=\W)|(?<=\W)LT(?=\W)|(?<=\W)GE(?=\W)|(?<=\W)LE(?=\W)"
230 def Eval(Operator
, Oprand1
, Oprand2
= None):
233 if Operator
not in ["==", "!=", ">=", "<=", ">", "<", "in", "not in"] and \
234 (type(Oprand1
) == type('') or type(Oprand2
) == type('')):
235 raise BadExpression(ERR_STRING_EXPR
% Operator
)
236 if Operator
in ['in', 'not in']:
237 if type(Oprand1
) != type(''):
238 Oprand1
= IntToStr(Oprand1
)
239 if type(Oprand2
) != type(''):
240 Oprand2
= IntToStr(Oprand2
)
249 if Operator
in ["!", "NOT", "not"]:
250 if type(Oprand1
) == type(''):
251 raise BadExpression(ERR_STRING_EXPR
% Operator
)
252 EvalStr
= 'not Oprand1'
253 elif Operator
in ["~"]:
254 if type(Oprand1
) == type(''):
255 raise BadExpression(ERR_STRING_EXPR
% Operator
)
256 EvalStr
= '~ Oprand1'
258 if Operator
in ["+", "-"] and (type(True) in [type(Oprand1
), type(Oprand2
)]):
259 # Boolean in '+'/'-' will be evaluated but raise warning
260 WrnExp
= WrnExpression(WRN_BOOL_EXPR
)
261 elif type('') in [type(Oprand1
), type(Oprand2
)] and type(Oprand1
)!= type(Oprand2
):
262 # == between string and number/boolean will always return False, != return True
264 WrnExp
= WrnExpression(WRN_EQCMP_STR_OTHERS
)
265 WrnExp
.result
= False
267 elif Operator
== "!=":
268 WrnExp
= WrnExpression(WRN_NECMP_STR_OTHERS
)
272 raise BadExpression(ERR_RELCMP_STR_OTHERS
% Operator
)
273 elif TypeDict
[type(Oprand1
)] != TypeDict
[type(Oprand2
)]:
274 if Operator
in ["==", "!=", ">=", "<=", ">", "<"] and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
275 # comparison between number and boolean is allowed
277 elif Operator
in ['&', '|', '^', "and", "or"] and set((TypeDict
[type(Oprand1
)], TypeDict
[type(Oprand2
)])) == set((TypeDict
[type(True)], TypeDict
[type(0)])):
278 # bitwise and logical operation between number and boolean is allowed
281 raise BadExpression(ERR_EXPR_TYPE
)
282 if type(Oprand1
) == type('') and type(Oprand2
) == type(''):
283 if (Oprand1
.startswith('L"') and not Oprand2
.startswith('L"')) or \
284 (not Oprand1
.startswith('L"') and Oprand2
.startswith('L"')):
285 raise BadExpression(ERR_STRING_CMP
% (Oprand1
, Operator
, Oprand2
))
286 if 'in' in Operator
and type(Oprand2
) == type(''):
287 Oprand2
= Oprand2
.split()
288 EvalStr
= 'Oprand1 ' + Operator
+ ' Oprand2'
290 # Local symbols used by built in eval function
296 Val
= eval(EvalStr
, {}, Dict
)
297 except Exception, Excpt
:
298 raise BadExpression(str(Excpt
))
300 if Operator
in ['and', 'or']:
311 def __init__(self
, Expression
, SymbolTable
={}):
312 self
._NoProcess
= False
313 if type(Expression
) != type(''):
314 self
._Expr
= Expression
315 self
._NoProcess
= True
318 self
._Expr
= ReplaceExprMacro(Expression
.strip(),
320 SupportedInMacroList
)
322 if not self
._Expr
.strip():
323 raise BadExpression(ERR_EMPTY_EXPR
)
326 # The symbol table including PCD and macro mapping
328 self
._Symb
= copy
.deepcopy(SymbolTable
)
329 self
._Symb
.update(self
.LogicalOperators
)
331 self
._Len
= len(self
._Expr
)
333 self
._WarnExcept
= None
335 # Literal token without any conversion
336 self
._LiteralToken
= ''
338 # Public entry for this class
339 # @param RealValue: False: only evaluate if the expression is true or false, used for conditional expression
340 # True : return the evaluated str(value), used for PCD value
342 # @return: True or False if RealValue is False
343 # Evaluated value of string format if RealValue is True
345 def __call__(self
, RealValue
=False, Depth
=0):
351 self
._Expr
= self
._Expr
.strip()
352 if RealValue
and Depth
== 0:
353 self
._Token
= self
._Expr
354 if self
.__IsNumberToken
():
358 Token
= self
._GetToken
()
359 except BadExpression
:
361 if type(Token
) == type('') and Token
.startswith('{') and Token
.endswith('}') and self
._Idx
>= self
._Len
:
367 Val
= self
._ConExpr
()
369 if type(Val
) == type(''):
375 elif not Val
.startswith('L"') and not Val
.startswith('{') and not Val
.startswith("L'"):
377 RealVal
= '"' + RealVal
+ '"'
379 # The expression has been parsed, but the end of expression is not reached
380 # It means the rest does not comply EBNF of <Expression>
381 if self
._Idx
!= self
._Len
:
382 raise BadExpression(ERR_SNYTAX
% self
._Expr
[self
._Idx
:])
385 RetVal
= str(RealVal
)
392 self
._WarnExcept
.result
= RetVal
393 raise self
._WarnExcept
397 # Template function to parse binary operators which have same precedence
398 # Expr [Operator Expr]*
399 def _ExprFuncTemplate(self
, EvalFunc
, OpLst
):
401 while self
._IsOperator
(OpLst
):
405 if self
._IsOperator
(':'):
413 Val
= self
.Eval(Op
, Val
, EvalFunc())
414 except WrnExpression
, Warn
:
415 self
._WarnExcept
= Warn
420 return self
._ExprFuncTemplate
(self
._OrExpr
, ['?', ':'])
424 return self
._ExprFuncTemplate
(self
._AndExpr
, ["OR", "or", "||"])
428 return self
._ExprFuncTemplate
(self
._BitOr
, ["AND", "and", "&&"])
432 return self
._ExprFuncTemplate
(self
._BitXor
, ["|"])
436 return self
._ExprFuncTemplate
(self
._BitAnd
, ["XOR", "xor", "^"])
440 return self
._ExprFuncTemplate
(self
._EqExpr
, ["&"])
444 Val
= self
._RelExpr
()
445 while self
._IsOperator
(["==", "!=", "EQ", "NE", "IN", "in", "!", "NOT", "not"]):
447 if Op
in ["!", "NOT", "not"]:
448 if not self
._IsOperator
(["IN", "in"]):
449 raise BadExpression(ERR_REL_NOT_IN
)
450 Op
+= ' ' + self
._Token
452 Val
= self
.Eval(Op
, Val
, self
._RelExpr
())
453 except WrnExpression
, Warn
:
454 self
._WarnExcept
= Warn
460 return self
._ExprFuncTemplate
(self
._ShiftExpr
, ["<=", ">=", "<", ">", "LE", "GE", "LT", "GT"])
462 def _ShiftExpr(self
):
463 return self
._ExprFuncTemplate
(self
._AddExpr
, ["<<", ">>"])
467 return self
._ExprFuncTemplate
(self
._MulExpr
, ["+", "-"])
471 return self
._ExprFuncTemplate
(self
._UnaryExpr
, ["*", "/", "%"])
474 def _UnaryExpr(self
):
475 if self
._IsOperator
(["!", "NOT", "not"]):
476 Val
= self
._UnaryExpr
()
478 return self
.Eval('not', Val
)
479 except WrnExpression
, Warn
:
480 self
._WarnExcept
= Warn
482 if self
._IsOperator
(["~"]):
483 Val
= self
._UnaryExpr
()
485 return self
.Eval('~', Val
)
486 except WrnExpression
, Warn
:
487 self
._WarnExcept
= Warn
489 return self
._IdenExpr
()
491 # Parse identifier or encapsulated expression
493 Tk
= self
._GetToken
()
495 Val
= self
._ConExpr
()
497 # _GetToken may also raise BadExpression
498 if self
._GetToken
() != ')':
499 raise BadExpression(ERR_MATCH
)
500 except BadExpression
:
501 raise BadExpression(ERR_MATCH
)
505 # Skip whitespace or tab
507 for Char
in self
._Expr
[self
._Idx
:]:
508 if Char
not in ' \t':
512 # Try to convert string to number
513 def __IsNumberToken(self
):
515 if self
._Token
.lower()[0:2] == '0x' and len(self
._Token
) > 2:
517 if self
._Token
.startswith('"') or self
._Token
.startswith('L"'):
519 for Index
in range(len(self
._Token
)):
520 if self
._Token
[Index
] in ['"']:
521 if self
._Token
[Index
- 1] == '\\':
524 if Flag
== 2 and self
._Token
.endswith('"'):
526 if self
._Token
.startswith("'") or self
._Token
.startswith("L'"):
528 for Index
in range(len(self
._Token
)):
529 if self
._Token
[Index
] in ["'"]:
530 if self
._Token
[Index
- 1] == '\\':
533 if Flag
== 2 and self
._Token
.endswith("'"):
536 self
._Token
= int(self
._Token
, Radix
)
544 def __GetArray(self
):
547 self
.__GetNList
(True)
548 Token
+= self
._LiteralToken
549 if self
._Idx
>= self
._Len
or self
._Expr
[self
._Idx
] != '}':
550 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
553 # All whitespace and tabs in array are already stripped.
554 IsArray
= IsGuid
= False
555 if len(Token
.split(',')) == 11 and len(Token
.split(',{')) == 2 \
556 and len(Token
.split('},')) == 1:
557 HexLen
= [11,6,6,5,4,4,4,4,4,4,6]
558 HexList
= Token
.split(',')
559 if HexList
[3].startswith('{') and \
560 not [Index
for Index
, Hex
in enumerate(HexList
) if len(Hex
) > HexLen
[Index
]]:
562 if Token
.lstrip('{').rstrip('}').find('{') == -1:
563 if not [Hex
for Hex
in Token
.lstrip('{').rstrip('}').split(',') if len(Hex
) > 4]:
565 if not IsArray
and not IsGuid
:
566 raise BadExpression(ERR_ARRAY_TOKEN
% Token
)
568 self
._Token
= self
._LiteralToken
= Token
571 # Parse string, the format must be: "..."
572 def __GetString(self
):
578 # Replace escape \\\", \"
579 if self
._Expr
[Idx
] == '"':
580 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace('\\\"', '\\\'')
585 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
586 if not self
._Token
.endswith('"'):
587 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
588 #Replace escape \\\', \'
589 elif self
._Expr
[Idx
] == "'":
590 Expr
= self
._Expr
[self
._Idx
:].replace('\\\\', '//').replace("\\\'", "\\\"")
595 self
._Token
= self
._LiteralToken
= self
._Expr
[Idx
:self
._Idx
]
596 if not self
._Token
.endswith("'"):
597 raise BadExpression(ERR_STRING_TOKEN
% self
._Token
)
598 self
._Token
= self
._Token
[1:-1]
601 # Get token that is comprised by alphanumeric, underscore or dot(used by PCD)
602 # @param IsAlphaOp: Indicate if parsing general token or script operator(EQ, NE...)
603 def __GetIdToken(self
, IsAlphaOp
= False):
605 for Ch
in self
._Expr
[self
._Idx
:]:
606 if not self
.__IsIdChar
(Ch
) or ('?' in self
._Expr
and Ch
== ':'):
611 self
._Token
= self
._LiteralToken
= IdToken
613 self
.__ResolveToken
()
616 # Try to resolve token
617 def __ResolveToken(self
):
619 raise BadExpression(ERR_EMPTY_TOKEN
)
622 if self
.PcdPattern
.match(self
._Token
):
623 if self
._Token
not in self
._Symb
:
624 Ex
= BadExpression(ERR_PCD_RESOLVE
% self
._Token
)
627 self
._Token
= ValueExpression(self
._Symb
[self
._Token
], self
._Symb
)(True, self
._Depth
+1)
628 if type(self
._Token
) != type(''):
629 self
._LiteralToken
= hex(self
._Token
)
632 if self
._Token
.startswith('"'):
633 self
._Token
= self
._Token
[1:-1]
634 elif self
._Token
in ["FALSE", "false", "False"]:
636 elif self
._Token
in ["TRUE", "true", "True"]:
639 self
.__IsNumberToken
()
641 def __GetNList(self
, InArray
=False):
642 self
._GetSingleToken
()
643 if not self
.__IsHexLiteral
():
645 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
649 Expr
= self
._Expr
[self
._Idx
:]
650 if not Expr
.startswith(','):
653 NList
= self
._LiteralToken
654 while Expr
.startswith(','):
658 self
._GetSingleToken
()
659 if not self
.__IsHexLiteral
():
660 raise BadExpression(ERR_ARRAY_ELE
% self
._Token
)
661 NList
+= self
._LiteralToken
663 Expr
= self
._Expr
[self
._Idx
:]
664 self
._Token
= self
._LiteralToken
= NList
667 def __IsHexLiteral(self
):
668 if self
._LiteralToken
.startswith('{') and \
669 self
._LiteralToken
.endswith('}'):
672 if self
.HexPattern
.match(self
._LiteralToken
):
673 Token
= self
._LiteralToken
[2:]
675 self
._LiteralToken
= '0x0'
677 self
._LiteralToken
= '0x' + Token
682 return self
.__GetNList
()
686 return Ch
in '._:' or Ch
.isalnum()
689 def _GetSingleToken(self
):
691 Expr
= self
._Expr
[self
._Idx
:]
692 if Expr
.startswith('L"'):
695 UStr
= self
.__GetString
()
696 self
._Token
= 'L"' + UStr
+ '"'
698 elif Expr
.startswith("L'"):
701 UStr
= self
.__GetString
()
702 self
._Token
= "L'" + UStr
+ "'"
704 elif Expr
.startswith("'"):
705 UStr
= self
.__GetString
()
706 self
._Token
= "'" + UStr
+ "'"
708 elif Expr
.startswith('UINT'):
709 Re
= re
.compile('(?:UINT8|UINT16|UINT32|UINT64)\((.+)\)')
711 RetValue
= Re
.search(Expr
).group(1)
713 raise BadExpression('Invalid Expression %s' % Expr
)
718 Prefix
= self
._Expr
[Idx
:self
._Idx
- 1]
721 TmpValue
= self
._Expr
[Idx
:self
._Idx
- 1]
722 TmpValue
= ValueExpression(TmpValue
)(True)
723 TmpValue
= '0x%x' % int(TmpValue
) if type(TmpValue
) != type('') else TmpValue
725 self
._Token
, Size
= ParseFieldValue(Prefix
+ '(' + TmpValue
+ ')')
731 Match
= self
.RegGuidPattern
.match(Expr
)
732 if Match
and not Expr
[Match
.end():Match
.end()+1].isalnum() \
733 and Expr
[Match
.end():Match
.end()+1] != '_':
734 self
._Idx
+= Match
.end()
735 self
._Token
= ValueExpression(GuidStringToGuidStructureString(Expr
[0:Match
.end()]))(True, self
._Depth
+1)
737 elif self
.__IsIdChar
(Ch
):
738 return self
.__GetIdToken
()
740 return self
.__GetString
()
742 return self
.__GetArray
()
743 elif Ch
== '(' or Ch
== ')':
748 raise BadExpression(ERR_VALID_TOKEN
% Expr
)
751 def _GetOperator(self
):
753 LegalOpLst
= ['&&', '||', '!=', '==', '>=', '<='] + self
.NonLetterOpLst
+ ['?',':']
756 Expr
= self
._Expr
[self
._Idx
:]
758 # Reach end of expression
762 # Script operator: LT, GT, LE, GE, EQ, NE, and, or, xor, not
763 if Expr
[0].isalpha():
764 return self
.__GetIdToken
(True)
766 # Start to get regular operator: +, -, <, > ...
767 if Expr
[0] not in self
.NonLetterOpLst
:
772 if Ch
in self
.NonLetterOpLst
:
773 if '!' == Ch
and OpToken
:
780 if OpToken
not in LegalOpLst
:
781 raise BadExpression(ERR_OPERATOR_UNSUPPORT
% OpToken
)
782 self
._Token
= OpToken
785 # Check if current token matches the operators given from OpList
786 def _IsOperator(self
, OpList
):
789 if self
._Token
in OpList
:
790 if self
._Token
in self
.LogicalOperators
:
791 self
._Token
= self
.LogicalOperators
[self
._Token
]
796 class ValueExpressionEx(ValueExpression
):
797 def __init__(self
, PcdValue
, PcdType
, SymbolTable
={}):
798 ValueExpression
.__init
__(self
, PcdValue
, SymbolTable
)
799 self
.PcdValue
= PcdValue
800 self
.PcdType
= PcdType
802 def __call__(self
, RealValue
=False, Depth
=0):
803 PcdValue
= self
.PcdValue
805 PcdValue
= ValueExpression
.__call
__(self
, RealValue
, Depth
)
806 if self
.PcdType
== 'VOID*' and (PcdValue
.startswith("'") or PcdValue
.startswith("L'")):
807 PcdValue
, Size
= ParseFieldValue(PcdValue
)
809 for I
in range(Size
):
810 PcdValueList
.append('0x%02X'%(PcdValue
& 0xff))
811 PcdValue
= PcdValue
>> 8
812 PcdValue
= '{' + ','.join(PcdValueList
) + '}'
813 elif self
.PcdType
in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN'] and (PcdValue
.startswith("'") or \
814 PcdValue
.startswith('"') or PcdValue
.startswith("L'") or PcdValue
.startswith('L"') or PcdValue
.startswith('{')):
816 except WrnExpression
, Value
:
817 PcdValue
= Value
.result
818 except BadExpression
, Value
:
819 if self
.PcdType
in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN']:
820 PcdValue
= PcdValue
.strip()
821 if type(PcdValue
) == type('') and PcdValue
.startswith('{') and PcdValue
.endswith('}'):
822 PcdValue
= SplitPcdValueString(PcdValue
[1:-1])
823 if type(PcdValue
) == type([]):
827 for Item
in PcdValue
:
829 if Item
.startswith('UINT8'):
832 elif Item
.startswith('UINT16'):
835 elif Item
.startswith('UINT32'):
838 elif Item
.startswith('UINT64'):
841 elif Item
.startswith('"') or Item
.startswith("'") or Item
.startswith('L'):
847 Item
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
851 tmpValue
= int(Item
, 16) if Item
.upper().startswith('0X') else int(Item
, 0)
853 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
854 except BadExpression
, Value
:
855 raise BadExpression(Value
)
858 ItemValue
, ItemSize
= ParseFieldValue(Item
)
860 ItemValue
= ParseFieldValue(Item
)[0]
862 if type(ItemValue
) == type(''):
863 ItemValue
= int(ItemValue
, 16) if ItemValue
.startswith('0x') else int(ItemValue
)
865 TmpValue
= (ItemValue
<< (Size
* 8)) | TmpValue
866 Size
= Size
+ ItemSize
869 TmpValue
, Size
= ParseFieldValue(PcdValue
)
870 except BadExpression
, Value
:
871 raise BadExpression("Type: %s, Value: %s, %s" % (self
.PcdType
, PcdValue
, Value
))
872 if type(TmpValue
) == type(''):
874 TmpValue
= int(TmpValue
)
876 raise BadExpression(Value
)
878 PcdValue
= '0x%0{}X'.format(Size
) % (TmpValue
)
880 raise BadExpression('Type %s PCD Value is negative' % self
.PcdType
)
881 if self
.PcdType
== 'UINT8' and Size
> 1:
882 raise BadExpression('Type %s PCD Value Size is Larger than 1 byte' % self
.PcdType
)
883 if self
.PcdType
== 'UINT16' and Size
> 2:
884 raise BadExpression('Type %s PCD Value Size is Larger than 2 byte' % self
.PcdType
)
885 if self
.PcdType
== 'UINT32' and Size
> 4:
886 raise BadExpression('Type %s PCD Value Size is Larger than 4 byte' % self
.PcdType
)
887 if self
.PcdType
== 'UINT64' and Size
> 8:
888 raise BadExpression('Type %s PCD Value Size is Larger than 8 byte' % self
.PcdType
)
891 TmpValue
= long(PcdValue
)
893 if TmpValue
.bit_length() == 0:
896 for I
in range((TmpValue
.bit_length() + 7) / 8):
897 TmpList
.append('0x%02x' % ((TmpValue
>> I
* 8) & 0xff))
898 PcdValue
= '{' + ', '.join(TmpList
) + '}'
900 if PcdValue
.strip().startswith('{'):
901 PcdValueList
= SplitPcdValueString(PcdValue
.strip()[1:-1])
904 ReLabel
= re
.compile('LABEL\((\w+)\)')
905 ReOffset
= re
.compile('OFFSET_OF\((\w+)\)')
907 for Index
, Item
in enumerate(PcdValueList
):
908 # compute byte offset of every LABEL
909 LabelList
= ReLabel
.findall(Item
)
910 Item
= ReLabel
.sub('', Item
)
913 for Label
in LabelList
:
914 if not IsValidCName(Label
):
915 raise BadExpression('%s is not a valid c variable name' % Label
)
916 if Label
not in LabelDict
.keys():
917 LabelDict
[Label
] = str(LabelOffset
)
918 if Item
.startswith('UINT8'):
919 LabelOffset
= LabelOffset
+ 1
920 elif Item
.startswith('UINT16'):
921 LabelOffset
= LabelOffset
+ 2
922 elif Item
.startswith('UINT32'):
923 LabelOffset
= LabelOffset
+ 4
924 elif Item
.startswith('UINT64'):
925 LabelOffset
= LabelOffset
+ 8
928 ItemValue
, ItemSize
= ParseFieldValue(Item
)
929 LabelOffset
= LabelOffset
+ ItemSize
931 LabelOffset
= LabelOffset
+ 1
933 for Index
, Item
in enumerate(PcdValueList
):
937 Item
= ReLabel
.sub('', Item
)
941 OffsetList
= ReOffset
.findall(Item
)
944 for Offset
in OffsetList
:
945 if Offset
in LabelDict
.keys():
946 Re
= re
.compile('OFFSET_OF\(%s\)' % Offset
)
947 Item
= Re
.sub(LabelDict
[Offset
], Item
)
949 raise BadExpression('%s not defined' % Offset
)
950 NewPcdValueList
.append(Item
)
953 for Item
in NewPcdValueList
:
956 TokenSpaceGuidName
= ''
957 if Item
.startswith('GUID') and Item
.endswith(')'):
959 TokenSpaceGuidName
= re
.search('GUID\((\w+)\)', Item
).group(1)
962 if TokenSpaceGuidName
and TokenSpaceGuidName
in self
._Symb
:
963 Item
= 'GUID(' + self
._Symb
[TokenSpaceGuidName
] + ')'
964 elif TokenSpaceGuidName
:
965 raise BadExpression('%s not found in DEC file' % TokenSpaceGuidName
)
966 Item
, Size
= ParseFieldValue(Item
)
967 for Index
in range(0, Size
):
968 ValueStr
= '0x%02X' % (int(Item
) & 255)
970 AllPcdValueList
.append(ValueStr
)
972 elif Item
.startswith('DEVICE_PATH') and Item
.endswith(')'):
973 Item
, Size
= ParseFieldValue(Item
)
974 AllPcdValueList
.append(Item
[1:-1])
978 if Item
.startswith('UINT8'):
981 elif Item
.startswith('UINT16'):
984 elif Item
.startswith('UINT32'):
987 elif Item
.startswith('UINT64'):
993 TmpValue
= ValueExpressionEx(Item
, ValueType
, self
._Symb
)(True)
995 TmpValue
= ValueExpressionEx(Item
, self
.PcdType
, self
._Symb
)(True)
996 Item
= '0x%x' % TmpValue
if type(TmpValue
) != type('') else TmpValue
998 ItemValue
, ItemSize
= ParseFieldValue(Item
)
999 if not (Item
.startswith('"') or Item
.startswith('L') or Item
.startswith('{')) and ItemSize
> 1:
1000 raise BadExpression("Byte array number %s should less than 0xFF." % Item
)
1002 ItemValue
= ParseFieldValue(Item
)[0]
1003 for I
in range(0, ItemSize
):
1004 ValueStr
= '0x%02X' % (int(ItemValue
) & 255)
1006 AllPcdValueList
.append(ValueStr
)
1010 PcdValue
= '{' + ','.join(AllPcdValueList
) + '}'
1012 raise BadExpression("Type: %s, Value: %s, %s"%(self
.PcdType
, PcdValue
, Value
))
1014 if PcdValue
== 'True':
1016 if PcdValue
== 'False':
1022 if __name__
== '__main__':
1025 input = raw_input('Input expr: ')
1029 print ValueExpression(input)(True)
1030 print ValueExpression(input)(False)
1031 except WrnExpression
, Ex
:
1034 except Exception, Ex
: