SimObject.py revision 1046
1# Copyright (c) 2004 The Regents of The University of Michigan 2# All rights reserved. 3# 4# Redistribution and use in source and binary forms, with or without 5# modification, are permitted provided that the following conditions are 6# met: redistributions of source code must retain the above copyright 7# notice, this list of conditions and the following disclaimer; 8# redistributions in binary form must reproduce the above copyright 9# notice, this list of conditions and the following disclaimer in the 10# documentation and/or other materials provided with the distribution; 11# neither the name of the copyright holders nor the names of its 12# contributors may be used to endorse or promote products derived from 13# this software without specific prior written permission. 14# 15# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 16# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 17# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 18# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 19# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 20# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 21# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 22# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 23# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 27from __future__ import generators 28 29import os 30import re 31import sys 32 33##################################################################### 34# 35# M5 Python Configuration Utility 36# 37# The basic idea is to write simple Python programs that build Python 38# objects corresponding to M5 SimObjects for the deisred simulation 39# configuration. For now, the Python emits a .ini file that can be 40# parsed by M5. In the future, some tighter integration between M5 41# and the Python interpreter may allow bypassing the .ini file. 42# 43# Each SimObject class in M5 is represented by a Python class with the 44# same name. The Python inheritance tree mirrors the M5 C++ tree 45# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 46# SimObjects inherit from a single SimObject base class). To specify 47# an instance of an M5 SimObject in a configuration, the user simply 48# instantiates the corresponding Python object. The parameters for 49# that SimObject are given by assigning to attributes of the Python 50# object, either using keyword assignment in the constructor or in 51# separate assignment statements. For example: 52# 53# cache = BaseCache('my_cache', root, size=64*K) 54# cache.hit_latency = 3 55# cache.assoc = 8 56# 57# (The first two constructor arguments specify the name of the created 58# cache and its parent node in the hierarchy.) 59# 60# The magic lies in the mapping of the Python attributes for SimObject 61# classes to the actual SimObject parameter specifications. This 62# allows parameter validity checking in the Python code. Continuing 63# the example above, the statements "cache.blurfl=3" or 64# "cache.assoc='hello'" would both result in runtime errors in Python, 65# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 66# parameter requires an integer, respectively. This magic is done 67# primarily by overriding the special __setattr__ method that controls 68# assignment to object attributes. 69# 70# The Python module provides another class, ConfigNode, which is a 71# superclass of SimObject. ConfigNode implements the parent/child 72# relationship for building the configuration hierarchy tree. 73# Concrete instances of ConfigNode can be used to group objects in the 74# hierarchy, but do not correspond to SimObjects themselves (like a 75# .ini section with "children=" but no "type=". 76# 77# Once a set of Python objects have been instantiated in a hierarchy, 78# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 79# will generate a .ini file. See simple-4cpu.py for an example 80# (corresponding to m5-test/simple-4cpu.ini). 81# 82##################################################################### 83 84##################################################################### 85# 86# ConfigNode/SimObject classes 87# 88# The Python class hierarchy rooted by ConfigNode (which is the base 89# class of SimObject, which in turn is the base class of all other M5 90# SimObject classes) has special attribute behavior. In general, an 91# object in this hierarchy has three categories of attribute-like 92# things: 93# 94# 1. Regular Python methods and variables. These must start with an 95# underscore to be treated normally. 96# 97# 2. SimObject parameters. These values are stored as normal Python 98# attributes, but all assignments to these attributes are checked 99# against the pre-defined set of parameters stored in the class's 100# _param_dict dictionary. Assignments to attributes that do not 101# correspond to predefined parameters, or that are not of the correct 102# type, incur runtime errors. 103# 104# 3. Hierarchy children. The child nodes of a ConfigNode are stored 105# in the node's _children dictionary, but can be accessed using the 106# Python attribute dot-notation (just as they are printed out by the 107# simulator). Children cannot be created using attribute assigment; 108# they must be added by specifying the parent node in the child's 109# constructor or using the '+=' operator. 110 111# The SimObject parameters are the most complex, for a few reasons. 112# First, both parameter descriptions and parameter values are 113# inherited. Thus parameter description lookup must go up the 114# inheritance chain like normal attribute lookup, but this behavior 115# must be explicitly coded since the lookup occurs in each class's 116# _param_dict attribute. Second, because parameter values can be set 117# on SimObject classes (to implement default values), the parameter 118# checking behavior must be enforced on class attribute assignments as 119# well as instance attribute assignments. Finally, because we allow 120# class specialization via inheritance (e.g., see the L1Cache class in 121# the simple-4cpu.py example), we must do parameter checking even on 122# class instantiation. To provide all these features, we use a 123# metaclass to define most of the SimObject parameter behavior for 124# this class hierarchy. 125# 126##################################################################### 127 128# The metaclass for ConfigNode (and thus for everything that derives 129# from ConfigNode, including SimObject). This class controls how new 130# classes that derive from ConfigNode are instantiated, and provides 131# inherited class behavior (just like a class controls how instances 132# of that class are instantiated, and provides inherited instance 133# behavior). 134class MetaConfigNode(type): 135 136 # __new__ is called before __init__, and is where the statements 137 # in the body of the class definition get loaded into the class's 138 # __dict__. We intercept this to filter out parameter assignments 139 # and only allow "private" attributes to be passed to the base 140 # __new__ (starting with underscore). 141 def __new__(cls, name, bases, dict): 142 priv_keys = [k for k in dict.iterkeys() if k.startswith('_')] 143 priv_dict = {} 144 for k in priv_keys: priv_dict[k] = dict[k]; del dict[k] 145 # entries left in dict will get passed to __init__, where we'll 146 # deal with them as params. 147 return super(MetaConfigNode, cls).__new__(cls, name, bases, priv_dict) 148 149 # initialization: start out with an empty param dict (makes life 150 # simpler if we can assume _param_dict is always valid). Also 151 # build inheritance list to simplify searching for inherited 152 # params. Finally set parameters specified in class definition 153 # (if any). 154 def __init__(cls, name, bases, dict): 155 super(MetaConfigNode, cls).__init__(cls, name, bases, {}) 156 # initialize _param_dict to empty 157 cls._param_dict = {} 158 # __mro__ is the ordered list of classes Python uses for 159 # method resolution. We want to pick out the ones that have a 160 # _param_dict attribute for doing parameter lookups. 161 cls._param_bases = \ 162 [c for c in cls.__mro__ if hasattr(c, '_param_dict')] 163 # initialize attributes with values from class definition 164 for (pname, value) in dict.items(): 165 try: 166 setattr(cls, pname, value) 167 except Exception, exc: 168 print "Error setting '%s' to '%s' on class '%s'\n" \ 169 % (pname, value, cls.__name__), exc 170 171 # set the class's parameter dictionary (called when loading 172 # class descriptions) 173 def set_param_dict(cls, param_dict): 174 # should only be called once (current one should be empty one 175 # from __init__) 176 assert not cls._param_dict 177 cls._param_dict = param_dict 178 # initialize attributes with default values 179 for (pname, param) in param_dict.items(): 180 try: 181 setattr(cls, pname, param.default) 182 except Exception, exc: 183 print "Error setting '%s' default on class '%s'\n" \ 184 % (pname, cls.__name__), exc 185 186 # Set the class's parameter dictionary given a code string of 187 # parameter initializers (as from an object description file). 188 # Note that the caller must pass in the namespace in which to 189 # execute the code (usually the caller's globals()), since if we 190 # call globals() from inside this function all we get is this 191 # module's internal scope. 192 def init_params(cls, init_code, ctx): 193 dict = {} 194 try: 195 exec fixPythonIndentation(init_code) in ctx, dict 196 except Exception, exc: 197 print "Error in %s.init_params:" % cls.__name__, exc 198 raise 199 cls.set_param_dict(dict) 200 201 # Lookup a parameter description by name in the given class. Use 202 # the _param_bases list defined in __init__ to go up the 203 # inheritance hierarchy if necessary. 204 def lookup_param(cls, param_name): 205 for c in cls._param_bases: 206 param = c._param_dict.get(param_name) 207 if param: return param 208 return None 209 210 # Set attribute (called on foo.attr_name = value when foo is an 211 # instance of class cls). 212 def __setattr__(cls, attr_name, value): 213 # normal processing for private attributes 214 if attr_name.startswith('_'): 215 type.__setattr__(cls, attr_name, value) 216 return 217 # no '_': must be SimObject param 218 param = cls.lookup_param(attr_name) 219 if not param: 220 raise AttributeError, \ 221 "Class %s has no parameter %s" % (cls.__name__, attr_name) 222 # It's ok: set attribute by delegating to 'object' class. 223 # Note the use of param.make_value() to verify/canonicalize 224 # the assigned value 225 type.__setattr__(cls, attr_name, param.make_value(value)) 226 227 # generator that iterates across all parameters for this class and 228 # all classes it inherits from 229 def all_param_names(cls): 230 for c in cls._param_bases: 231 for p in c._param_dict.iterkeys(): 232 yield p 233 234# The ConfigNode class is the root of the special hierarchy. Most of 235# the code in this class deals with the configuration hierarchy itself 236# (parent/child node relationships). 237class ConfigNode(object): 238 # Specify metaclass. Any class inheriting from ConfigNode will 239 # get this metaclass. 240 __metaclass__ = MetaConfigNode 241 242 # Constructor. Since bare ConfigNodes don't have parameters, just 243 # worry about the name and the parent/child stuff. 244 def __init__(self, _name, _parent=None): 245 # Type-check _name 246 if type(_name) != str: 247 if isinstance(_name, ConfigNode): 248 # special case message for common error of trying to 249 # coerce a SimObject to the wrong type 250 raise TypeError, \ 251 "Attempt to coerce %s to %s" \ 252 % (_name.__class__.__name__, self.__class__.__name__) 253 else: 254 raise TypeError, \ 255 "%s name must be string (was %s, %s)" \ 256 % (self.__class__.__name__, _name, type(_name)) 257 # if specified, parent must be a subclass of ConfigNode 258 if _parent != None and not isinstance(_parent, ConfigNode): 259 raise TypeError, \ 260 "%s parent must be ConfigNode subclass (was %s, %s)" \ 261 % (self.__class__.__name__, _name, type(_name)) 262 self._name = _name 263 self._parent = _parent 264 if (_parent): 265 _parent._add_child(self) 266 self._children = {} 267 # keep a list of children in addition to the dictionary keys 268 # so we can remember the order they were added and print them 269 # out in that order. 270 self._child_list = [] 271 272 # When printing (e.g. to .ini file), just give the name. 273 def __str__(self): 274 return self._name 275 276 # Catch attribute accesses that could be requesting children, and 277 # satisfy them. Note that __getattr__ is called only if the 278 # regular attribute lookup fails, so private and parameter lookups 279 # will already be satisfied before we ever get here. 280 def __getattr__(self, name): 281 try: 282 return self._children[name] 283 except KeyError: 284 raise AttributeError, \ 285 "Node '%s' has no attribute or child '%s'" \ 286 % (self._name, name) 287 288 # Set attribute. All attribute assignments go through here. Must 289 # be private attribute (starts with '_') or valid parameter entry. 290 # Basically identical to MetaConfigClass.__setattr__(), except 291 # this sets attributes on specific instances rather than on classes. 292 def __setattr__(self, attr_name, value): 293 if attr_name.startswith('_'): 294 object.__setattr__(self, attr_name, value) 295 return 296 # not private; look up as param 297 param = self.__class__.lookup_param(attr_name) 298 if not param: 299 raise AttributeError, \ 300 "Class %s has no parameter %s" \ 301 % (self.__class__.__name__, attr_name) 302 # It's ok: set attribute by delegating to 'object' class. 303 # Note the use of param.make_value() to verify/canonicalize 304 # the assigned value. 305 v = param.make_value(value) 306 object.__setattr__(self, attr_name, v) 307 308 # A little convenient magic: if the parameter is a ConfigNode 309 # (or vector of ConfigNodes, or anything else with a 310 # '_set_parent_if_none' function attribute) that does not have 311 # a parent (and so is not part of the configuration 312 # hierarchy), then make this node its parent. 313 if hasattr(v, '_set_parent_if_none'): 314 v._set_parent_if_none(self) 315 316 def _path(self): 317 # Return absolute path from root. 318 if not self._parent and self._name != 'Universe': 319 print >> sys.stderr, "Warning:", self._name, "has no parent" 320 parent_path = self._parent and self._parent._path() 321 if parent_path and parent_path != 'Universe': 322 return parent_path + '.' + self._name 323 else: 324 return self._name 325 326 # Add a child to this node. 327 def _add_child(self, new_child): 328 # set child's parent before calling this function 329 assert new_child._parent == self 330 if not isinstance(new_child, ConfigNode): 331 raise TypeError, \ 332 "ConfigNode child must also be of class ConfigNode" 333 if new_child._name in self._children: 334 raise AttributeError, \ 335 "Node '%s' already has a child '%s'" \ 336 % (self._name, new_child._name) 337 self._children[new_child._name] = new_child 338 self._child_list += [new_child] 339 340 # operator overload for '+='. You can say "node += child" to add 341 # a child that was created with parent=None. An early attempt 342 # at playing with syntax; turns out not to be that useful. 343 def __iadd__(self, new_child): 344 if new_child._parent != None: 345 raise AttributeError, \ 346 "Node '%s' already has a parent" % new_child._name 347 new_child._parent = self 348 self._add_child(new_child) 349 return self 350 351 # Set this instance's parent to 'parent' if it doesn't already 352 # have one. See ConfigNode.__setattr__(). 353 def _set_parent_if_none(self, parent): 354 if self._parent == None: 355 parent += self 356 357 # Print instance info to .ini file. 358 def _instantiate(self): 359 print '[' + self._path() + ']' # .ini section header 360 if self._child_list: 361 # instantiate children in same order they were added for 362 # backward compatibility (else we can end up with cpu1 363 # before cpu0). 364 print 'children =', ' '.join([c._name for c in self._child_list]) 365 self._instantiateParams() 366 print 367 # recursively dump out children 368 for c in self._child_list: 369 c._instantiate() 370 371 # ConfigNodes have no parameters. Overridden by SimObject. 372 def _instantiateParams(self): 373 pass 374 375# SimObject is a minimal extension of ConfigNode, implementing a 376# hierarchy node that corresponds to an M5 SimObject. It prints out a 377# "type=" line to indicate its SimObject class, prints out the 378# assigned parameters corresponding to its class, and allows 379# parameters to be set by keyword in the constructor. Note that most 380# of the heavy lifting for the SimObject param handling is done in the 381# MetaConfigNode metaclass. 382 383class SimObject(ConfigNode): 384 # initialization: like ConfigNode, but handle keyword-based 385 # parameter initializers. 386 def __init__(self, _name, _parent=None, **params): 387 ConfigNode.__init__(self, _name, _parent) 388 for param, value in params.items(): 389 setattr(self, param, value) 390 391 # print type and parameter values to .ini file 392 def _instantiateParams(self): 393 print "type =", self.__class__._name 394 for pname in self.__class__.all_param_names(): 395 value = getattr(self, pname) 396 if value != None: 397 print pname, '=', value 398 399 def _sim_code(cls): 400 name = cls.__name__ 401 param_names = cls._param_dict.keys() 402 param_names.sort() 403 code = "BEGIN_DECLARE_SIM_OBJECT_PARAMS(%s)\n" % name 404 decls = [" " + cls._param_dict[pname].sim_decl(pname) \ 405 for pname in param_names] 406 code += "\n".join(decls) + "\n" 407 code += "END_DECLARE_SIM_OBJECT_PARAMS(%s)\n\n" % name 408 code += "BEGIN_INIT_SIM_OBJECT_PARAMS(%s)\n" % name 409 inits = [" " + cls._param_dict[pname].sim_init(pname) \ 410 for pname in param_names] 411 code += ",\n".join(inits) + "\n" 412 code += "END_INIT_SIM_OBJECT_PARAMS(%s)\n\n" % name 413 return code 414 _sim_code = classmethod(_sim_code) 415 416##################################################################### 417# 418# Parameter description classes 419# 420# The _param_dict dictionary in each class maps parameter names to 421# either a Param or a VectorParam object. These objects contain the 422# parameter description string, the parameter type, and the default 423# value (loaded from the PARAM section of the .odesc files). The 424# make_value() method on these objects is used to force whatever value 425# is assigned to the parameter to the appropriate type. 426# 427# Note that the default values are loaded into the class's attribute 428# space when the parameter dictionary is initialized (in 429# MetaConfigNode.set_param_dict()); after that point they aren't 430# used. 431# 432##################################################################### 433 434def isNullPointer(value): 435 return isinstance(value, NullSimObject) 436 437# Regular parameter. 438class Param(object): 439 # Constructor. E.g., Param(Int, "number of widgets", 5) 440 def __init__(self, ptype, desc, default=None): 441 self.ptype = ptype 442 self.ptype_name = self.ptype.__name__ 443 self.desc = desc 444 self.default = default 445 446 # Convert assigned value to appropriate type. Force parameter 447 # value (rhs of '=') to ptype (or None, which means not set). 448 def make_value(self, value): 449 # nothing to do if None or already correct type. Also allow NULL 450 # pointer to be assigned where a SimObject is expected. 451 if value == None or isinstance(value, self.ptype) or \ 452 isNullPointer(value) and issubclass(self.ptype, ConfigNode): 453 return value 454 # this type conversion will raise an exception if it's illegal 455 return self.ptype(value) 456 457 def sim_decl(self, name): 458 return 'Param<%s> %s;' % (self.ptype_name, name) 459 460 def sim_init(self, name): 461 if self.default == None: 462 return 'INIT_PARAM(%s, "%s")' % (name, self.desc) 463 else: 464 return 'INIT_PARAM_DFLT(%s, "%s", %s)' % \ 465 (name, self.desc, str(self.default)) 466 467# The _VectorParamValue class is a wrapper for vector-valued 468# parameters. The leading underscore indicates that users shouldn't 469# see this class; it's magically generated by VectorParam. The 470# parameter values are stored in the 'value' field as a Python list of 471# whatever type the parameter is supposed to be. The only purpose of 472# storing these instead of a raw Python list is that we can override 473# the __str__() method to not print out '[' and ']' in the .ini file. 474class _VectorParamValue(object): 475 def __init__(self, value): 476 assert isinstance(value, list) or value == None 477 self.value = value 478 479 def __str__(self): 480 return ' '.join(map(str, self.value)) 481 482 # Set member instance's parents to 'parent' if they don't already 483 # have one. Extends "magic" parenting of ConfigNodes to vectors 484 # of ConfigNodes as well. See ConfigNode.__setattr__(). 485 def _set_parent_if_none(self, parent): 486 if self.value and hasattr(self.value[0], '_set_parent_if_none'): 487 for v in self.value: 488 v._set_parent_if_none(parent) 489 490# Vector-valued parameter description. Just like Param, except that 491# the value is a vector (list) of the specified type instead of a 492# single value. 493class VectorParam(Param): 494 495 # Inherit Param constructor. However, the resulting parameter 496 # will be a list of ptype rather than a single element of ptype. 497 def __init__(self, ptype, desc, default=None): 498 Param.__init__(self, ptype, desc, default) 499 500 # Convert assigned value to appropriate type. If the RHS is not a 501 # list or tuple, it generates a single-element list. 502 def make_value(self, value): 503 if value == None: return value 504 if isinstance(value, list) or isinstance(value, tuple): 505 # list: coerce each element into new list 506 val_list = [Param.make_value(self, v) for v in iter(value)] 507 else: 508 # singleton: coerce & wrap in a list 509 val_list = [Param.make_value(self, value)] 510 # wrap list in _VectorParamValue (see above) 511 return _VectorParamValue(val_list) 512 513 def sim_decl(self, name): 514 return 'VectorParam<%s> %s;' % (self.ptype_name, name) 515 516 # sim_init inherited from Param 517 518##################################################################### 519# 520# Parameter Types 521# 522# Though native Python types could be used to specify parameter types 523# (the 'ptype' field of the Param and VectorParam classes), it's more 524# flexible to define our own set of types. This gives us more control 525# over how Python expressions are converted to values (via the 526# __init__() constructor) and how these values are printed out (via 527# the __str__() conversion method). Eventually we'll need these types 528# to correspond to distinct C++ types as well. 529# 530##################################################################### 531 532# Integer parameter type. 533class Int(object): 534 # Constructor. Value must be Python int or long (long integer). 535 def __init__(self, value): 536 t = type(value) 537 if t == int or t == long: 538 self.value = value 539 else: 540 raise TypeError, "Int param got value %s %s" % (repr(value), t) 541 542 # Use Python string conversion. Note that this puts an 'L' on the 543 # end of long integers; we can strip that off here if it gives us 544 # trouble. 545 def __str__(self): 546 return str(self.value) 547 548# Counter, Addr, and Tick are just aliases for Int for now. 549class Counter(Int): 550 pass 551 552class Addr(Int): 553 pass 554 555class Tick(Int): 556 pass 557 558# Boolean parameter type. 559class Bool(object): 560 561 # Constructor. Typically the value will be one of the Python bool 562 # constants True or False (or the aliases true and false below). 563 # Also need to take integer 0 or 1 values since bool was not a 564 # distinct type in Python 2.2. Parse a bunch of boolean-sounding 565 # strings too just for kicks. 566 def __init__(self, value): 567 t = type(value) 568 if t == bool: 569 self.value = value 570 elif t == int or t == long: 571 if value == 1: 572 self.value = True 573 elif value == 0: 574 self.value = False 575 elif t == str: 576 v = value.lower() 577 if v == "true" or v == "t" or v == "yes" or v == "y": 578 self.value = True 579 elif v == "false" or v == "f" or v == "no" or v == "n": 580 self.value = False 581 # if we didn't set it yet, it must not be something we understand 582 if not hasattr(self, 'value'): 583 raise TypeError, "Bool param got value %s %s" % (repr(value), t) 584 585 # Generate printable string version. 586 def __str__(self): 587 if self.value: return "true" 588 else: return "false" 589 590# String-valued parameter. 591class String(object): 592 # Constructor. Value must be Python string. 593 def __init__(self, value): 594 t = type(value) 595 if t == str: 596 self.value = value 597 else: 598 raise TypeError, "String param got value %s %s" % (repr(value), t) 599 600 # Generate printable string version. Not too tricky. 601 def __str__(self): 602 return self.value 603 604# Special class for NULL pointers. Note the special check in 605# make_param_value() above that lets these be assigned where a 606# SimObject is required. 607class NullSimObject(object): 608 # Constructor. No parameters, nothing to do. 609 def __init__(self): 610 pass 611 612 def __str__(self): 613 return "NULL" 614 615# The only instance you'll ever need... 616NULL = NullSimObject() 617 618# Enumerated types are a little more complex. The user specifies the 619# type as Enum(foo) where foo is either a list or dictionary of 620# alternatives (typically strings, but not necessarily so). (In the 621# long run, the integer value of the parameter will be the list index 622# or the corresponding dictionary value. For now, since we only check 623# that the alternative is valid and then spit it into a .ini file, 624# there's not much point in using the dictionary.) 625 626# What Enum() must do is generate a new type encapsulating the 627# provided list/dictionary so that specific values of the parameter 628# can be instances of that type. We define two hidden internal 629# classes (_ListEnum and _DictEnum) to serve as base classes, then 630# derive the new type from the appropriate base class on the fly. 631 632 633# Base class for list-based Enum types. 634class _ListEnum(object): 635 # Constructor. Value must be a member of the type's map list. 636 def __init__(self, value): 637 if value in self.map: 638 self.value = value 639 self.index = self.map.index(value) 640 else: 641 raise TypeError, "Enum param got bad value '%s' (not in %s)" \ 642 % (value, self.map) 643 644 # Generate printable string version of value. 645 def __str__(self): 646 return str(self.value) 647 648class _DictEnum(object): 649 # Constructor. Value must be a key in the type's map dictionary. 650 def __init__(self, value): 651 if value in self.map: 652 self.value = value 653 self.index = self.map[value] 654 else: 655 raise TypeError, "Enum param got bad value '%s' (not in %s)" \ 656 % (value, self.map.keys()) 657 658 # Generate printable string version of value. 659 def __str__(self): 660 return str(self.value) 661 662# Enum metaclass... calling Enum(foo) generates a new type (class) 663# that derives from _ListEnum or _DictEnum as appropriate. 664class Enum(type): 665 # counter to generate unique names for generated classes 666 counter = 1 667 668 def __new__(cls, map): 669 if isinstance(map, dict): 670 base = _DictEnum 671 keys = map.keys() 672 elif isinstance(map, list): 673 base = _ListEnum 674 keys = map 675 else: 676 raise TypeError, "Enum map must be list or dict (got %s)" % map 677 classname = "Enum%04d" % Enum.counter 678 Enum.counter += 1 679 # New class derives from selected base, and gets a 'map' 680 # attribute containing the specified list or dict. 681 return type.__new__(cls, classname, (base,), { 'map': map }) 682 683 684# 685# "Constants"... handy aliases for various values. 686# 687 688# For compatibility with C++ bool constants. 689false = False 690true = True 691 692# Some memory range specifications use this as a default upper bound. 693MAX_ADDR = 2**64 - 1 694 695# For power-of-two sizing, e.g. 64*K gives an integer value 65536. 696K = 1024 697M = K*K 698G = K*M 699 700##################################################################### 701 702# Munge an arbitrary Python code string to get it to execute (mostly 703# dealing with indentation). Stolen from isa_parser.py... see 704# comments there for a more detailed description. 705def fixPythonIndentation(s): 706 # get rid of blank lines first 707 s = re.sub(r'(?m)^\s*\n', '', s); 708 if (s != '' and re.match(r'[ \t]', s[0])): 709 s = 'if 1:\n' + s 710 return s 711 712# Hook to generate C++ parameter code. 713def gen_sim_code(file): 714 for objname in sim_object_list: 715 print >> file, eval("%s._sim_code()" % objname) 716 717# The final hook to generate .ini files. Called from configuration 718# script once config is built. 719def instantiate(*objs): 720 for obj in objs: 721 obj._instantiate() 722 723 724