2017-01-24 02:00:00 +08:00
# Copyright 2016-2017 The Meson development team
2016-11-20 01:48:12 +08:00
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This class contains the basic functionality needed to run any interpreter
# or an interpreter-based tool.
2021-06-10 18:18:06 +08:00
from . . import mparser , mesonlib , mlog
2021-06-20 00:02:19 +08:00
from . . import environment
2016-11-20 01:48:12 +08:00
2021-06-10 19:08:59 +08:00
from . baseobjects import (
InterpreterObject ,
2021-06-17 06:07:04 +08:00
MesonInterpreterObject ,
2021-06-10 19:08:59 +08:00
MutableInterpreterObject ,
2021-06-17 06:07:04 +08:00
InterpreterObjectTypeVar ,
2021-06-10 19:08:59 +08:00
ObjectHolder ,
RangeHolder ,
2021-06-17 06:07:04 +08:00
TYPE_elementary ,
2021-06-10 19:08:59 +08:00
TYPE_var ,
2021-06-17 06:07:04 +08:00
TYPE_kwargs ,
2021-06-10 19:08:59 +08:00
)
2021-06-10 18:38:11 +08:00
from . exceptions import (
InterpreterException ,
InvalidCode ,
InvalidArguments ,
SubdirDoneRequest ,
ContinueRequest ,
BreakRequest
)
2021-06-10 19:25:09 +08:00
from . decorators import FeatureNew , builtinMethodNoKwargs
2021-06-10 19:18:42 +08:00
from . disabler import Disabler , is_disabled
2021-06-26 03:14:27 +08:00
from . helpers import check_stringlist , default_resolve_key , flatten , resolve_second_level_holders
2021-06-17 06:07:04 +08:00
from . _unholder import _unholder
2021-06-10 19:08:59 +08:00
2021-01-15 02:41:04 +08:00
import os , copy , re
2020-01-09 00:44:50 +08:00
import typing as T
2019-12-09 02:22:14 +08:00
2021-06-17 06:07:04 +08:00
if T . TYPE_CHECKING :
from . . interpreter import Interpreter
HolderMapType = T . Dict [
T . Type [ mesonlib . HoldableObject ] ,
# For some reason, this has to be a callable and can't just be ObjectHolder[InterpreterObjectTypeVar]
T . Callable [ [ InterpreterObjectTypeVar , ' Interpreter ' ] , ObjectHolder [ InterpreterObjectTypeVar ] ]
]
FunctionType = T . Dict [
str ,
T . Callable [ [ mparser . BaseNode , T . List [ TYPE_var ] , T . Dict [ str , TYPE_var ] ] , TYPE_var ]
]
2018-07-18 01:54:56 +08:00
2020-08-15 05:41:18 +08:00
class MesonVersionString ( str ) :
pass
2016-11-20 01:48:12 +08:00
class InterpreterBase :
2021-06-12 01:56:06 +08:00
elementary_types = ( int , str , bool , list )
2019-12-09 02:22:14 +08:00
2020-01-29 03:57:07 +08:00
def __init__ ( self , source_root : str , subdir : str , subproject : str ) :
2016-11-20 01:48:12 +08:00
self . source_root = source_root
2021-06-17 06:07:04 +08:00
self . funcs : FunctionType = { }
self . builtin : T . Dict [ str , InterpreterObject ] = { }
# Holder maps store a mapping from an HoldableObject to a class ObjectHolder
self . holder_map : HolderMapType = { }
self . bound_holder_map : HolderMapType = { }
2016-11-20 01:48:12 +08:00
self . subdir = subdir
2020-09-28 20:49:41 +08:00
self . root_subdir = subdir
2019-12-08 03:48:44 +08:00
self . subproject = subproject
2021-06-17 06:07:04 +08:00
# TODO: This should actually be more strict: T.Union[TYPE_elementary, InterpreterObject]
self . variables : T . Dict [ str , T . Union [ TYPE_var , InterpreterObject ] ] = { }
2017-01-24 02:00:00 +08:00
self . argument_depth = 0
2017-08-14 20:54:07 +08:00
self . current_lineno = - 1
2019-01-23 01:33:12 +08:00
# Current node set during a function call. This can be used as location
# when printing a warning message during a method call.
2019-12-09 02:22:14 +08:00
self . current_node = None # type: mparser.BaseNode
2020-08-15 05:41:18 +08:00
# This is set to `version_string` when this statement is evaluated:
# meson.version().compare_version(version_string)
# If it was part of a if-clause, it is used to temporally override the
# current meson version target within that if-block.
2020-09-02 22:45:15 +08:00
self . tmp_meson_version = None # type: T.Optional[str]
2016-11-20 01:48:12 +08:00
2019-12-09 02:22:14 +08:00
def load_root_meson_file ( self ) - > None :
2016-11-20 01:48:12 +08:00
mesonfile = os . path . join ( self . source_root , self . subdir , environment . build_filename )
if not os . path . isfile ( mesonfile ) :
raise InvalidArguments ( ' Missing Meson file in %s ' % mesonfile )
2021-06-23 04:59:16 +08:00
with open ( mesonfile , encoding = ' utf-8 ' ) as mf :
2016-11-20 01:48:12 +08:00
code = mf . read ( )
Don't use len() to test emptiness vs not emptiness
Meson has a common pattern of using 'if len(foo) == 0:' or
'if len(foo) != 0:', however, this is a common anti-pattern in python.
Instead tests for emptiness/non-emptiness should be done with a simple
'if foo:' or 'if not foo:'
Consider the following:
>>> import timeit
>>> timeit.timeit('if len([]) == 0: pass')
0.10730923599840025
>>> timeit.timeit('if not []: pass')
0.030033907998586074
>>> timeit.timeit('if len(['a', 'b', 'c', 'd']) == 0: pass')
0.1154778649979562
>>> timeit.timeit("if not ['a', 'b', 'c', 'd']: pass")
0.08259823200205574
>>> timeit.timeit('if len("") == 0: pass')
0.089759664999292
>>> timeit.timeit('if not "": pass')
0.02340641999762738
>>> timeit.timeit('if len("foo") == 0: pass')
0.08848102600313723
>>> timeit.timeit('if not "foo": pass')
0.04032287199879647
And for the one additional case of 'if len(foo.strip()) == 0', which can
be replaced with 'if not foo.isspace()'
>>> timeit.timeit('if len(" ".strip()) == 0: pass')
0.15294511600222904
>>> timeit.timeit('if " ".isspace(): pass')
0.09413968399894657
>>> timeit.timeit('if len(" abc".strip()) == 0: pass')
0.2023209120015963
>>> timeit.timeit('if " abc".isspace(): pass')
0.09571301700270851
In other words, it's always a win to not use len(), when you don't
actually want to check the length.
2017-05-02 06:11:01 +08:00
if code . isspace ( ) :
2016-11-20 01:48:12 +08:00
raise InvalidCode ( ' Builder file is empty. ' )
assert ( isinstance ( code , str ) )
try :
2020-02-14 10:58:37 +08:00
self . ast = mparser . Parser ( code , mesonfile ) . parse ( )
2016-11-20 01:48:12 +08:00
except mesonlib . MesonException as me :
2019-10-10 05:40:30 +08:00
me . file = mesonfile
2016-11-20 01:48:12 +08:00
raise me
2016-11-20 02:18:30 +08:00
2020-01-09 00:44:50 +08:00
def join_path_strings ( self , args : T . Sequence [ str ] ) - > str :
2018-10-31 05:27:51 +08:00
return os . path . join ( * args ) . replace ( ' \\ ' , ' / ' )
2019-12-09 02:22:14 +08:00
def parse_project ( self ) - > None :
2016-11-20 02:18:30 +08:00
"""
Parses project ( ) and initializes languages , compilers etc . Do this
early because we need this before we parse the rest of the AST .
"""
self . evaluate_codeblock ( self . ast , end = 1 )
2019-12-09 02:22:14 +08:00
def sanity_check_ast ( self ) - > None :
2016-11-20 02:18:30 +08:00
if not isinstance ( self . ast , mparser . CodeBlockNode ) :
raise InvalidCode ( ' AST is of invalid type. Possibly a bug in the parser. ' )
Don't use len() to test emptiness vs not emptiness
Meson has a common pattern of using 'if len(foo) == 0:' or
'if len(foo) != 0:', however, this is a common anti-pattern in python.
Instead tests for emptiness/non-emptiness should be done with a simple
'if foo:' or 'if not foo:'
Consider the following:
>>> import timeit
>>> timeit.timeit('if len([]) == 0: pass')
0.10730923599840025
>>> timeit.timeit('if not []: pass')
0.030033907998586074
>>> timeit.timeit('if len(['a', 'b', 'c', 'd']) == 0: pass')
0.1154778649979562
>>> timeit.timeit("if not ['a', 'b', 'c', 'd']: pass")
0.08259823200205574
>>> timeit.timeit('if len("") == 0: pass')
0.089759664999292
>>> timeit.timeit('if not "": pass')
0.02340641999762738
>>> timeit.timeit('if len("foo") == 0: pass')
0.08848102600313723
>>> timeit.timeit('if not "foo": pass')
0.04032287199879647
And for the one additional case of 'if len(foo.strip()) == 0', which can
be replaced with 'if not foo.isspace()'
>>> timeit.timeit('if len(" ".strip()) == 0: pass')
0.15294511600222904
>>> timeit.timeit('if " ".isspace(): pass')
0.09413968399894657
>>> timeit.timeit('if len(" abc".strip()) == 0: pass')
0.2023209120015963
>>> timeit.timeit('if " abc".isspace(): pass')
0.09571301700270851
In other words, it's always a win to not use len(), when you don't
actually want to check the length.
2017-05-02 06:11:01 +08:00
if not self . ast . lines :
2016-11-20 02:18:30 +08:00
raise InvalidCode ( ' No statements in code. ' )
first = self . ast . lines [ 0 ]
if not isinstance ( first , mparser . FunctionNode ) or first . func_name != ' project ' :
raise InvalidCode ( ' First statement must be a call to project ' )
2019-12-09 02:22:14 +08:00
def run ( self ) - > None :
2016-11-20 02:18:30 +08:00
# Evaluate everything after the first line, which is project() because
# we already parsed that in self.parse_project()
2018-06-07 02:23:17 +08:00
try :
self . evaluate_codeblock ( self . ast , start = 1 )
except SubdirDoneRequest :
pass
2016-11-20 02:18:30 +08:00
2020-01-09 00:44:50 +08:00
def evaluate_codeblock ( self , node : mparser . CodeBlockNode , start : int = 0 , end : T . Optional [ int ] = None ) - > None :
2016-11-20 02:18:30 +08:00
if node is None :
return
if not isinstance ( node , mparser . CodeBlockNode ) :
e = InvalidCode ( ' Tried to execute a non-codeblock. Possibly a bug in the parser. ' )
e . lineno = node . lineno
e . colno = node . colno
raise e
statements = node . lines [ start : end ]
i = 0
while i < len ( statements ) :
cur = statements [ i ]
try :
2017-08-14 20:54:07 +08:00
self . current_lineno = cur . lineno
2016-11-20 02:18:30 +08:00
self . evaluate_statement ( cur )
except Exception as e :
2020-03-12 05:41:26 +08:00
if getattr ( e , ' lineno ' , None ) is None :
2019-12-09 02:22:14 +08:00
# We are doing the equivalent to setattr here and mypy does not like it
e . lineno = cur . lineno # type: ignore
e . colno = cur . colno # type: ignore
e . file = os . path . join ( self . source_root , self . subdir , environment . build_filename ) # type: ignore
2016-11-20 02:18:30 +08:00
raise e
i + = 1 # In THE FUTURE jump over blocks and stuff.
2021-06-17 06:07:04 +08:00
def evaluate_statement ( self , cur : mparser . BaseNode ) - > T . Optional [ T . Union [ TYPE_var , InterpreterObject ] ] :
2020-03-13 02:36:52 +08:00
self . current_node = cur
2016-11-20 02:18:30 +08:00
if isinstance ( cur , mparser . FunctionNode ) :
return self . function_call ( cur )
elif isinstance ( cur , mparser . AssignmentNode ) :
2019-12-09 02:22:14 +08:00
self . assignment ( cur )
2016-11-20 02:18:30 +08:00
elif isinstance ( cur , mparser . MethodNode ) :
return self . method_call ( cur )
elif isinstance ( cur , mparser . StringNode ) :
2020-08-29 01:48:00 +08:00
return cur . value
2016-11-20 02:18:30 +08:00
elif isinstance ( cur , mparser . BooleanNode ) :
2020-08-29 01:48:00 +08:00
return cur . value
2016-11-20 02:18:30 +08:00
elif isinstance ( cur , mparser . IfClauseNode ) :
return self . evaluate_if ( cur )
elif isinstance ( cur , mparser . IdNode ) :
return self . get_variable ( cur . value )
elif isinstance ( cur , mparser . ComparisonNode ) :
return self . evaluate_comparison ( cur )
elif isinstance ( cur , mparser . ArrayNode ) :
return self . evaluate_arraystatement ( cur )
2018-04-28 07:56:56 +08:00
elif isinstance ( cur , mparser . DictNode ) :
return self . evaluate_dictstatement ( cur )
2016-11-20 02:18:30 +08:00
elif isinstance ( cur , mparser . NumberNode ) :
2020-08-29 01:48:00 +08:00
return cur . value
2016-11-20 02:18:30 +08:00
elif isinstance ( cur , mparser . AndNode ) :
return self . evaluate_andstatement ( cur )
elif isinstance ( cur , mparser . OrNode ) :
return self . evaluate_orstatement ( cur )
elif isinstance ( cur , mparser . NotNode ) :
return self . evaluate_notstatement ( cur )
elif isinstance ( cur , mparser . UMinusNode ) :
return self . evaluate_uminusstatement ( cur )
elif isinstance ( cur , mparser . ArithmeticNode ) :
return self . evaluate_arithmeticstatement ( cur )
elif isinstance ( cur , mparser . ForeachClauseNode ) :
2019-12-09 02:22:14 +08:00
self . evaluate_foreach ( cur )
2016-11-20 02:18:30 +08:00
elif isinstance ( cur , mparser . PlusAssignmentNode ) :
2019-12-09 02:22:14 +08:00
self . evaluate_plusassign ( cur )
2016-11-20 02:18:30 +08:00
elif isinstance ( cur , mparser . IndexNode ) :
return self . evaluate_indexing ( cur )
elif isinstance ( cur , mparser . TernaryNode ) :
return self . evaluate_ternary ( cur )
2021-03-07 11:59:38 +08:00
elif isinstance ( cur , mparser . FormatStringNode ) :
return self . evaluate_fstring ( cur )
2018-07-18 04:47:41 +08:00
elif isinstance ( cur , mparser . ContinueNode ) :
raise ContinueRequest ( )
elif isinstance ( cur , mparser . BreakNode ) :
raise BreakRequest ( )
2019-12-09 02:22:14 +08:00
elif isinstance ( cur , self . elementary_types ) :
2016-11-20 02:18:30 +08:00
return cur
else :
raise InvalidCode ( " Unknown statement. " )
2019-12-09 02:22:14 +08:00
return None
2016-11-20 02:18:30 +08:00
2021-06-17 06:07:04 +08:00
def evaluate_arraystatement ( self , cur : mparser . ArrayNode ) - > T . List [ T . Union [ TYPE_var , InterpreterObject ] ] :
2016-11-20 02:18:30 +08:00
( arguments , kwargs ) = self . reduce_arguments ( cur . args )
if len ( kwargs ) > 0 :
raise InvalidCode ( ' Keyword arguments are invalid in array construction. ' )
return arguments
2018-05-31 17:53:40 +08:00
@FeatureNew ( ' dict ' , ' 0.47.0 ' )
2021-06-17 06:07:04 +08:00
def evaluate_dictstatement ( self , cur : mparser . DictNode ) - > T . Union [ TYPE_var , InterpreterObject ] :
2020-08-28 23:58:54 +08:00
def resolve_key ( key : mparser . BaseNode ) - > str :
2019-12-04 12:34:47 +08:00
if not isinstance ( key , mparser . StringNode ) :
2020-05-13 01:53:37 +08:00
FeatureNew . single_use ( ' Dictionary entry using non literal key ' , ' 0.53.0 ' , self . subproject )
2019-12-09 02:22:14 +08:00
str_key = self . evaluate_statement ( key )
if not isinstance ( str_key , str ) :
2019-12-04 12:34:47 +08:00
raise InvalidArguments ( ' Key must be a string ' )
2020-08-28 23:58:54 +08:00
return str_key
arguments , kwargs = self . reduce_arguments ( cur . args , key_resolver = resolve_key , duplicate_key_error = ' Duplicate dictionary key: {} ' )
assert not arguments
return kwargs
2018-04-28 07:56:56 +08:00
2020-01-09 00:44:50 +08:00
def evaluate_notstatement ( self , cur : mparser . NotNode ) - > T . Union [ bool , Disabler ] :
2016-11-20 03:25:28 +08:00
v = self . evaluate_statement ( cur . value )
2019-12-09 02:22:14 +08:00
if isinstance ( v , Disabler ) :
2019-10-08 23:02:00 +08:00
return v
2016-11-20 03:25:28 +08:00
if not isinstance ( v , bool ) :
raise InterpreterException ( ' Argument to " not " is not a boolean. ' )
return not v
2020-01-09 00:44:50 +08:00
def evaluate_if ( self , node : mparser . IfClauseNode ) - > T . Optional [ Disabler ] :
2016-11-20 03:25:28 +08:00
assert ( isinstance ( node , mparser . IfClauseNode ) )
for i in node . ifs :
2020-08-15 05:41:18 +08:00
# Reset self.tmp_meson_version to know if it gets set during this
# statement evaluation.
self . tmp_meson_version = None
2016-11-20 03:25:28 +08:00
result = self . evaluate_statement ( i . condition )
2019-12-09 02:22:14 +08:00
if isinstance ( result , Disabler ) :
2017-09-23 01:51:30 +08:00
return result
2016-11-20 03:25:28 +08:00
if not ( isinstance ( result , bool ) ) :
2021-03-05 06:16:11 +08:00
raise InvalidCode ( f ' If clause { result !r} does not evaluate to true or false. ' )
2016-11-20 03:25:28 +08:00
if result :
2020-08-15 05:41:18 +08:00
prev_meson_version = mesonlib . project_meson_versions [ self . subproject ]
if self . tmp_meson_version :
mesonlib . project_meson_versions [ self . subproject ] = self . tmp_meson_version
try :
self . evaluate_codeblock ( i . block )
finally :
mesonlib . project_meson_versions [ self . subproject ] = prev_meson_version
2019-12-09 02:22:14 +08:00
return None
2016-11-20 03:25:28 +08:00
if not isinstance ( node . elseblock , mparser . EmptyNode ) :
self . evaluate_codeblock ( node . elseblock )
2019-12-09 02:22:14 +08:00
return None
2016-11-20 02:18:30 +08:00
2020-01-09 00:44:50 +08:00
def validate_comparison_types ( self , val1 : T . Any , val2 : T . Any ) - > bool :
2018-01-07 03:26:27 +08:00
if type ( val1 ) != type ( val2 ) :
2018-02-09 23:24:57 +08:00
return False
return True
2018-01-07 03:26:27 +08:00
2020-01-09 00:44:50 +08:00
def evaluate_in ( self , val1 : T . Any , val2 : T . Any ) - > bool :
2021-06-28 23:22:14 +08:00
if not isinstance ( val1 , ( str , int , float , mesonlib . HoldableObject ) ) :
2018-07-18 01:54:56 +08:00
raise InvalidArguments ( ' lvalue of " in " operator must be a string, integer, float, or object ' )
if not isinstance ( val2 , ( list , dict ) ) :
raise InvalidArguments ( ' rvalue of " in " operator must be an array or a dict ' )
return val1 in val2
2020-01-09 00:44:50 +08:00
def evaluate_comparison ( self , node : mparser . ComparisonNode ) - > T . Union [ bool , Disabler ] :
2017-05-18 07:40:49 +08:00
val1 = self . evaluate_statement ( node . left )
2019-12-09 02:22:14 +08:00
if isinstance ( val1 , Disabler ) :
2017-09-23 01:51:30 +08:00
return val1
2017-05-18 07:40:49 +08:00
val2 = self . evaluate_statement ( node . right )
2019-12-09 02:22:14 +08:00
if isinstance ( val2 , Disabler ) :
2017-09-23 01:51:30 +08:00
return val2
2021-06-28 23:22:14 +08:00
# Do not compare the ObjectHolders but the actual held objects
val1 = _unholder ( val1 )
val2 = _unholder ( val2 )
2018-07-18 01:54:56 +08:00
if node . ctype == ' in ' :
return self . evaluate_in ( val1 , val2 )
elif node . ctype == ' notin ' :
return not self . evaluate_in ( val1 , val2 )
2018-02-09 23:24:57 +08:00
valid = self . validate_comparison_types ( val1 , val2 )
# Ordering comparisons of different types isn't allowed since PR #1810
# (0.41.0). Since PR #2884 we also warn about equality comparisons of
# different types, which will one day become an error.
if not valid and ( node . ctype == ' == ' or node . ctype == ' != ' ) :
mlog . warning ( ''' Trying to compare values of different types ( {} , {} ) using {} .
2018-02-12 00:33:57 +08:00
The result of this is undefined and will become a hard error in a future Meson release . '''
. format ( type ( val1 ) . __name__ , type ( val2 ) . __name__ , node . ctype ) , location = node )
2016-11-20 04:11:20 +08:00
if node . ctype == ' == ' :
return val1 == val2
elif node . ctype == ' != ' :
return val1 != val2
2018-02-09 23:24:57 +08:00
elif not valid :
raise InterpreterException (
' Values of different types ( {} , {} ) cannot be compared using {} . ' . format ( type ( val1 ) . __name__ ,
type ( val2 ) . __name__ ,
node . ctype ) )
2019-12-09 02:22:14 +08:00
elif not isinstance ( val1 , self . elementary_types ) :
raise InterpreterException ( ' {} can only be compared for equality. ' . format ( getattr ( node . left , ' value ' , ' <ERROR> ' ) ) )
elif not isinstance ( val2 , self . elementary_types ) :
raise InterpreterException ( ' {} can only be compared for equality. ' . format ( getattr ( node . right , ' value ' , ' <ERROR> ' ) ) )
# Use type: ignore because mypy will complain that we are comparing two Unions,
# but we actually guarantee earlier that both types are the same
2016-11-20 04:11:20 +08:00
elif node . ctype == ' < ' :
2019-12-09 02:22:14 +08:00
return val1 < val2 # type: ignore
2016-11-20 04:11:20 +08:00
elif node . ctype == ' <= ' :
2019-12-09 02:22:14 +08:00
return val1 < = val2 # type: ignore
2016-11-20 04:11:20 +08:00
elif node . ctype == ' > ' :
2019-12-09 02:22:14 +08:00
return val1 > val2 # type: ignore
2016-11-20 04:11:20 +08:00
elif node . ctype == ' >= ' :
2019-12-09 02:22:14 +08:00
return val1 > = val2 # type: ignore
2016-11-20 04:11:20 +08:00
else :
raise InvalidCode ( ' You broke my compare eval. ' )
2020-01-09 00:44:50 +08:00
def evaluate_andstatement ( self , cur : mparser . AndNode ) - > T . Union [ bool , Disabler ] :
2016-11-20 04:11:20 +08:00
l = self . evaluate_statement ( cur . left )
2019-12-09 02:22:14 +08:00
if isinstance ( l , Disabler ) :
2017-09-23 01:51:30 +08:00
return l
2016-11-20 04:11:20 +08:00
if not isinstance ( l , bool ) :
raise InterpreterException ( ' First argument to " and " is not a boolean. ' )
if not l :
return False
r = self . evaluate_statement ( cur . right )
2019-12-09 02:22:14 +08:00
if isinstance ( r , Disabler ) :
2017-09-23 01:51:30 +08:00
return r
2016-11-20 04:11:20 +08:00
if not isinstance ( r , bool ) :
raise InterpreterException ( ' Second argument to " and " is not a boolean. ' )
return r
2020-01-09 00:44:50 +08:00
def evaluate_orstatement ( self , cur : mparser . OrNode ) - > T . Union [ bool , Disabler ] :
2016-11-20 04:11:20 +08:00
l = self . evaluate_statement ( cur . left )
2019-12-09 02:22:14 +08:00
if isinstance ( l , Disabler ) :
2017-09-23 01:51:30 +08:00
return l
2016-11-20 04:11:20 +08:00
if not isinstance ( l , bool ) :
raise InterpreterException ( ' First argument to " or " is not a boolean. ' )
if l :
return True
r = self . evaluate_statement ( cur . right )
2019-12-09 02:22:14 +08:00
if isinstance ( r , Disabler ) :
2017-09-23 01:51:30 +08:00
return r
2016-11-20 04:11:20 +08:00
if not isinstance ( r , bool ) :
raise InterpreterException ( ' Second argument to " or " is not a boolean. ' )
return r
2020-08-29 00:01:22 +08:00
def evaluate_uminusstatement ( self , cur : mparser . UMinusNode ) - > T . Union [ int , Disabler ] :
2016-11-20 04:11:20 +08:00
v = self . evaluate_statement ( cur . value )
2019-12-09 02:22:14 +08:00
if isinstance ( v , Disabler ) :
2017-09-23 01:51:30 +08:00
return v
2016-11-20 04:11:20 +08:00
if not isinstance ( v , int ) :
raise InterpreterException ( ' Argument to negation is not an integer. ' )
return - v
2019-03-14 17:35:00 +08:00
@FeatureNew ( ' / with string arguments ' , ' 0.49.0 ' )
2019-12-09 02:22:14 +08:00
def evaluate_path_join ( self , l : str , r : str ) - > str :
2019-03-14 17:35:00 +08:00
if not isinstance ( l , str ) :
raise InvalidCode ( ' The division operator can only append to a string. ' )
if not isinstance ( r , str ) :
raise InvalidCode ( ' The division operator can only append a string. ' )
return self . join_path_strings ( ( l , r ) )
2020-01-09 00:44:50 +08:00
def evaluate_division ( self , l : T . Any , r : T . Any ) - > T . Union [ int , str ] :
2019-03-14 17:35:00 +08:00
if isinstance ( l , str ) or isinstance ( r , str ) :
return self . evaluate_path_join ( l , r )
if isinstance ( l , int ) and isinstance ( r , int ) :
if r == 0 :
raise InvalidCode ( ' Division by zero. ' )
return l / / r
raise InvalidCode ( ' Division works only with strings or integers. ' )
2020-01-09 00:44:50 +08:00
def evaluate_arithmeticstatement ( self , cur : mparser . ArithmeticNode ) - > T . Union [ int , str , dict , list , Disabler ] :
2017-05-18 07:40:49 +08:00
l = self . evaluate_statement ( cur . left )
2019-12-09 02:22:14 +08:00
if isinstance ( l , Disabler ) :
2017-09-23 01:51:30 +08:00
return l
2017-05-18 07:40:49 +08:00
r = self . evaluate_statement ( cur . right )
2019-12-09 02:22:14 +08:00
if isinstance ( r , Disabler ) :
2017-09-23 01:51:30 +08:00
return r
2016-11-20 04:11:20 +08:00
if cur . operation == ' add ' :
2018-07-18 21:57:34 +08:00
if isinstance ( l , dict ) and isinstance ( r , dict ) :
return { * * l , * * r }
2016-11-20 04:11:20 +08:00
try :
2019-12-09 02:22:14 +08:00
# MyPy error due to handling two Unions (we are catching all exceptions anyway)
return l + r # type: ignore
2016-11-20 04:11:20 +08:00
except Exception as e :
raise InvalidCode ( ' Invalid use of addition: ' + str ( e ) )
elif cur . operation == ' sub ' :
if not isinstance ( l , int ) or not isinstance ( r , int ) :
raise InvalidCode ( ' Subtraction works only with integers. ' )
return l - r
elif cur . operation == ' mul ' :
if not isinstance ( l , int ) or not isinstance ( r , int ) :
raise InvalidCode ( ' Multiplication works only with integers. ' )
return l * r
elif cur . operation == ' div ' :
2019-03-14 17:35:00 +08:00
return self . evaluate_division ( l , r )
2016-11-20 04:11:20 +08:00
elif cur . operation == ' mod ' :
if not isinstance ( l , int ) or not isinstance ( r , int ) :
raise InvalidCode ( ' Modulo works only with integers. ' )
return l % r
else :
raise InvalidCode ( ' You broke me. ' )
2021-06-17 06:07:04 +08:00
def evaluate_ternary ( self , node : mparser . TernaryNode ) - > T . Union [ TYPE_var , InterpreterObject ] :
2016-11-20 04:11:20 +08:00
assert ( isinstance ( node , mparser . TernaryNode ) )
result = self . evaluate_statement ( node . condition )
2019-12-09 02:22:14 +08:00
if isinstance ( result , Disabler ) :
2017-09-23 01:51:30 +08:00
return result
2016-11-20 04:11:20 +08:00
if not isinstance ( result , bool ) :
raise InterpreterException ( ' Ternary condition is not boolean. ' )
if result :
return self . evaluate_statement ( node . trueblock )
else :
return self . evaluate_statement ( node . falseblock )
2021-03-08 06:08:35 +08:00
@FeatureNew ( ' format strings ' , ' 0.58.0 ' )
2021-03-07 11:59:38 +08:00
def evaluate_fstring ( self , node : mparser . FormatStringNode ) - > TYPE_var :
assert ( isinstance ( node , mparser . FormatStringNode ) )
def replace ( match : T . Match [ str ] ) - > str :
var = str ( match . group ( 1 ) )
try :
2021-03-08 04:02:32 +08:00
val = self . variables [ var ]
if not isinstance ( val , ( str , int , float , bool ) ) :
2021-03-08 06:25:39 +08:00
raise InvalidCode ( f ' Identifier " { var } " does not name a formattable variable ' +
' (has to be an integer, a string, a floating point number or a boolean). ' )
2021-03-08 04:02:32 +08:00
return str ( val )
2021-03-07 11:59:38 +08:00
except KeyError :
2021-03-08 04:16:13 +08:00
raise InvalidCode ( f ' Identifier " { var } " does not name a variable. ' )
2021-03-07 11:59:38 +08:00
2021-03-08 04:02:32 +08:00
return re . sub ( r ' @([_a-zA-Z][_0-9a-zA-Z]*)@ ' , replace , node . value )
2021-03-07 11:59:38 +08:00
2019-12-09 02:22:14 +08:00
def evaluate_foreach ( self , node : mparser . ForeachClauseNode ) - > None :
2016-11-20 04:11:20 +08:00
assert ( isinstance ( node , mparser . ForeachClauseNode ) )
items = self . evaluate_statement ( node . items )
2018-04-28 07:56:56 +08:00
2021-02-07 00:14:25 +08:00
if isinstance ( items , ( list , RangeHolder ) ) :
2018-04-28 07:56:56 +08:00
if len ( node . varnames ) != 1 :
raise InvalidArguments ( ' Foreach on array does not unpack ' )
2019-12-07 21:42:23 +08:00
varname = node . varnames [ 0 ]
2018-04-28 07:56:56 +08:00
for item in items :
self . set_variable ( varname , item )
2018-07-18 04:47:41 +08:00
try :
self . evaluate_codeblock ( node . block )
except ContinueRequest :
continue
except BreakRequest :
break
2018-04-28 07:56:56 +08:00
elif isinstance ( items , dict ) :
if len ( node . varnames ) != 2 :
raise InvalidArguments ( ' Foreach on dict unpacks key and value ' )
2020-10-26 18:14:54 +08:00
for key , value in sorted ( items . items ( ) ) :
2019-12-07 21:42:23 +08:00
self . set_variable ( node . varnames [ 0 ] , key )
self . set_variable ( node . varnames [ 1 ] , value )
2018-07-18 04:47:41 +08:00
try :
self . evaluate_codeblock ( node . block )
except ContinueRequest :
continue
except BreakRequest :
break
2018-04-28 07:56:56 +08:00
else :
raise InvalidArguments ( ' Items of foreach loop must be an array or a dict ' )
2016-11-20 04:11:20 +08:00
2019-12-09 02:22:14 +08:00
def evaluate_plusassign ( self , node : mparser . PlusAssignmentNode ) - > None :
2016-11-20 04:11:20 +08:00
assert ( isinstance ( node , mparser . PlusAssignmentNode ) )
varname = node . var_name
addition = self . evaluate_statement ( node . value )
2020-08-18 22:07:59 +08:00
2016-11-20 04:11:20 +08:00
# Remember that all variables are immutable. We must always create a
# full new variable and then assign it.
old_variable = self . get_variable ( varname )
2020-01-09 00:44:50 +08:00
new_value = None # type: T.Union[str, int, float, bool, dict, list]
2016-11-20 04:11:20 +08:00
if isinstance ( old_variable , str ) :
if not isinstance ( addition , str ) :
raise InvalidArguments ( ' The += operator requires a string on the right hand side if the variable on the left is a string ' )
new_value = old_variable + addition
elif isinstance ( old_variable , int ) :
if not isinstance ( addition , int ) :
raise InvalidArguments ( ' The += operator requires an int on the right hand side if the variable on the left is an int ' )
new_value = old_variable + addition
2018-07-18 21:57:34 +08:00
elif isinstance ( old_variable , list ) :
2016-11-20 04:11:20 +08:00
if isinstance ( addition , list ) :
new_value = old_variable + addition
else :
new_value = old_variable + [ addition ]
2018-07-18 21:57:34 +08:00
elif isinstance ( old_variable , dict ) :
if not isinstance ( addition , dict ) :
raise InvalidArguments ( ' The += operator requires a dict on the right hand side if the variable on the left is a dict ' )
2019-12-04 12:34:47 +08:00
new_value = { * * old_variable , * * addition }
2018-07-18 21:57:34 +08:00
# Add other data types here.
else :
2020-08-18 22:07:59 +08:00
raise InvalidArguments ( ' The += operator currently only works with arrays, dicts, strings or ints ' )
2016-11-20 04:11:20 +08:00
self . set_variable ( varname , new_value )
2021-06-17 06:07:04 +08:00
def evaluate_indexing ( self , node : mparser . IndexNode ) - > T . Union [ TYPE_elementary , InterpreterObject ] :
2016-11-20 04:11:20 +08:00
assert ( isinstance ( node , mparser . IndexNode ) )
iobject = self . evaluate_statement ( node . iobject )
2019-12-09 02:22:14 +08:00
if isinstance ( iobject , Disabler ) :
2017-09-23 01:51:30 +08:00
return iobject
2017-09-26 04:46:07 +08:00
if not hasattr ( iobject , ' __getitem__ ' ) :
raise InterpreterException (
' Tried to index an object that doesn \' t support indexing. ' )
2016-11-20 04:11:20 +08:00
index = self . evaluate_statement ( node . index )
2018-04-28 07:56:56 +08:00
if isinstance ( iobject , dict ) :
if not isinstance ( index , str ) :
raise InterpreterException ( ' Key is not a string ' )
try :
2020-09-02 01:36:21 +08:00
# The cast is required because we don't have recursive types...
2021-06-17 06:07:04 +08:00
return T . cast ( T . Union [ TYPE_elementary , InterpreterObject ] , iobject [ index ] )
2018-04-28 07:56:56 +08:00
except KeyError :
raise InterpreterException ( ' Key %s is not in dict ' % index )
else :
if not isinstance ( index , int ) :
raise InterpreterException ( ' Index value is not an integer. ' )
try :
2019-12-09 02:22:14 +08:00
# Ignore the MyPy error, since we don't know all indexable types here
# and we handle non indexable types with an exception
# TODO maybe find a better solution
2021-06-17 06:07:04 +08:00
res = iobject [ index ] # type: ignore
# Only holderify if we are dealing with `InterpreterObject`, since raw
# lists already store ObjectHolders
if isinstance ( iobject , InterpreterObject ) :
return self . _holderify ( res )
else :
return res
2018-04-28 07:56:56 +08:00
except IndexError :
2021-01-13 05:15:42 +08:00
# We are already checking for the existence of __getitem__, so this should be save
2019-12-09 02:22:14 +08:00
raise InterpreterException ( ' Index %d out of bounds of array of size %d . ' % ( index , len ( iobject ) ) ) # type: ignore
2016-11-20 04:11:20 +08:00
2021-06-17 06:07:04 +08:00
def function_call ( self , node : mparser . FunctionNode ) - > T . Optional [ T . Union [ TYPE_elementary , InterpreterObject ] ] :
2016-11-20 02:18:30 +08:00
func_name = node . func_name
2021-06-17 06:07:04 +08:00
( h_posargs , h_kwargs ) = self . reduce_arguments ( node . args )
( posargs , kwargs ) = self . _unholder_args ( h_posargs , h_kwargs )
2021-08-11 07:02:39 +08:00
if is_disabled ( posargs , kwargs ) and func_name not in { ' get_variable ' , ' set_variable ' , ' unset_variable ' , ' is_disabler ' } :
2017-09-23 01:51:30 +08:00
return Disabler ( )
2016-11-20 02:18:30 +08:00
if func_name in self . funcs :
2018-04-27 06:33:20 +08:00
func = self . funcs [ func_name ]
2021-06-17 06:07:04 +08:00
func_args = posargs
2018-04-27 06:33:20 +08:00
if not getattr ( func , ' no-args-flattening ' , False ) :
2019-12-09 02:22:14 +08:00
func_args = flatten ( posargs )
2021-06-26 03:14:27 +08:00
if not getattr ( func , ' no-second-level-holder-flattening ' , False ) :
func_args , kwargs = resolve_second_level_holders ( func_args , kwargs )
2021-06-17 06:07:04 +08:00
res = func ( node , func_args , kwargs )
return self . _holderify ( res )
2016-11-20 02:18:30 +08:00
else :
self . unknown_function_called ( func_name )
2019-12-09 02:22:14 +08:00
return None
2016-11-20 02:18:30 +08:00
2021-06-17 06:07:04 +08:00
def method_call ( self , node : mparser . MethodNode ) - > T . Optional [ T . Union [ TYPE_var , InterpreterObject ] ] :
2016-11-20 04:11:20 +08:00
invokable = node . source_object
2021-06-17 06:07:04 +08:00
obj : T . Union [ TYPE_var , InterpreterObject ]
2016-11-20 04:11:20 +08:00
if isinstance ( invokable , mparser . IdNode ) :
object_name = invokable . value
obj = self . get_variable ( object_name )
else :
obj = self . evaluate_statement ( invokable )
method_name = node . name
2021-06-17 06:07:04 +08:00
( h_args , h_kwargs ) = self . reduce_arguments ( node . args )
( args , kwargs ) = self . _unholder_args ( h_args , h_kwargs )
2019-12-09 02:22:14 +08:00
if is_disabled ( args , kwargs ) :
return Disabler ( )
2016-11-20 04:11:20 +08:00
if isinstance ( obj , str ) :
2020-03-13 02:36:52 +08:00
return self . string_method_call ( obj , method_name , args , kwargs )
2016-11-20 04:11:20 +08:00
if isinstance ( obj , bool ) :
2020-03-13 02:36:52 +08:00
return self . bool_method_call ( obj , method_name , args , kwargs )
2016-11-20 04:11:20 +08:00
if isinstance ( obj , int ) :
2020-03-13 02:36:52 +08:00
return self . int_method_call ( obj , method_name , args , kwargs )
2016-11-20 04:11:20 +08:00
if isinstance ( obj , list ) :
2020-03-13 02:36:52 +08:00
return self . array_method_call ( obj , method_name , args , kwargs )
2018-04-30 03:58:41 +08:00
if isinstance ( obj , dict ) :
2020-03-13 02:36:52 +08:00
return self . dict_method_call ( obj , method_name , args , kwargs )
2016-11-20 04:11:20 +08:00
if not isinstance ( obj , InterpreterObject ) :
raise InvalidArguments ( ' Variable " %s " is not callable. ' % object_name )
2017-09-23 01:51:30 +08:00
# Special case. This is the only thing you can do with a disabler
# object. Every other use immediately returns the disabler object.
2019-10-25 02:20:53 +08:00
if isinstance ( obj , Disabler ) :
if method_name == ' found ' :
return False
else :
return Disabler ( )
2021-06-17 06:07:04 +08:00
# TODO: InterpreterBase **really** shouldn't be in charge of checking this
2016-11-20 04:11:20 +08:00
if method_name == ' extract_objects ' :
2019-12-09 02:22:14 +08:00
if not isinstance ( obj , ObjectHolder ) :
2021-06-17 06:07:04 +08:00
raise InvalidArguments ( f ' Invalid operation " extract_objects " on variable " { object_name } " of type { type ( obj ) . __name__ } ' )
2016-11-20 04:11:20 +08:00
self . validate_extraction ( obj . held_object )
2019-01-23 01:33:12 +08:00
obj . current_node = node
2021-06-17 06:07:04 +08:00
return self . _holderify ( obj . method_call ( method_name , args , kwargs ) )
2021-06-20 00:02:19 +08:00
def _holderify ( self , res : T . Union [ TYPE_var , InterpreterObject , None ] ) - > T . Union [ TYPE_elementary , InterpreterObject ] :
2021-06-17 06:07:04 +08:00
if res is None :
return None
if isinstance ( res , ( int , bool , str ) ) :
return res
elif isinstance ( res , list ) :
return [ self . _holderify ( x ) for x in res ]
elif isinstance ( res , dict ) :
return { k : self . _holderify ( v ) for k , v in res . items ( ) }
elif isinstance ( res , mesonlib . HoldableObject ) :
# Always check for an exact match first.
cls = self . holder_map . get ( type ( res ) , None )
if cls is not None :
# Casts to Interpreter are required here since an assertion would
# not work for the `ast` module.
return cls ( res , T . cast ( ' Interpreter ' , self ) )
# Try the boundary types next.
for typ , cls in self . bound_holder_map . items ( ) :
if isinstance ( res , typ ) :
return cls ( res , T . cast ( ' Interpreter ' , self ) )
raise mesonlib . MesonBugException ( f ' Object { res } of type { type ( res ) . __name__ } is neither in self.holder_map nor self.bound_holder_map. ' )
elif isinstance ( res , ObjectHolder ) :
raise mesonlib . MesonBugException ( f ' Returned object { res } of type { type ( res ) . __name__ } is an object holder. ' )
elif isinstance ( res , MesonInterpreterObject ) :
return res
raise mesonlib . MesonBugException ( f ' Unknown returned object { res } of type { type ( res ) . __name__ } in the parameters. ' )
def _unholder_args ( self ,
args : T . List [ T . Union [ TYPE_var , InterpreterObject ] ] ,
kwargs : T . Dict [ str , T . Union [ TYPE_var , InterpreterObject ] ] ) - > T . Tuple [ T . List [ TYPE_var ] , TYPE_kwargs ] :
return [ _unholder ( x ) for x in args ] , { k : _unholder ( v ) for k , v in kwargs . items ( ) }
2016-11-20 04:11:20 +08:00
2020-03-13 02:36:52 +08:00
@builtinMethodNoKwargs
2021-06-17 06:07:04 +08:00
def bool_method_call ( self , obj : bool , method_name : str , posargs : T . List [ TYPE_var ] , kwargs : TYPE_kwargs ) - > T . Union [ str , int ] :
2016-11-20 04:11:20 +08:00
if method_name == ' to_string ' :
Don't use len() to test emptiness vs not emptiness
Meson has a common pattern of using 'if len(foo) == 0:' or
'if len(foo) != 0:', however, this is a common anti-pattern in python.
Instead tests for emptiness/non-emptiness should be done with a simple
'if foo:' or 'if not foo:'
Consider the following:
>>> import timeit
>>> timeit.timeit('if len([]) == 0: pass')
0.10730923599840025
>>> timeit.timeit('if not []: pass')
0.030033907998586074
>>> timeit.timeit('if len(['a', 'b', 'c', 'd']) == 0: pass')
0.1154778649979562
>>> timeit.timeit("if not ['a', 'b', 'c', 'd']: pass")
0.08259823200205574
>>> timeit.timeit('if len("") == 0: pass')
0.089759664999292
>>> timeit.timeit('if not "": pass')
0.02340641999762738
>>> timeit.timeit('if len("foo") == 0: pass')
0.08848102600313723
>>> timeit.timeit('if not "foo": pass')
0.04032287199879647
And for the one additional case of 'if len(foo.strip()) == 0', which can
be replaced with 'if not foo.isspace()'
>>> timeit.timeit('if len(" ".strip()) == 0: pass')
0.15294511600222904
>>> timeit.timeit('if " ".isspace(): pass')
0.09413968399894657
>>> timeit.timeit('if len(" abc".strip()) == 0: pass')
0.2023209120015963
>>> timeit.timeit('if " abc".isspace(): pass')
0.09571301700270851
In other words, it's always a win to not use len(), when you don't
actually want to check the length.
2017-05-02 06:11:01 +08:00
if not posargs :
2017-01-06 20:36:51 +08:00
if obj :
2016-11-20 04:11:20 +08:00
return ' true '
else :
return ' false '
elif len ( posargs ) == 2 and isinstance ( posargs [ 0 ] , str ) and isinstance ( posargs [ 1 ] , str ) :
2017-01-06 20:36:51 +08:00
if obj :
2016-11-20 04:11:20 +08:00
return posargs [ 0 ]
else :
return posargs [ 1 ]
else :
raise InterpreterException ( ' bool.to_string() must have either no arguments or exactly two string arguments that signify what values to return for true and false. ' )
elif method_name == ' to_int ' :
2017-01-06 20:36:51 +08:00
if obj :
2016-11-20 04:11:20 +08:00
return 1
else :
return 0
else :
raise InterpreterException ( ' Unknown method " %s " for a boolean. ' % method_name )
2020-03-13 02:36:52 +08:00
@builtinMethodNoKwargs
2021-06-17 06:07:04 +08:00
def int_method_call ( self , obj : int , method_name : str , posargs : T . List [ TYPE_var ] , kwargs : TYPE_kwargs ) - > T . Union [ str , bool ] :
2016-11-20 04:11:20 +08:00
if method_name == ' is_even ' :
Don't use len() to test emptiness vs not emptiness
Meson has a common pattern of using 'if len(foo) == 0:' or
'if len(foo) != 0:', however, this is a common anti-pattern in python.
Instead tests for emptiness/non-emptiness should be done with a simple
'if foo:' or 'if not foo:'
Consider the following:
>>> import timeit
>>> timeit.timeit('if len([]) == 0: pass')
0.10730923599840025
>>> timeit.timeit('if not []: pass')
0.030033907998586074
>>> timeit.timeit('if len(['a', 'b', 'c', 'd']) == 0: pass')
0.1154778649979562
>>> timeit.timeit("if not ['a', 'b', 'c', 'd']: pass")
0.08259823200205574
>>> timeit.timeit('if len("") == 0: pass')
0.089759664999292
>>> timeit.timeit('if not "": pass')
0.02340641999762738
>>> timeit.timeit('if len("foo") == 0: pass')
0.08848102600313723
>>> timeit.timeit('if not "foo": pass')
0.04032287199879647
And for the one additional case of 'if len(foo.strip()) == 0', which can
be replaced with 'if not foo.isspace()'
>>> timeit.timeit('if len(" ".strip()) == 0: pass')
0.15294511600222904
>>> timeit.timeit('if " ".isspace(): pass')
0.09413968399894657
>>> timeit.timeit('if len(" abc".strip()) == 0: pass')
0.2023209120015963
>>> timeit.timeit('if " abc".isspace(): pass')
0.09571301700270851
In other words, it's always a win to not use len(), when you don't
actually want to check the length.
2017-05-02 06:11:01 +08:00
if not posargs :
2016-11-20 04:11:20 +08:00
return obj % 2 == 0
else :
raise InterpreterException ( ' int.is_even() must have no arguments. ' )
elif method_name == ' is_odd ' :
Don't use len() to test emptiness vs not emptiness
Meson has a common pattern of using 'if len(foo) == 0:' or
'if len(foo) != 0:', however, this is a common anti-pattern in python.
Instead tests for emptiness/non-emptiness should be done with a simple
'if foo:' or 'if not foo:'
Consider the following:
>>> import timeit
>>> timeit.timeit('if len([]) == 0: pass')
0.10730923599840025
>>> timeit.timeit('if not []: pass')
0.030033907998586074
>>> timeit.timeit('if len(['a', 'b', 'c', 'd']) == 0: pass')
0.1154778649979562
>>> timeit.timeit("if not ['a', 'b', 'c', 'd']: pass")
0.08259823200205574
>>> timeit.timeit('if len("") == 0: pass')
0.089759664999292
>>> timeit.timeit('if not "": pass')
0.02340641999762738
>>> timeit.timeit('if len("foo") == 0: pass')
0.08848102600313723
>>> timeit.timeit('if not "foo": pass')
0.04032287199879647
And for the one additional case of 'if len(foo.strip()) == 0', which can
be replaced with 'if not foo.isspace()'
>>> timeit.timeit('if len(" ".strip()) == 0: pass')
0.15294511600222904
>>> timeit.timeit('if " ".isspace(): pass')
0.09413968399894657
>>> timeit.timeit('if len(" abc".strip()) == 0: pass')
0.2023209120015963
>>> timeit.timeit('if " abc".isspace(): pass')
0.09571301700270851
In other words, it's always a win to not use len(), when you don't
actually want to check the length.
2017-05-02 06:11:01 +08:00
if not posargs :
2016-11-20 04:11:20 +08:00
return obj % 2 != 0
else :
raise InterpreterException ( ' int.is_odd() must have no arguments. ' )
2017-11-23 18:13:24 +08:00
elif method_name == ' to_string ' :
if not posargs :
return str ( obj )
else :
2017-11-24 06:00:15 +08:00
raise InterpreterException ( ' int.to_string() must have no arguments. ' )
2016-11-20 04:11:20 +08:00
else :
raise InterpreterException ( ' Unknown method " %s " for an integer. ' % method_name )
2017-08-14 07:38:15 +08:00
@staticmethod
2021-06-17 06:07:04 +08:00
def _get_one_string_posarg ( posargs : T . List [ TYPE_var ] , method_name : str ) - > str :
2017-08-14 07:38:15 +08:00
if len ( posargs ) > 1 :
2021-07-05 07:18:28 +08:00
raise InterpreterException ( f ' { method_name } () must have zero or one arguments ' )
2017-08-14 07:38:15 +08:00
elif len ( posargs ) == 1 :
s = posargs [ 0 ]
if not isinstance ( s , str ) :
2021-07-05 07:18:28 +08:00
raise InterpreterException ( f ' { method_name } () argument must be a string ' )
2017-08-14 07:38:15 +08:00
return s
return None
2020-03-13 02:36:52 +08:00
@builtinMethodNoKwargs
2021-06-17 06:07:04 +08:00
def string_method_call ( self , obj : str , method_name : str , posargs : T . List [ TYPE_var ] , kwargs : TYPE_kwargs ) - > T . Union [ str , int , bool , T . List [ str ] ] :
2016-11-20 04:11:20 +08:00
if method_name == ' strip ' :
2019-12-09 02:22:14 +08:00
s1 = self . _get_one_string_posarg ( posargs , ' strip ' )
if s1 is not None :
return obj . strip ( s1 )
2016-11-20 04:11:20 +08:00
return obj . strip ( )
elif method_name == ' format ' :
2019-12-09 02:22:14 +08:00
return self . format_string ( obj , posargs )
2016-11-20 04:11:20 +08:00
elif method_name == ' to_upper ' :
return obj . upper ( )
elif method_name == ' to_lower ' :
return obj . lower ( )
elif method_name == ' underscorify ' :
return re . sub ( r ' [^a-zA-Z0-9] ' , ' _ ' , obj )
elif method_name == ' split ' :
2019-12-09 02:22:14 +08:00
s2 = self . _get_one_string_posarg ( posargs , ' split ' )
if s2 is not None :
return obj . split ( s2 )
2017-08-14 07:38:15 +08:00
return obj . split ( )
2016-11-20 04:11:20 +08:00
elif method_name == ' startswith ' or method_name == ' contains ' or method_name == ' endswith ' :
2019-12-09 02:22:14 +08:00
s3 = posargs [ 0 ]
if not isinstance ( s3 , str ) :
2016-11-20 04:11:20 +08:00
raise InterpreterException ( ' Argument must be a string. ' )
if method_name == ' startswith ' :
2019-12-09 02:22:14 +08:00
return obj . startswith ( s3 )
2016-11-20 04:11:20 +08:00
elif method_name == ' contains ' :
2019-12-09 02:22:14 +08:00
return obj . find ( s3 ) > = 0
return obj . endswith ( s3 )
2016-11-20 04:11:20 +08:00
elif method_name == ' to_int ' :
try :
return int ( obj )
except Exception :
2021-03-05 06:16:11 +08:00
raise InterpreterException ( f ' String { obj !r} cannot be converted to int ' )
2016-11-20 04:11:20 +08:00
elif method_name == ' join ' :
if len ( posargs ) != 1 :
raise InterpreterException ( ' Join() takes exactly one argument. ' )
strlist = posargs [ 0 ]
check_stringlist ( strlist )
2019-12-09 02:22:14 +08:00
assert isinstance ( strlist , list ) # Required for mypy
2016-11-20 04:11:20 +08:00
return obj . join ( strlist )
elif method_name == ' version_compare ' :
if len ( posargs ) != 1 :
raise InterpreterException ( ' Version_compare() takes exactly one argument. ' )
cmpr = posargs [ 0 ]
if not isinstance ( cmpr , str ) :
raise InterpreterException ( ' Version_compare() argument must be a string. ' )
2020-08-15 05:41:18 +08:00
if isinstance ( obj , MesonVersionString ) :
self . tmp_meson_version = cmpr
2016-11-20 04:11:20 +08:00
return mesonlib . version_compare ( obj , cmpr )
2020-07-09 18:34:34 +08:00
elif method_name == ' substring ' :
if len ( posargs ) > 2 :
raise InterpreterException ( ' substring() takes maximum two arguments. ' )
start = 0
end = len ( obj )
if len ( posargs ) > 0 :
if not isinstance ( posargs [ 0 ] , int ) :
raise InterpreterException ( ' substring() argument must be an int ' )
start = posargs [ 0 ]
if len ( posargs ) > 1 :
if not isinstance ( posargs [ 1 ] , int ) :
raise InterpreterException ( ' substring() argument must be an int ' )
end = posargs [ 1 ]
return obj [ start : end ]
2021-03-08 12:59:21 +08:00
elif method_name == ' replace ' :
FeatureNew . single_use ( ' str.replace ' , ' 0.58.0 ' , self . subproject )
if len ( posargs ) != 2 :
raise InterpreterException ( ' replace() takes exactly two arguments. ' )
if not isinstance ( posargs [ 0 ] , str ) or not isinstance ( posargs [ 1 ] , str ) :
raise InterpreterException ( ' replace() requires that both arguments be strings ' )
return obj . replace ( posargs [ 0 ] , posargs [ 1 ] )
2016-11-20 04:11:20 +08:00
raise InterpreterException ( ' Unknown method " %s " for a string. ' % method_name )
2021-06-17 06:07:04 +08:00
def format_string ( self , templ : str , args : T . List [ TYPE_var ] ) - > str :
2019-04-21 05:02:03 +08:00
arg_strings = [ ]
for arg in args :
2019-12-09 02:22:14 +08:00
if isinstance ( arg , mparser . BaseNode ) :
arg = self . evaluate_statement ( arg )
2019-04-21 05:02:03 +08:00
if isinstance ( arg , bool ) : # Python boolean is upper case.
arg = str ( arg ) . lower ( )
arg_strings . append ( str ( arg ) )
2020-08-29 00:01:22 +08:00
def arg_replace ( match : T . Match [ str ] ) - > str :
2019-04-21 05:02:03 +08:00
idx = int ( match . group ( 1 ) )
if idx > = len ( arg_strings ) :
2021-03-05 06:16:11 +08:00
raise InterpreterException ( f ' Format placeholder @ { idx } @ out of range. ' )
2019-04-21 05:02:03 +08:00
return arg_strings [ idx ]
return re . sub ( r ' @( \ d+)@ ' , arg_replace , templ )
2019-12-09 02:22:14 +08:00
def unknown_function_called ( self , func_name : str ) - > None :
2017-09-23 01:51:30 +08:00
raise InvalidCode ( ' Unknown function " %s " . ' % func_name )
2016-11-20 02:18:30 +08:00
2020-03-13 02:36:52 +08:00
@builtinMethodNoKwargs
2021-06-17 06:07:04 +08:00
def array_method_call ( self ,
obj : T . List [ T . Union [ TYPE_elementary , InterpreterObject ] ] ,
method_name : str ,
posargs : T . List [ TYPE_var ] ,
kwargs : TYPE_kwargs ) - > T . Union [ TYPE_var , InterpreterObject ] :
2016-11-20 04:11:20 +08:00
if method_name == ' contains ' :
2021-07-31 23:51:05 +08:00
def check_contains ( el : T . List [ TYPE_var ] ) - > bool :
2019-12-09 02:22:14 +08:00
if len ( posargs ) != 1 :
raise InterpreterException ( ' Contains method takes exactly one argument. ' )
item = posargs [ 0 ]
for element in el :
if isinstance ( element , list ) :
found = check_contains ( element )
if found :
return True
if element == item :
return True
return False
2021-07-31 23:51:05 +08:00
return check_contains ( [ _unholder ( x ) for x in obj ] )
2016-11-20 04:11:20 +08:00
elif method_name == ' length ' :
return len ( obj )
elif method_name == ' get ' :
2017-09-23 01:51:30 +08:00
index = posargs [ 0 ]
2017-01-27 02:12:50 +08:00
fallback = None
2017-09-23 01:51:30 +08:00
if len ( posargs ) == 2 :
2021-06-20 06:02:25 +08:00
fallback = self . _holderify ( posargs [ 1 ] )
2017-09-23 01:51:30 +08:00
elif len ( posargs ) > 2 :
2017-01-27 02:12:50 +08:00
m = ' Array method \' get() \' only takes two arguments: the ' \
' index and an optional fallback value if the index is ' \
' out of range. '
raise InvalidArguments ( m )
2016-11-20 04:11:20 +08:00
if not isinstance ( index , int ) :
raise InvalidArguments ( ' Array index must be a number. ' )
if index < - len ( obj ) or index > = len ( obj ) :
2017-01-27 02:12:50 +08:00
if fallback is None :
m = ' Array index {!r} is out of bounds for array of size {!r} . '
raise InvalidArguments ( m . format ( index , len ( obj ) ) )
2019-12-09 02:22:14 +08:00
if isinstance ( fallback , mparser . BaseNode ) :
return self . evaluate_statement ( fallback )
2017-01-27 02:12:50 +08:00
return fallback
2020-09-02 01:36:21 +08:00
return obj [ index ]
2021-07-05 07:18:28 +08:00
raise InterpreterException ( f ' Arrays do not have a method called { method_name !r} . ' )
2016-11-20 04:11:20 +08:00
2020-03-13 02:36:52 +08:00
@builtinMethodNoKwargs
2021-06-17 06:07:04 +08:00
def dict_method_call ( self ,
obj : T . Dict [ str , T . Union [ TYPE_elementary , InterpreterObject ] ] ,
method_name : str ,
posargs : T . List [ TYPE_var ] ,
kwargs : TYPE_kwargs ) - > T . Union [ TYPE_var , InterpreterObject ] :
2018-04-30 03:58:41 +08:00
if method_name in ( ' has_key ' , ' get ' ) :
if method_name == ' has_key ' :
if len ( posargs ) != 1 :
raise InterpreterException ( ' has_key() takes exactly one argument. ' )
else :
if len ( posargs ) not in ( 1 , 2 ) :
raise InterpreterException ( ' get() takes one or two arguments. ' )
key = posargs [ 0 ]
if not isinstance ( key , ( str ) ) :
raise InvalidArguments ( ' Dictionary key must be a string. ' )
has_key = key in obj
if method_name == ' has_key ' :
return has_key
if has_key :
return obj [ key ]
if len ( posargs ) == 2 :
2021-06-20 06:02:25 +08:00
fallback = self . _holderify ( posargs [ 1 ] )
2019-12-09 02:22:14 +08:00
if isinstance ( fallback , mparser . BaseNode ) :
return self . evaluate_statement ( fallback )
return fallback
2018-04-30 03:58:41 +08:00
2021-03-05 06:16:11 +08:00
raise InterpreterException ( f ' Key { key !r} is not in the dictionary. ' )
2018-04-30 03:58:41 +08:00
if method_name == ' keys ' :
if len ( posargs ) != 0 :
raise InterpreterException ( ' keys() takes no arguments. ' )
2020-10-26 18:14:54 +08:00
return sorted ( obj . keys ( ) )
2018-04-30 03:58:41 +08:00
raise InterpreterException ( ' Dictionaries do not have a method called " %s " . ' % method_name )
2020-08-28 23:58:54 +08:00
def reduce_arguments (
self ,
args : mparser . ArgumentNode ,
key_resolver : T . Callable [ [ mparser . BaseNode ] , str ] = default_resolve_key ,
duplicate_key_error : T . Optional [ str ] = None ,
2021-06-17 06:07:04 +08:00
) - > T . Tuple [
T . List [ T . Union [ TYPE_var , InterpreterObject ] ] ,
T . Dict [ str , T . Union [ TYPE_var , InterpreterObject ] ]
] :
2016-11-20 02:18:30 +08:00
assert ( isinstance ( args , mparser . ArgumentNode ) )
if args . incorrect_order ( ) :
raise InvalidArguments ( ' All keyword arguments must be after positional arguments. ' )
2017-01-24 02:00:00 +08:00
self . argument_depth + = 1
2021-06-17 06:07:04 +08:00
reduced_pos : T . List [ T . Union [ TYPE_var , InterpreterObject ] ] = [ self . evaluate_statement ( arg ) for arg in args . arguments ]
reduced_kw : T . Dict [ str , T . Union [ TYPE_var , InterpreterObject ] ] = { }
2019-12-09 02:22:14 +08:00
for key , val in args . kwargs . items ( ) :
2020-08-28 23:58:54 +08:00
reduced_key = key_resolver ( key )
2021-06-17 06:07:04 +08:00
assert isinstance ( val , mparser . BaseNode )
reduced_val = self . evaluate_statement ( val )
2020-08-28 23:58:54 +08:00
if duplicate_key_error and reduced_key in reduced_kw :
raise InvalidArguments ( duplicate_key_error . format ( reduced_key ) )
2019-12-09 02:22:14 +08:00
reduced_kw [ reduced_key ] = reduced_val
2017-01-24 02:00:00 +08:00
self . argument_depth - = 1
2018-12-03 04:40:43 +08:00
final_kw = self . expand_default_kwargs ( reduced_kw )
return reduced_pos , final_kw
2021-06-17 06:07:04 +08:00
def expand_default_kwargs ( self , kwargs : T . Dict [ str , T . Union [ TYPE_var , InterpreterObject ] ] ) - > T . Dict [ str , T . Union [ TYPE_var , InterpreterObject ] ] :
2018-12-03 04:40:43 +08:00
if ' kwargs ' not in kwargs :
return kwargs
to_expand = kwargs . pop ( ' kwargs ' )
if not isinstance ( to_expand , dict ) :
2018-12-07 05:45:35 +08:00
raise InterpreterException ( ' Value of " kwargs " must be dictionary. ' )
if ' kwargs ' in to_expand :
raise InterpreterException ( ' Kwargs argument must not contain a " kwargs " entry. Points for thinking meta, though. :P ' )
2018-12-03 04:40:43 +08:00
for k , v in to_expand . items ( ) :
if k in kwargs :
2021-03-05 06:16:11 +08:00
raise InterpreterException ( f ' Entry " { k } " defined both as a keyword argument and in a " kwarg " entry. ' )
2018-12-03 04:40:43 +08:00
kwargs [ k ] = v
return kwargs
2016-11-20 02:18:30 +08:00
2019-12-09 02:22:14 +08:00
def assignment ( self , node : mparser . AssignmentNode ) - > None :
2016-11-20 02:18:30 +08:00
assert ( isinstance ( node , mparser . AssignmentNode ) )
2017-01-24 02:00:00 +08:00
if self . argument_depth != 0 :
raise InvalidArguments ( ''' Tried to assign values inside an argument list.
To specify a keyword argument , use : instead of = . ''' )
2016-11-20 02:18:30 +08:00
var_name = node . var_name
if not isinstance ( var_name , str ) :
raise InvalidArguments ( ' Tried to assign value to a non-variable. ' )
value = self . evaluate_statement ( node . value )
if not self . is_assignable ( value ) :
2021-06-20 00:02:19 +08:00
raise InvalidCode ( f ' Tried to assign the invalid value " { value } " of type { type ( value ) . __name__ } to variable. ' )
2016-11-20 02:18:30 +08:00
# For mutable objects we need to make a copy on assignment
if isinstance ( value , MutableInterpreterObject ) :
value = copy . deepcopy ( value )
self . set_variable ( var_name , value )
2017-01-24 02:00:00 +08:00
return None
2016-11-20 02:18:30 +08:00
2021-06-20 00:02:19 +08:00
def set_variable ( self , varname : str , variable : T . Union [ TYPE_var , InterpreterObject ] , * , holderify : bool = False ) - > None :
2016-11-20 02:18:30 +08:00
if variable is None :
raise InvalidCode ( ' Can not assign None to variable. ' )
2021-06-20 00:02:19 +08:00
if holderify :
variable = self . _holderify ( variable )
else :
# Ensure that we are never storing a HoldableObject
def check ( x : T . Union [ TYPE_var , InterpreterObject ] ) - > None :
if isinstance ( x , mesonlib . HoldableObject ) :
raise mesonlib . MesonBugException ( f ' set_variable in InterpreterBase called with a HoldableObject { x } of type { type ( x ) . __name__ } ' )
elif isinstance ( x , list ) :
for y in x :
check ( y )
elif isinstance ( x , dict ) :
for v in x . values ( ) :
check ( v )
check ( variable )
2016-11-20 02:18:30 +08:00
if not isinstance ( varname , str ) :
raise InvalidCode ( ' First argument to set_variable must be a string. ' )
if not self . is_assignable ( variable ) :
2021-06-20 00:02:19 +08:00
raise InvalidCode ( f ' Assigned value " { variable } " of type { type ( variable ) . __name__ } is not an assignable type. ' )
2016-11-20 02:18:30 +08:00
if re . match ( ' [_a-zA-Z][_0-9a-zA-Z]*$ ' , varname ) is None :
raise InvalidCode ( ' Invalid variable name: ' + varname )
if varname in self . builtin :
raise InvalidCode ( ' Tried to overwrite internal variable " %s " ' % varname )
self . variables [ varname ] = variable
2021-06-17 06:07:04 +08:00
def get_variable ( self , varname : str ) - > T . Union [ TYPE_var , InterpreterObject ] :
2016-11-20 02:18:30 +08:00
if varname in self . builtin :
return self . builtin [ varname ]
if varname in self . variables :
return self . variables [ varname ]
raise InvalidCode ( ' Unknown variable " %s " . ' % varname )
2020-01-09 00:44:50 +08:00
def is_assignable ( self , value : T . Any ) - > bool :
2021-06-20 00:02:19 +08:00
return isinstance ( value , ( InterpreterObject , str , int , list , dict ) )
2016-11-20 02:18:30 +08:00
2021-06-17 06:07:04 +08:00
def validate_extraction ( self , buildtarget : mesonlib . HoldableObject ) - > None :
2019-12-09 02:22:14 +08:00
raise InterpreterException ( ' validate_extraction is not implemented in this context (please file a bug) ' )