1#     Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
2#
3#     Part of "Nuitka", an optimizing Python compiler that is compatible and
4#     integrates with CPython, but also works on its own.
5#
6#     Licensed under the Apache License, Version 2.0 (the "License");
7#     you may not use this file except in compliance with the License.
8#     You may obtain a copy of the License at
9#
10#        http://www.apache.org/licenses/LICENSE-2.0
11#
12#     Unless required by applicable law or agreed to in writing, software
13#     distributed under the License is distributed on an "AS IS" BASIS,
14#     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15#     See the License for the specific language governing permissions and
16#     limitations under the License.
17#
18""" Built-in iterator nodes.
19
20These play a role in for loops, and in unpacking. They can something be
21predicted to succeed or fail, in which case, code can become less complex.
22
23The length of things is an important optimization issue for these to be
24good.
25"""
26
27from nuitka.specs import BuiltinParameterSpecs
28
29from .ExpressionBases import ExpressionBuiltinSingleArgBase
30from .shapes.BuiltinTypeShapes import tshape_int_or_long
31
32
33class ExpressionBuiltinLen(ExpressionBuiltinSingleArgBase):
34    kind = "EXPRESSION_BUILTIN_LEN"
35
36    builtin_spec = BuiltinParameterSpecs.builtin_len_spec
37
38    def getIntegerValue(self):
39        value = self.subnode_value
40
41        if value.hasShapeSlotLen():
42            return value.getIterationLength()
43        else:
44            return None
45
46    def computeExpression(self, trace_collection):
47        return self.subnode_value.computeExpressionLen(
48            len_node=self, trace_collection=trace_collection
49        )
50
51    @staticmethod
52    def getTypeShape():
53        # Length could be really big, using a long.
54        return tshape_int_or_long
55
56    def mayRaiseException(self, exception_type):
57        value = self.subnode_value
58
59        if value.mayRaiseException(exception_type):
60            return True
61
62        return not value.getTypeShape().hasShapeSlotLen()
63