# Part of the A-A-P recipe executive: Handling of scopes

# Copyright (C) 2002-2003 Stichting NLnet Labs
# Permission to copy and use this file is specified in the file COPYING.
# If this file is missing you can find it here: http://www.a-a-p.org/COPYING

from UserDict import UserDict

from Message import *
from Error import *
from DoConf import init_conf_dict

#
# These classes are used to be able to access different scopes also in the
# Python code of a recipe.  E.g., "_recipe.var" uses "_recipe" as if it was a
# Python module, but it's actually a RecipeDict object.
#
# The three different classes here are used for:
# RecipeDict:     Toplevel recipe and snapshot of it.  Also used for a user
#                 scope.  No handling of scopes other than the scope itself.
# NoScopeDict:    Used for other recipes and build command blocks.  Implements
#                 the "_no" scope: First looks in the current scope, then
#                 "_up".
# CallstackDict:  Used for the "_up" scope: search in a stack of surrounding
#                 scopes.
#

#
# Note: __setattr__() and __getattr__() are overruled, so that these classes
# can be used as if they were modules.  This is dangerous!
# Access to "self.var" will not work directly.
# Must use 'self.__dict__["var"]' instead.
#

class RecipeDict(UserDict):
    """This simulates a dictionary.  What is missing from UserDict is the
       methods to get/set attributes.  These are required for using the class
       in place of a module."""
    def __init__(self, init_dict = None):
        UserDict.__init__(self)
        if init_dict:
            # Initialize the recdict with a copy of information in "init_dict".
            # Since all variables should be strings a shallow copy is
            # sufficient.
            self.data = init_dict.copy()

    def __getattr__(self, key):
        return self.data[key]

    def __setattr__(self, key, value):
        if key == "data":
            # UserDict.__init__() will do "self.data = {}", catch that here.
            self.__dict__[key] = value
        else:
            self.data[key] = value

    def __delattr__(self, key):
        del self.data[key]

    def __delitem(self, key):
        del self.data[key]

    def __nonzero__(self):
        return len(self.data) > 0


class NoScopeDict:
    """
    Simulated dictionary used for the "_no" scope.
    This looks:
           1. in a dictionary for the current scope
           2. in the "_up" scope; uses a CallstackDict object
    The "_up" scope is in 'data["_up"]'.
    Inspired by UserDict, but not everything is implemented.
    """

    def __init__(self):
        # The "read_from_callstack" dictionary is used to remember which
        # variables were read without a scope specified.
        # TODO: this has been disabled, because it gives too many warnings,
        # e.g.  when we don't know if CFLAGS was set in the local scope or not.
        # self.__dict__["read_from_callstack"] = {}

        # Create the self.data dictionary, containing the actual items.
        self.__dict__["data"] = {}

    def __getitem__(self, key):
        return self.__getattr__(key)

    def __getattr__(self, key):
        # 1: local scope
        if self.data.has_key(key):
            return self.data[key]

        # Remember we read the variable from a non-local scope.
        # self.read_from_callstack[key] = 1

        # 2: _up scope (callstack)
        if self.data.has_key("_up") and self.data["_up"].has_key(key):
            return self.data["_up"][key]

        # Generate an error as if reading from the local scope.
        return self.data[key]

    def __setitem__(self, key, value):
        self.__setattr__(key, value)

    def __setattr__(self, key, value):
        # if self.read_from_callstack.get(key):
        #    raise WriteAfterRead, _("Setting local variable after reading from other scope: %s") % str(key)
        self.data[key] = value

    def has_key(self, key):
        return (self.data.has_key(key)
               or (self.data.has_key("_up") and self.data["_up"].has_key(key)))

    def get(self, key, f = None):
        if self.data.has_key(key):
            return self.data[key]
        if self.data.has_key("_up") and self.data["_up"].has_key(key):
            return self.data["_up"][key]
        return f

    def keys(self):
        l = self.data.keys()
        if self.data.has_key("_up"):
            l.extend(self.data["_up"].keys())

        # Remove duplicates: two scopes can hold the same variable but we will
        # only get it from the lowest one.
        # Go from end to start, so that the order is kept as-is.
        i = len(l) - 1
        while i > 0:
            if l[i] in l[:i]:
                del l[i]
            i = i - 1

        return l

    def __delattr(self, key):
        # can only delete from the current scope, not "_up".
        del self.data[key]

    def __delitem__(self, key):
        # can only delete from the current scope, not "_up".
        del self.data[key]

    def __str__(self):
        s = str(self.data)
        if self.data.has_key("_up"):
            s = s + "; _up stack: " + str(self.data["_up"])
        return s

    def copy(self):
        c = NoScopeDict()
        # c.__dict__["read_from_callstack"] = self.read_from_callstack.copy()
        c.__dict__["data"] = self.data.copy()
        return c

    def __len__(self):
        return len(self.keys())

    def __nonzero__(self):
        return self.__len__() > 0

    def __contains__(self, key):
        return (self.data.__contains__(key)
                or (self.data.has_key("_up")
                    and self.data["_up"].__contains__(key)))

    def items(self):
        # Can't use map() here for Python 1.5
        l = self.keys()
        for i in range(len(l)):
            l[i] = (l[i], self.__getattr__(l[i]))
        return l

    def values(self):
        # Can't use map() here for Python 1.5
        l = self.keys()
        for i in range(len(l)):
            l[i] = self.__getattr__(l[i])
        return l

    # not implemented yet:
    # __repr__()
    # __cmp__()
    # clear()
    # iteritems()
    # iterkeys()
    # itervalues()
    # __iter__()
    # update()
    # setdefault()
    # popitem()


class CallstackDict:
    """Simulated dictionary used find variables in the "_up" scope: stack of
       executing command blocks or recipes.
       Inspired by UserDict, but not everything is implemented.
       The "stack" item holds a list of dictionaries to search for an item.
       Order is important: first entry is searched first."""
    def __init__(self, stack):
        self.__dict__["stack"] = stack

    def __getitem__(self, key):
        return self.__getattr__(key)

    def __getattr__(self, key):
        for d in self.stack:
            if d.has_key(key):
                return d[key]
        raise AttributeError, _("Variable not found in _up scope: %s") % str(key)

    def __setattr__(self, key, value):
        for d in self.stack:
            if d.has_key(key):
                d[key] = value
                return
        raise AttributeError, _("Variable not found in _up scope: %s") % str(key)

    def __setitem__(self, key, value):
        for d in self.stack:
            if d.has_key(key):
                d[key] = value
                return
        raise AttributeError, _("Variable not found in _up scope: %s") % str(key)

    def __delitem__(self, key):
        raise AttributeError, _("Cannot delete variable from _up scope: %s") % str(key)

    def __str__(self):
        return self.stack.__str__()

    def copy(self):
        return CallstackDict(self.stack.copy())

    def __len__(self):
        return len(self.keys())

    def __nonzero__(self):
        return self.__len__() > 0

    def has_key(self, key):
        for d in self.stack:
            if d.has_key(key):
                return 1
        return 0

    def __contains__(self, key):
        for d in self.stack:
            if d.__contains__(key):
                return 1
        return 0

    def get(self, key, f = None):
        for d in self.stack:
            if d.has_key(key):
                return d[key]
        return f

    def keys(self):
        l = []
        for d in self.stack:
            l.extend(d.keys())

        # Remove duplicates: a variable may appear in several scopes but is
        # used only once.
        # Go from end to start, so that the order is kept as-is.
        i = len(l) - 1
        while i > 0:
            if l[i] in l[:i]:
                del l[i]
            i = i - 1

        return l

    def items(self):
        # Can't use map() here for Python 1.5
        l = self.keys()
        for i in range(len(l)):
            l[i] = (l[i], self.__getattr__(l[i]))
        return l

    def values(self):
        # Can't use map() here for Python 1.5
        l = self.keys()
        for i in range(len(l)):
            l[i] = self.__getattr__(l[i])
        return l

    # not implemented yet:
    # __repr__()
    # __cmp__()
    # clear()
    # iteritems()
    # iterkeys()
    # itervalues()
    # __iter__()
    # update()
    # setdefault()
    # popitem()


def create_topscope(recipe_name):
    """
    Create a toplevel scope.  To be used for the real toplevel recipe and
    for ":execute" and ":child {nopass}", these simulate a new toplevel.
    """
    # "_start" and "_default" will be set later.
    # There is no "_stack" or "_parent" scope, since this is the toplevel.

    # Set the scope names as keys in the recdict, they will be used like Python
    # modules.
    topscope = RecipeDict()
    recdict = topscope.data
    recdict["_top"] = topscope
    recdict["_recipe"] = topscope
    recdict["_dirstack"] = []
    recdict["_prevdir"] = None

    # The "_arg" scope holds variables set on the command line.
    recdict["_arg"] = RecipeDict()

    # The "_conf" scope is used for collecting of configuration results that
    # are used in recipes.  It is a RecipeDict with some extra items.
    confdict = RecipeDict()
    recdict["_conf"] = confdict
    init_conf_dict(confdict)

    # List of user scope names, initially empty.
    topscope.__dict__["user_scope_names"] = []

    # Recipe name for this scope.  No line number.
    topscope["recipe_name"] = recipe_name
    topscope["recipe_lnum"] = 0

    # No need to use a NoScopeDict() for "_no", since "_stack" and "_tree" are
    # empty.
    recdict["_no"] = topscope

    # The toplevel recipe is the top of the recipe tree.
    recdict["_tree"] = CallstackDict([ recdict ])

    # The "_up" scope only contains "_conf"
    recdict["_up"] = CallstackDict([ confdict ])

    # The "_buildrule_targets" entry is used for the target nodes from build
    # rules.  These are used when no target was explicitly specified.
    recdict["_buildrule_targets"] = []

    return topscope


def find_recdict(recdict, name):
    """
    Search for variable "name" in the current scope and up the stack.
    Return the recdict in which it is defined.  None if it is not defined.
    """
    nord = recdict.get("_no")
    if not nord:
        # simple recdict, can't use scopes
        if recdict.has_key(name):
            return recdict
        return None

    # use the _no scope
    if nord.data.has_key(name):
        return nord.data
    if nord.data.has_key("_up"):
        for rd in nord.data["_up"].stack:
            if rd.has_key(name):
                return rd
    return None


def get_build_recdict(recdict, buildrecdict, rpstack = None,
                    keep_current_scope = 0, recipe_name = None, xscope = None):
    """
    Create a recdict for a recipe or build commands.  Setup the scopes.
    When used for a ":child" or ":execute":
        "buildrecdict" is None
        "recipe_name" is the recipe name.
    When used for a block of build commands:
        "buildrecdict" is the recdict of the recipe where the build commands
        were defined
        "keep_current_scope" is non-zero for rules and actions: the scope from
        "recdict" is used for most variables (e.g., $CFLAGS) and "buildrecdict"
        for specific things (e.g. $_recipe.var).
        "rpstack" holds the position where the build commands were defined
        "recipe_name" is None.
        "xscope" is a list of names of extra scopes, to be used after the local
        scope, before any other scopes.
        Add the items from "buildrecdict": the recdict of the recipe where the
        action was defined.
    """
    # Create a new scope, to be used for the "_no" scope.
    noscopedict = NoScopeDict()
    new_recdict = noscopedict.data
    new_recdict["_no"] = noscopedict
    new_recdict["_top"] = recdict["_top"]
    new_recdict["_arg"] = recdict["_arg"]
    new_recdict["_default"] = recdict["_default"]
    new_recdict["_start"] = recdict["_start"]
    new_recdict["_conf"] = recdict["_conf"]
    new_recdict["_dirstack"] = []
    new_recdict["_prevdir"] = None

    # Add the user scopes.
    for n in recdict["_top"].user_scope_names:
        new_recdict[n] = recdict[n]

    if buildrecdict:
        # ":do", ":update", etc.: nested command block.
        new_recdict["_recipe"] = buildrecdict["_recipe"]
        if keep_current_scope:
            # An action first uses the recipe tree from where it was invoked
            # from, then the tree where it was defined.
            new_recdict["_tree"] = CallstackDict(recdict["_tree"].stack 
                                                 + buildrecdict["_tree"].stack)
        else:
            # For a dependency the tree of the invoker is not used.
            new_recdict["_tree"] = buildrecdict["_tree"]
        if buildrecdict.has_key("_parent"):
            new_recdict["_parent"] = buildrecdict["_parent"]
        new_recdict["_rpstack"] = buildrecdict["_rpstack"]

        # Add the invoking scope to the "_stack" scope.
        if recdict.has_key("_stack"):
            stack = [ recdict ] + recdict["_stack"].stack
            new_recdict["_caller"] = recdict
        else:
            stack = [ ]
        new_recdict["_stack"] = CallstackDict(stack)

        # The "_up" scope searches "_stack", "_tree" and then "_conf".
        new_recdict["_up"] = CallstackDict(new_recdict["_stack"].stack
                                           + new_recdict["_tree"].stack
                                           + [ new_recdict["_conf"] ])

        # Recipe name and line number for this scope.
        noscopedict["recipe_name"] = rpstack[-1].name
        noscopedict["recipe_lnum"] = rpstack[-1].line_nr

    else:
        # ":child {pass}" or ":execute {pass}" command.
        # Add the child recipe to the "_tree" scope
        new_recdict["_tree"] = CallstackDict([ new_recdict ]
                                                      + recdict["_tree"].stack)
        # The "_stack" scope doesn't change.
        if recdict.has_key("_stack"):
            new_recdict["_stack"] = recdict["_stack"]

        # The "_up" scope is "_stack" plus "_tree" plus "_conf", but exclude
        # the recipe itself.
        if recdict.has_key("_stack"):
            new_recdict["_up"] = CallstackDict(new_recdict["_stack"].stack
                                               + recdict["_tree"].stack
                                               + [ recdict["_conf"] ])
        else:
            new_recdict["_up"] = CallstackDict(recdict["_tree"].stack
                                               + [ recdict["_conf"] ])

        # Don't use "noscopedict" for _recipe, "$_recipe.var" would be searched
        # for in parent scopes.  Do need a UserDict to make "_parent.var" work.
        rd = RecipeDict()
        rd.data = noscopedict.data
        new_recdict["_recipe"] = rd

        # Recipe name and line number for this scope.
        noscopedict["recipe_name"] = recipe_name
        noscopedict["recipe_lnum"] = 0

        # The "_buildrule_targets" entry is used for the target nodes from build
        # rules.  These are used when no target was explicitly specified.
        new_recdict["_buildrule_targets"] = []

    if xscope:
        for n in xscope:
            # Prepend the user scope in _stack and _up.
            # First check if anything is defined for the scope.
            if not n in recdict["_top"].user_scope_names:
                msg_warning(recdict, _('"%s" is not a known scope') % n)
            else:
                d = recdict["_top"].get(n)
                if d:
                    new_recdict["_stack"].stack.insert(0, d)
                    new_recdict["_up"].stack.insert(0, d)

    return new_recdict


def check_user_scope(recdict, name):
    """
    Check if the user scope "name" can be created without conflicting with an
    existing variable.  The caller must have checked that the scope itself
    doesn't exist yet and the name is valid.
    Doesn't check the current scope, because aap_assign() will use the variable
    value as a dictionary and fail then.
    Return None if it is OK, an error message otherwise.
    """
    if recdict.has_key("_up"):
        for d in recdict["_up"].stack:
            if d.has_key(name):
                if d.has_key("recipe_name"):
                    if d["recipe_name"] == "toplevel":
                        where = "at the toplevel"
                    else:
                        where = 'in recipe "%s"' % d["recipe_name"]
                        if d.get("recipe_lnum"):
                            where = where + ' line %d' % d["recipe_lnum"]
                else:
                    where = "in another scope"
                return (_("scope name used as variable %s: %s") % (where, name))
    return None


def create_user_scope(recdict, name):
    """
    Create a new scope "name" for the user.
    Caller must verify that "name" is a valid scope name.
    """
    # Create a new scope.  It won't search in other scopes, thus a RecipeDict
    # will do.
    add_user_scope(recdict, name, RecipeDict())

def add_user_scope(recdict, name, dict):
    # Add the user scope to the current scope.
    recdict[name] = dict

    # Add the user scope to the callstack and recipe tree scopes, so that it is
    # available when leaving the current scope.
    if recdict.has_key("_up"):
        for d in recdict["_up"].stack:
            d[name] = dict

    # Remember this scope exists, so that it will be copied to nested scopes.
    recdict["_top"].user_scope_names.append(name)


def prepend_user_scope(recdict, namelist):
    """
    Prepend the user scope names in list "namelist" to the scopes used in
    "recdict".  Return a dictionary that is to be passed to undo_user_scope().
    """
    if not namelist:
        return None

    # First save the current stacks.
    ret = {}
    ret["_up"] = recdict["_up"].stack
    ret["_stack"] = recdict["_stack"].stack

    # Prepend the user scopes to the _up and _stack scopes.
    for n in namelist:
        d = recdict["_top"].get(n)
        if d and isinstance(d, RecipeDict):
            recdict["_stack"].stack.insert(0, d)
            recdict["_up"].stack.insert(0, d)

    return ret

def undo_user_scope(recdict, d):
    """
    Undo the effect of prepend_user_scope().
    """
    if d:
        if d.get("_up"):
            recdict["_up"].__dict__["stack"] = d.get("_up")
        if d.get("_stack"):
            recdict["_stack"].__dict__["stack"] = d.get("_stack")


def is_scope_name(recdict, name):
    """Return non-zero when "name" is a scope name."""
    return name in [ "_no", "_tree", "_parent", "_recipe", "_up", "_top",
                     "_default", "_start", "_stack",
                    "_caller", "_conf" ] + recdict["_top"].user_scope_names


def rule_in_tree(rule_recdict, target_recdict):
    """
    Check if the recipe of "target_recdict" is in the tree of scopes that
    "rule_recdict" contains.  Used to check if a rule can be used for a target.
    """
    if not rule_recdict:
        return 0
    if rule_recdict["_recipe"] is target_recdict["_recipe"]:
        return 1            # that was easy!

    # Check the _tree scope for rules.
    if target_recdict.has_key("_tree"):
        for rd in target_recdict["_tree"].stack:
            if rd["_recipe"] is rule_recdict["_recipe"]:
                return 1
    return 0


# vim: set sw=4 et sts=4 tw=79 fo+=l:
