1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
|
# 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:
i = recdict.get(n)
if i is None:
msg_warning(recdict, _('get_build_recdict(): "%s" scope missing') % n)
else:
new_recdict[n] = i
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:
|