#     Copyright 2015, Kay Hayen, mailto:kay.hayen@gmail.com
#
#     Part of "Nuitka", an optimizing Python compiler that is compatible and
#     integrates with CPython, but also works on its own.
#
#     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.
#
""" Call node

Function calls and generally calling expressions are the same thing. This is
very important, because it allows to predict most things, and avoid expensive
operations like parameter parsing at run time.

There will be a method "computeExpressionCall" to aid predicting them in other
nodes.
"""

from .NodeBases import ExpressionChildrenHavingBase
from .NodeMakingHelpers import wrapExpressionWithSideEffects


class ExpressionCall(ExpressionChildrenHavingBase):
    kind = "EXPRESSION_CALL"

    named_children = (
        "called", "args", "kw"
    )

    def __init__(self, called, args, kw, source_ref):
        assert called.isExpression()
        assert args.isExpression()
        assert kw.isExpression()

        ExpressionChildrenHavingBase.__init__(
            self,
            values     = {
                "called" : called,
                "args"   : args,
                "kw"     : kw,
            },
            source_ref = source_ref
        )

    getCalled = ExpressionChildrenHavingBase.childGetter("called")
    getCallArgs = ExpressionChildrenHavingBase.childGetter("args")
    getCallKw = ExpressionChildrenHavingBase.childGetter("kw")

    def isExpressionCall(self):
        return True

    def computeExpression(self, constraint_collection):
        called = self.getCalled()

        if called.willRaiseException(BaseException):
            return called, "new_raise", "Called expression raises exception"

        args = self.getCallArgs()

        if args.willRaiseException(BaseException):
            result = wrapExpressionWithSideEffects(
                side_effects = (called,),
                old_node     = self,
                new_node     = args
            )

            return result, "new_raise", "Call arguments raise exception"

        kw = self.getCallKw()

        if kw.willRaiseException(BaseException):
            result = wrapExpressionWithSideEffects(
                side_effects = (called, args),
                old_node     = self,
                new_node     = kw
            )

            return result, "new_raise", "Call keyword arguments raise exception"

        # Any code could be run, note that. TODO: Move this down into the
        # specific handlers.
        constraint_collection.onControlFlowEscape(self)

        return called.computeExpressionCall(
            call_node             = self,
            constraint_collection = constraint_collection
        )

    def extractPreCallSideEffects(self):
        args = self.getCallArgs()
        kw = self.getCallKw()

        return args.extractSideEffects() + kw.extractSideEffects()


class ExpressionCallNoKeywords(ExpressionChildrenHavingBase):
    kind = "EXPRESSION_CALL_NO_KEYWORDS"

    named_children = (
        "called",
        "args"
    )

    def __init__(self, called, args, source_ref):
        assert called.isExpression()
        assert args.isExpression()

        ExpressionChildrenHavingBase.__init__(
            self,
            values     = {
                "called" : called,
                "args"   : args
            },
            source_ref = source_ref
        )

    getCalled = ExpressionChildrenHavingBase.childGetter("called")
    getCallArgs = ExpressionChildrenHavingBase.childGetter("args")

    @staticmethod
    def getCallKw():
        return None

    def isExpressionCall(self):
        return True

    def computeExpression(self, constraint_collection):
        called = self.getCalled()

        if called.willRaiseException(BaseException):
            return called, "new_raise", "Called expression raises exception"

        args = self.getCallArgs()

        if args.willRaiseException(BaseException):
            result = wrapExpressionWithSideEffects(
                side_effects = (called,),
                old_node     = self,
                new_node     = args
            )

            return result, "new_raise", "Call arguments raise exception"

        # Any code could be run, note that. TODO: Move this down into the
        # specific handlers.
        constraint_collection.onControlFlowEscape(self)

        return called.computeExpressionCall(
            call_node             = self,
            constraint_collection = constraint_collection
        )

    def extractPreCallSideEffects(self):
        args = self.getCallArgs()

        return args.extractSideEffects()


class ExpressionCallKeywordsOnly(ExpressionChildrenHavingBase):
    kind = "EXPRESSION_CALL_KEYWORDS_ONLY"

    named_children = (
        "called",
        "kw"
    )

    def __init__(self, called, kw, source_ref):
        assert called.isExpression()
        assert kw.isExpression()

        ExpressionChildrenHavingBase.__init__(
            self,
            values     = {
                "called" : called,
                "kw"     : kw
            },
            source_ref = source_ref
        )

    getCalled = ExpressionChildrenHavingBase.childGetter("called")
    getCallKw = ExpressionChildrenHavingBase.childGetter("kw")

    @staticmethod
    def getCallArgs():
        return None

    def isExpressionCall(self):
        return True

    def computeExpression(self, constraint_collection):
        called = self.getCalled()

        if called.willRaiseException(BaseException):
            return called, "new_raise", "Called expression raises exception"

        kw = self.getCallKw()

        if kw.willRaiseException(BaseException):
            result = wrapExpressionWithSideEffects(
                side_effects = (called,),
                old_node     = self,
                new_node     = kw
            )

            return result, "new_raise", "Call keyword arguments raise exception"

        # Any code could be run, note that. TODO: Move this down into the
        # specific handlers.
        constraint_collection.onControlFlowEscape(self)

        return called.computeExpressionCall(
            call_node             = self,
            constraint_collection = constraint_collection
        )

    def extractPreCallSideEffects(self):
        kw = self.getCallKw()

        return kw.extractSideEffects()


class ExpressionCallEmpty(ExpressionChildrenHavingBase):
    kind = "EXPRESSION_CALL_EMPTY"

    named_children = (
        "called",
    )

    def __init__(self, called, source_ref):
        assert called.isExpression()

        ExpressionChildrenHavingBase.__init__(
            self,
            values     = {
                "called" : called,
            },
            source_ref = source_ref
        )

    getCalled = ExpressionChildrenHavingBase.childGetter("called")

    @staticmethod
    def getCallKw():
        return None

    @staticmethod
    def getCallArgs():
        return None

    def isExpressionCall(self):
        return True

    def computeExpression(self, constraint_collection):
        called = self.getCalled()

        if called.willRaiseException(BaseException):
            return called, "new_raise", "Called expression raises exception"

        # Any code could be run, note that. TODO: Move this down into the
        # specific handlers.
        constraint_collection.onControlFlowEscape(self)

        return called.computeExpressionCall(
            call_node             = self,
            constraint_collection = constraint_collection
        )

    @staticmethod
    def extractPreCallSideEffects():
        return ()


def makeExpressionCall(called, args, kw, source_ref):
    """ Make the most simple call node possible.

        By avoiding the more complex classes, we can achieve that there is
        less work to do for analysis.
    """
    has_kw = not kw.isExpressionConstantRef() or kw.getConstant() != {}
    has_args = not args.isExpressionConstantRef() or args.getConstant() != ()

    if has_kw:
        if has_args:
            return ExpressionCall(called, args, kw, source_ref)
        else:
            return ExpressionCallKeywordsOnly(called, kw, source_ref)
    else:
        if has_args:
            return ExpressionCallNoKeywords(called, args, source_ref)
        else:
            return ExpressionCallEmpty(called, source_ref)
