The Sparta Modeling Framework
Loading...
Searching...
No Matches
sparta::TreeNode Class Reference

Node in a composite tree representing a sparta Tree item. More...

#include <TreeNode.hpp>

Inheritance diagram for sparta::TreeNode:
Collaboration diagram for sparta::TreeNode:

Classes

struct  ANY_TYPE
 Type for indicating that ANY notification source type should be included in a search performed by locateNotificationSources. More...
 
class  delegate
 Temporary delegate for notificaiton invokation until the implementation is working. This will then be merged with sparta::SpartaHandler. More...
 
class  ExtensionsBase
 Base class used to extend TreeNode parameter sets. More...
 
struct  NotificationInfo
 Notification type/name information. More...
 
class  type_info_container
 Container for std::type_info. More...
 

Public Types

Types
typedef uint64_t node_uid_type
 Type of unique-identifier assigned to every node.
 
typedef std::vector< TreeNode * > ChildrenVector
 Vector of TreeNode children.
 
typedef std::vector< std::string > AliasVector
 Vector of aliases (other names for this node)
 
typedef std::multimap< std::string, TreeNode * > ChildNameMapping
 Mapping of names, aliases, and groups to individual child nodes within one node. This must be in a deterministic order, so an ordered container (e.g. std::map) is required. A sorted contained is probably desirable, but not required.
 
typedef uint32_t group_idx_type
 Index within a group.
 
typedef std::weak_ptr< TreeNodeWeakPtr
 Weak pointer to a TreeNode. Acquire with getWeakPtr.
 
typedef std::weak_ptr< const TreeNodeConstWeakPtr
 Weak pointer to a const TreeNode. Acquire with getWeakPtr.
 
typedef std::shared_ptr< TreeNodeSharedPtr
 Shared pointer to TreeNode. Acquire with WeakPtr::lock().
 
typedef std::map< const std::string *, std::vector< TreeNode * > > TagsMap
 Map of strings (interned in StringManager) tags to TreeNodes.
 
- Public Types inherited from sparta::PhasedObject
enum  TreePhase {
  TREE_BUILDING = 0 , TREE_CONFIGURING = 1 , TREE_FINALIZING = 2 , TREE_FINALIZED = 3 ,
  TREE_TEARDOWN = 4
}
 Current phase of tree construction (applies to node and entire tree). More...
 

Public Member Functions

const ClockgetClock () override
 Walks up parents (starting with self) until a parent with an associated local clock is found, then returns that clock.
 
const ClockgetClock () const
 
const ClockgetLocalClock ()
 Gets the clock associated directly with this Node. This is useful for configuration and simulator debug, but not at run-time.
 
const ClockgetLocalClock () const
 
virtual void setClock (const Clock *clk)
 Assigns a clock to this node. This clock will then be accessed by any descendant which has no assigned clock or an ancestor with an assigned clock between that descendant and this node. getClock returns the Clock associated with the nearest ancestor.
 
SchedulergetScheduler (const bool must_exist=false)
 Get the scheduler associated with this tree node's root.
 
const SchedulergetScheduler (const bool must_exist=false) const
 
WeakPtr getWeakPtr ()
 Gets a weak pointer to this TreeNode. This weak pointer is guaranteed to expire when this TreeNode is destructed unless locked.
 
ConstWeakPtr getWeakPtr () const
 Const variant of getWeakPtr.
 
virtual void addLink (TreeNode *node, const std::string &label)
 Link this tree node with another tree node.
 
virtual void activateLink (const std::string &label)
 Activate one of the links added with addLink.
 
Construction
 TreeNode ()=delete
 Not default-constructable.
 
 TreeNode (const TreeNode &)=delete
 Not copy-constructable.
 
 TreeNode (TreeNode &&rhp)
 Move constructor.
 
TreeNodeoperator= (const TreeNode &)=delete
 Not assign-constructable.
 
 TreeNode (TreeNode *parent, const std::string &name, const std::string &group, group_idx_type group_idx, const std::string &desc, bool is_indexable)
 TreeNode full constructor. Initializes node and adds it as a child of an existing tree node (if parent is not null).
 
 TreeNode (TreeNode *parent, const std::string &name, const std::string &group, group_idx_type group_idx, const std::string &desc)
 TreeNode constructor with no is_indexable parameter [defaults to true].
 
 TreeNode (const std::string &name, const std::string &group, group_idx_type group_idx, const std::string &desc)
 TreeNode constructor with no parent Node.
 
 TreeNode (TreeNode *parent, const std::string &name, const std::string &desc)
 TreeNode constructor with no group information.
 
 TreeNode (TreeNode *parent, const std::string &group, group_idx_type group_idx, const std::string &desc)
 TreeNode constructor for anonymous node with group information.
 
 TreeNode (const std::string &name, const std::string &desc)
 TreeNode constructor with no parent node or group information.
 
virtual ~TreeNode ()
 Virtual destructor.
 
Identification
void addAlias (const std::string &alias)
 Add a single alias for this node.
 
void addAliases (const AliasVector &v)
 Adds each element of a vector of aliases to this node..
 
void addTag (const std::string &tag)
 Adds single tag to this node.
 
void addTags (const std::vector< std::string > &v)
 Adds each elements of a vector of tags to this node.
 
Node-Representation
virtual std::string stringize (bool pretty=false) const
 Create a string representation of this node.
 
void stringizeTags (std::stringstream &ss) const
 Render tags to a string in the form: " tags:[tag0, tag1]" If there are any tags. The leading space makes this a useful sub-utility of stringize because if there are no tags, returns empty string with no leading space.
 
Node Attributes
node_uid_type getNodeUID () const
 Gets the unique ID of this node.
 
const std::string & getName () const override
 Gets the name of this node.
 
const std::string * getNamePtr () const
 Gets the name of this node's string pointer which isinterned in StringManager)
 
bool isAnonymous () const
 Is this node anonymous.
 
bool isExpired () const
 Is this expired (i.e. has it been the rhp of a move constructor)
 
bool isIndexableByGroup () const
 Returns whether this object is accessible through its parent's interfaces for getting children by group and index.
 
const std::string & getGroup () const
 Gets the group name of this node.
 
const std::string * getGroupNamePtr () const
 Gets the group name string pointer (interned in StringManager singleton) of this node.
 
group_idx_type getGroupIdx () const
 Gets the group index of this node.
 
const std::vector< const std::string * > & getTags () const
 Gets the set of tags associated with this TreeNode.
 
bool hasTag (const std::string &tag) const
 Does this node have a specific tag (by name)
 
bool hasTag (const std::string *interned_tag_name) const
 Does this node have a specific tag (by string pointer interned with StringManager). This is faster than the alternate hasTag method because it relies only on pointer comparisons.
 
const std::string & getDesc () const
 Gets the description of this node.
 
bool isBuiltin () const
 Is this node in the builtins group.
 
void markHidden (bool hidden=true)
 Marks this TreeNode hidden for the purposes of printint out nodes. This does not make the node inaccessible, but causes it (and its subtree) to be hidden from typical recursive tree printouts.
 
bool isHidden () const
 Is this TreeNode supposed to be hidden during tree printouts This value does not have to be respected by anything using TreeNode and is mainly a UI/printout convenience.
 
Node Validation
void validateName (const std::string &nm)
 Validates the given name string for this TreeNode. Does not consider context (e.g. name collisions)
 
void validateGroup (const std::string &name, const std::string &group, group_idx_type idx)
 Validates the given group name string and group index for this TreeNode. Does not consider context (e.g. name collisions)
 
void validateDesc (const std::string &desc)
 Validates the given description string for this TreeNode.
 
TreeNode extensions
void addExtensionParameters (const std::string &extension_name, std::unique_ptr< ParameterSet > extension_params)
 Add a named parameter set to extend this tree node's metadata.
 
void addExtensionFactory (const std::string &extension_name, std::function< ExtensionsBase *()> factory)
 Add an extension factory to this tree node by its type (name). This method does not actually create any objects at this time. It will validate and create the extension only if asked for later on during simulation.
 
ExtensionsBasegetExtension (const std::string &extension_name)
 Get an extension object by type string. Returns nullptr if not found (unrecognized).
 
ExtensionsBasegetExtension ()
 Get an extension without needing to specify any particular type string. If no extensions exist, returns nullptr. If only one extension exists, returns that extension. If more than one extension exists, throws an exception.
 
const std::set< std::string > & getAllExtensionNames ()
 Extension names, if any. Tree node extensions are typically instantiated on-demand for best performance (you have to explicitly ask for an extension by its name, or it won't be created) - so note that calling this method will trigger the creation of all this node's extensions. The performance cost is proportional to the number of nodes in the virtual parameter tree.
 
Tree-Building
void addChild (TreeNode *child, bool inherit_phase=true)
 Adds a TreeNode to this node as a child.
 
void addChild (TreeNode &child)
 AddChild by reference for convenience.
 
void makeSubtreePrivate ()
 Make the entire subtree private.
 
void setScopeRoot ()
 
bool isScopeRoot () const
 
- Public Member Functions inherited from sparta::ResourceContainer
 ResourceContainer ()
 Consturct with a null, unlocked resource.
 
 ResourceContainer (const ResourceContainer &)=delete
 Copy construction disbled.
 
 ResourceContainer (ResourceContainer &&)=default
 Move constructor.
 
virtual ~ResourceContainer ()
 Destructor.
 
ResourcegetResource ()
 Gets the resource contained by this node if any. May only be called after finalization begins or during teardown.
 
const ResourcegetResource () const
 Const variant of getResource.
 
bool hasResource () const
 Determines if this node has a resource. This method exists in case the TreeNode is being explored by a tool or interactive UI. Typical TreeNode clients (such as Resources) will assume that there is a resource if they are expecting one.
 
template<class T , typename = typename std::enable_if<std::is_pointer<T>::value>::type>
const T getResourceAs () const
 Gets the resource contained by this node (if any) as the given type.
 
template<class T , typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
const T * getResourceAs () const
 Overload of getResourceAs for const access with a non-pointer template type.
 
template<class T , typename = typename std::enable_if<std::is_pointer<T>::value>::type>
getResourceAs ()
 Non-const overload of getResourceAs.
 
template<class T , typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
T * getResourceAs ()
 Non-const overload of getResourceAs.
 
virtual std::string getResourceType () const
 Gets the typename of the resource that this node will eventually contain.
 
virtual std::string getResourceTypeRaw () const
 Gets the typename of the resource that this node will eventually contain.
 
- Public Member Functions inherited from sparta::PhasedObject
 PhasedObject (PhasedObject &&)=default
 
TreePhase getPhase () const
 Gets the trees current phase.
 
virtual bool isBuilding () const
 Is this node (and thus the entire tree above and below it) currently in the TREE_BUILDING phase.
 
virtual bool isBuilt () const
 Is this node (and thus the entire tree above it) "built". Checks that getPhase has passed TREE_BUILDING.
 
virtual bool isConfigured () const
 Is this node (and thus the entire tree above it) "configured". Checks that getPhase has passed TREE_CONFIGURING (i.e. FINALIZED, FINALIZING, TEARDOWN, etc).
 
virtual bool isConfiguring () const
 Is this node (and thus the entire tree above it) currently in the TREE_CONFIGURING phase.
 
virtual bool isFinalizing () const
 Is this node (and thus the entire tree above it) "finalized".
 
virtual bool isFinalized () const
 Is this node (and thus the entire tree above it) "finalized".
 
virtual bool isTearingDown () const
 Is this node (and thus the entire tree above it) in the "teardown" phase.
 
- Public Member Functions inherited from sparta::ArchDataContainer
std::vector< ArchData * > getAssociatedArchDatas ()
 Retrieves all ArchDatas associated with this TreeNode so that children can use it to allocate their data.
 
const std::vector< ArchData * > getAssociatedArchDatas () const
 Const variant of getAssociatedArchDatas.
 
 ArchDataContainer ()=default
 Default constructor.
 
 ArchDataContainer (ArchDataContainer &)=delete
 Copy construction disabled.
 
 ArchDataContainer (ArchDataContainer &&)=default
 Move constructor.
 
virtual ~ArchDataContainer ()
 Virtual destructor.
 

Static Public Member Functions

static std::string createSearchRegexPattern (const std::string &pat)
 Compute a regex pattern for a node child path containing any number of wildcard characters (not a dot-separated location) which can be used to test against child node names.
 
static bool hasWildcardCharacters (const std::string &name)
 Determines if a given node name has any wildcard characters which will be substituted in createSearchRegexPattern.
 
static std::string getNextName (const std::string &name, size_t &pos)
 Gets the next name between two '.' chars in a string starting at pos.
 
static bool matchesGlobLike (const std::string &pattern, const std::string &other)
 Determine if a glob-like search pattern matches some other string.
 

Static Public Attributes

Constants
static const group_idx_type GROUP_IDX_NONE = (group_idx_type)-1
 GroupIndex indicating that a node has no group index because it belongs to no group.
 
static const node_uid_type MAX_NODE_UID
 Maximum value of node_uid_ before the framework throws an exception.
 
static constexpr char GROUP_NAME_NONE [] = ""
 Group name indicating that a node belongs to no group.
 
static constexpr char NODE_NAME_NONE [] = ""
 Node name for anonymous node.
 
static const std::string DEBUG_DUMP_SECTION_DIVIDER
 String dividing sections in a debug dump file.
 
static constexpr char NODE_NAME_VIRTUAL_GLOBAL [] = "_SPARTA_virtual_global_"
 Node name for the virtual glopbal node.
 
static constexpr char LOCATION_NODE_SEPARATOR_ATTACHED = '.'
 Separator character between node identifiers in a location string when the child is attached to the parent.
 
static constexpr char LOCATION_NODE_SEPARATOR_EXPECTING = ','
 Separator character between node identifiers in a location string when the child is being attached to the parent but has not been entirely attached (i.g. during construction of the child node)
 
static constexpr char LOCATION_NODE_SEPARATOR_UNATTACHED = '~'
 Separator character preceding a node identifiers in a location string when that node has no parent and is not in the process of being attached to one.
 
static const uint32_t RENDER_SUBTREE_INDENT = 2
 Spaces to indent for each tree level in sparta::TreeNode::renderSubtree.
 
static constexpr char GROUP_NAME_BUILTIN [] = "_SPARTA_builtin_group_"
 Reserved name for built-in nodes.
 
static const uint64_t CHILD_FIND_THRESHOLD = 100000
 Threshold for number of findChildren calls after finalization before a warning message is printed about framework misuse.
 
static const uint64_t CHILD_GET_THRESHOLD = 100000
 Threshold for number of getChild calls after finalization before a warning message is printed about framework misuse.
 
static const uint32_t TEARDOWN_ERROR_LIMIT = 5
 Number of teardown-phase-related messages that can be printed before the rest will be suppressed.
 
static const std::vector< std::pair< const char *, std::function< void(std::string &)> > > TREE_NODE_PATTERN_SUBS
 List of pattern susbtitutions when creating a search pattern from a TreeNode name containing wildcards.
 

Protected Member Functions

std::pair< uint32_t, std::string > recursGetDeepestMatchingPath_ (const std::string &path, size_t name_pos) const
 Finds the deepest node path mathing the input path. Implements getDeepestMatchingPath.
 
void setExpectedParent_ (const TreeNode *parent)
 Tracks a node as an expected parent without actually adding this node as a child. This is used almost exclusively for printing error messages which include a device-tree location BEFORE actually inserting this node into the device tree since node construction can fail.
 
void enterFinalizing_ ()
 Recursively enter TREE_FINALIZING phase.
 
void finalizeTree_ ()
 Recursively create resources based on tree configuration. enter_finalize_ should be invoked after this method successfully completes for an entire tree. Finalizes in the order of construction.
 
void validateTree_ ()
 Iterates the finalized tree and validates each node (e.g. ensures statistics can be evaluated)
 
void enterFinalized_ ()
 Recursively enter TREE_FINALIZED phase.
 
void enterConfig_ () noexcept
 Recursively enter TREE_CONFIGURING phase.
 
void bindTreeEarly_ ()
 Recursively invoke TreeNode::onBindTreeEarly_ and Resource::onBindTreeEarly_ (in that order for each node)
 
void bindTreeLate_ ()
 Recursively invoke TreeNode::onBindTreeEarly_ and Resource::onBindTreeLate_ (in that order for each node)
 
void simulationTerminating_ ()
 Hook to allow simulation resources to clean-up before simulation is ended.
 
void validatePostRun_ (const PostRunValidationInfo &info) const
 Hook to check the state of the simulator post-run and throw exceptions if something is incorrect.
 
void dumpDebugContent_ (std::ostream &out) const noexcept
 Allows resources to write out detailed textual debugging information about the node. This is typically called by a simulator when shutting down due to an exception (or depending on simulator config). However, it could also be called at other times.
 
void enterTeardown_ () noexcept
 Recursively enter TREE_TEARDOWN phase while alerting nodes through onEnteringTeardown_ and alterting Resources through Resource::onStartingTeardown_. Nodes already in TREE_TEARDOWN phase will not be alerted (neither will their associated Resources). All nodes are visited regardless of their parent's phase.
 
void verifyUniqueChildIdentifier_ (const std::string &ident, bool ignore_group_collision=false)
 Verifies that the given identifier is unique for all children of this node by comparing against names, groups, and aliases. Throws SpartaException if not unique.
 
void removeChildForTeardown_ (TreeNode *child)
 "Removes" the given child by invoking onDestroyingChild_ then removing this child from the children_ list
 
void removeFromParentForTeardown_ (TreeNode *parent)
 Protected Wrapper for getParent()->removeChildForTeardown_ which allows subclases of TreeNode to indirectly invoke removeChildForTeardown_ with themselves as the argument.
 
void detachFromParent_ ()
 Removes a node from its parent with the expectation this node will be immediately destroyed (i.e. is an xvalue)
 
void detachFromChildren_ ()
 Removes a node from its children with the expectation this node will be immediately destroyed (i.e. is an xvalue)
 
bool areParametersLocked_ () const
 This method informs whether the tree is past the lockdown phase for all LOCKED and HIDDEN parameters. Modifying LOCKED and HIDDEN parameters after this phase is disallowed. Tree can be locked down during TREE_BUILDING phase or TREE_CONFIGURING phase. During TREE_FINALIZING phase, all parameters are locked down as is.
 
- Protected Member Functions inherited from sparta::ResourceContainer
std::string getResourceTypeName_ () const
 Gets the rtti type name (demangled) of the resource type held by this container. If there is no resource held, returns empty string.
 
void setResource_ (Resource *r)
 Allows subclasses to assign the resource associated with this node.
 
void unsetResource_ ()
 Allows a resource to unset the resource set with setResource_.
 
void lockResource_ ()
 Allows subclasses to assign the resource associated with this node.
 
ResourcegetResource_ () noexcept
 Returns the currently held resource of this node (if any). This method can be called at any time.
 
const ResourcegetResource_ () const noexcept
 Const variant of getResource_.
 
- Protected Member Functions inherited from sparta::PhasedObject
void setPhase_ (TreePhase phase)
 Sets the current phase.
 

Static Protected Member Functions

static bool identityMatchesPattern_ (const std::string &ident, std::regex &expr, std::vector< std::string > &replacements)
 Performs pattern matching on a identity string.
 
static bool identityMatchesPattern_ (const std::string &ident, std::regex &expr)
 Variant of identityMatchesPattern_ with no replacements vector.
 
static std::string getPreviousName_ (const std::string &name, size_t &pos)
 Gets the previous name between two '.' chars in a string starting at pos.
 

Friends

class VirtualGlobalTreeNode
 Allow this class access internals for handling notification observation registration/deregistration broadcasts in a way that does not fit the composite tree pattern.
 
class ClockManager
 Allow ClockManager to directly change phase on nodes.
 
class SpartaStaticInitializer
 This class is responsible for instantiating the static container held by this TreeNode.
 
class TreeNodePrivateAttorney
 Friend an attorney pattern that can expose access to getAllChildren_ or other methods that bypass privacy_level_.
 

Internal Notification System

typedef std::vector< delegateDelegateVector
 Vector of delegates representing a list of observers to notify.
 
typedef std::map< type_info_container, DelegateVectorNotificationObserverMap
 Map of delegate vectors containing all observers.
 
template<typename DataT >
void postPropagatingNotification_ (const TreeNode *origin, const DataT &data, const std::string *name_id)
 Starts a notification propagating up the tree.
 
template<typename DataT , typename T , void(T::*)(const TreeNode &, const TreeNode &, const DataT &) TMethod>
DelegateVector::iterator findDelegate_ (DelegateVector &dvec, T *obj, const std::string &target_name)
 Finds a delegate associated with the given type T, object pointer, DataT, and TMethod within a DelevateVector. The intent of this function is to help see if a delegate is already registered with a calback by checking all known information associated with that callback against the input arguments.
 
template<typename DataT , typename T , void(T::*)(const DataT &) TMethod>
DelegateVector::iterator findDelegate_ (DelegateVector &dvec, T *obj, const std::string &target_name)
 
virtual void broadcastRegistrationForNotificationToChildren_ (const std::type_info &tinfo, const std::vector< const std::string * > &name_ids, TreeNode *obs_node, const delegate *del, const bool allow_private)
 Recursively notifies children that the notification described is now (or still is) being observed at the observation point TreeNode obs_node with the newly registered delegate del.
 
virtual void broadcastDeregistrationForNotificationToChildren_ (const std::type_info &tinfo, const std::vector< const std::string * > &name_ids, TreeNode *obs_node, const delegate *del, const bool allow_private)
 Recursively notifies children that the notification described has lost one particular observer (del) which was observing at the observation point TreeNode obs_node with the delegate del.
 
void broadcastRegistrationForNotificationListStringToChildren_ (const std::type_info &tinfo, const std::string &name, TreeNode *obs_node, const delegate *del, const bool private_only)
 Entry point to broadcastRegistrationForNotificationToChildren_ recursion. Breaks a name string.
 
void broadcastDeregistrationForNotificationListStringToChildren_ (const std::type_info &tinfo, const std::string &name, TreeNode *obs_node, const delegate *del, const bool private_only)
 Symmetric oppostie of broadcastRegistrationForNotificationListStringToChildren_.
 
template<typename DataT >
void invokeDelegatesOn_ (TreeNode *to_invoke, const DataT &data, const std::string *name_id)
 Protected wrapper for invokeDelegates_ which allows a TreeNode to invoke delegates on another TreeNode using itself as the origin.
 

Diagnostics

void lockdownParameters ()
 Method to put the device tree in lockdown phase. All LOCKED and HIDDEN parameters are frozen after this point. Regular parameters are not affected by this phase. This method requires a Simulation pointer and will assert at compile time if anyone tries to lockdown the tree without the context of a Simulation.
 
static const std::map< const TreeNode *, WeakPtr > & getParentlessNodes ()
 
static const std::map< const TreeNode *, WeakPtr > & getAllNodes ()
 Gets the vector of all TreeNodes currently known to be constructed.
 
static std::string formatAllNodes ()
 Prints the list of all TreeNodes currently known to be constructed.
 
static bool isNodeConstructed (const TreeNode *)
 Is a given node constructed?
 

Tree Navigation & State

virtual bool isAttached () const
 Is this node part of a device tree with a proper RootTreeNode at the root.
 
virtual TreeNodegetParent ()
 Gets immediate parent of this node if one exists.
 
virtual const TreeNodegetParent () const
 
template<class T , typename = typename std::enable_if<std::is_pointer<T>::value>::type>
const T getParentAs (bool must_exist=true) const
 Retrieves a parent casted to type T* if this node has a parent.
 
template<class T , typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
const T * getParentAs (bool must_exist=true) const
 
template<class T , typename = typename std::enable_if<std::is_pointer<T>::value>::type>
getParentAs (bool must_exist=true)
 
template<class T , typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
T * getParentAs (bool must_exist=true)
 
virtual TreeNodegetRoot ()
 Gets farthest ancestor of this node.
 
virtual const TreeNodegetRoot () const
 
TreeNodegetScopeRoot ()
 
const TreeNodegetScopeRoot () const
 
const TreeNodegetExpectedRoot () const
 build-time equivalent to getRoot before an object is actually attached to a tree. This is a mainly a framework and debugging tool for determining what the root of a node being constructed will be when complete
 
app::SimulationgetSimulation () const
 Gets the simulation (if any) associated with this tree.
 
uint32_t getNumChildren () const
 Gets the number of children that this node has including those in the sparta builtins group.
 
TreeNodegetChildAt (uint32_t idx) const
 Gets a child at a position in the children vector in the order in which they were added to this node.
 
const ChildrenVector getChildren () const
 Gets a vector of all children of this node in any group in the order in which they were added to this node.
 
uint32_t getChildren (std::vector< TreeNode * > &results, bool ignore_builtin_group=true, bool ignore_anonymous_nodes=true)
 Gets all children of this node in the order in which they were added to this node.
 
template<class T >
uint32_t getChildrenOfType (std::vector< T * > &results) const
 return all the children matching a particular type using dynamic cast.
 
sparta::TreeNodefindAncestorByName (const std::string &name)
 Find ancestor by name.
 
template<typename T >
sparta::TreeNodefindAncestorByType ()
 Find ancestor by type.
 
sparta::TreeNodefindAncestorByTag (const std::string &tag)
 Find the first ancestor with a particular tag.
 
template<typename T >
T * findAncestorResourceByType ()
 Find an ancestor's resource with a certain type.
 
const AliasVectorgetAliases () const
 Gets a vector of all aliases of this node.
 
uint32_t getChildrenIdentifiers (std::vector< std::string > &idents, bool ignore_builtin_group=true) const
 Gets all child identifiers, aliases, group names, and group-aliases which can be used to refer to a child of this node.
 
std::vector< const std::string * > getIdentifiers () const
 Gets all the identifiers for this node (excluding groups)
 
uint32_t getGroupSize (const std::string &group)
 Gets the number of nodes in a group.
 
group_idx_type getGroupIndexMax (const std::string &group)
 Gets the largest index of a node in the given group.
 
uint32_t getGroup (const std::string &group, std::vector< TreeNode * > &results)
 Gets all nodes in a child group.
 
uint32_t findChildren (const std::string &pattern, std::vector< TreeNode * > &results, std::vector< std::vector< std::string > > &replacements)
 Finds all children starting at this node with a given pattern relative to this node by matching names an aliases. Appends each found child to <results>.
 
uint32_t findChildren (const std::string &pattern, std::vector< TreeNode * > &results)
 Version of findChildren with no replacements vector.
 
virtual uint32_t findImmediateChildren_ (std::regex &expr, std::vector< TreeNode * > &found, std::vector< std::vector< std::string > > &replacements, bool allow_private=false)
 Finds immediate children with some identity (name or alias) matching a regex.
 
uint32_t findImmediateChildren_ (std::regex &expr, std::vector< TreeNode * > &found, bool allow_private=false)
 Variant of findImmediateChildren_ with no replacements vector.
 
virtual uint32_t findImmediateChildren_ (std::regex &expr, std::vector< const TreeNode * > &found, std::vector< std::vector< std::string > > &replacements, bool allow_private=false) const
 Const-qualified variant of findImmediateChildren_.
 
uint32_t findImmediateChildren_ (std::regex &expr, std::vector< const TreeNode * > &found, bool allow_private=false) const
 Variant of const-qualified findImmediateChildren_ with no replacements vector.
 
bool locationMatchesPattern (const std::string &pattern, const TreeNode *pat_loc) const
 Determines if the given pattern (which may contain wildcards) can describe this node.
 
TreeNodegetChild (const std::string &name, bool must_exist=true)
 Retrieves a child with this dotted path name.
 
const TreeNodegetChild (const std::string &name, bool must_exist=true) const
 Overloaded const-qualified.
 
std::string getDeepestMatchingPath (const std::string &path) const
 Gets the deepest whole node location starting from this node that matches some part of path starting at its beginning.
 
bool hasChild (const std::string &name) const noexcept
 Determines if a child can be found with the given dotted path.
 
bool hasImmediateChild (const TreeNode *n) const noexcept
 Determines if the node n is an immediate child of this node.
 
template<class T , typename = typename std::enable_if<std::is_pointer<T>::value>::type, class ConstT = typename ptr_to_const_obj_ptr<T>::type>
const ConstT getChildAs (const std::string &name, bool must_exist=true) const
 Retrieves a child that is castable to T with the given dotted path.
 
template<class T , typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
const T * getChildAs (const std::string &name, bool must_exist=true) const
 
template<class T , typename = typename std::enable_if<std::is_pointer<T>::value>::type>
getChildAs (const std::string &name, bool must_exist=true)
 
template<class T , typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
T * getChildAs (const std::string &name, bool must_exist=true)
 
template<class T , typename = typename std::enable_if<std::is_pointer<T>::value>::type, class ConstT = typename ptr_to_const_obj_ptr<T>::type>
ConstT getAs () const
 Retrieves this node after casting to type T.
 
template<class T , typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
const T * getAs () const
 Retrieves this node after casting to type const T.
 
template<class T , typename = typename std::enable_if<std::is_pointer<T>::value>::type>
getAs ()
 Retrieves this node after casting to type const T.
 
template<class T , typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
T * getAs ()
 Retrieves this node after casting to type const T.
 
uint32_t findChildrenByTag (const std::string &tag, std::vector< TreeNode * > &results, int32_t max_depth=-1)
 Finds a set of all children having the selected tag which this node or descendants of this node within a distance of the given max_depth.
 
bool isDescendantOf (const TreeNode *ancestor, int32_t max_depth=-1) const
 Determines if this node is a descendant of the specified ancestor node within some number of generations (depth).
 
std::string getLocation () const override final
 
std::string getDisplayLocation () const
 Returns the location of this node in the device tree which might not be usable for navigating the device tree (it cannot be used as an argument for getChild/findChildren).
 
std::string getExpectedLocation () const
 build-time equivalent to getLocation before an object is actually attached to a tree. This is a mainly a framework and debugging tool for determining what the location of a node currently being constructed will be when complete.
 
std::string renderSubtree (int32_t max_depth=-1, bool show_builtins=false, bool names_only=false, bool hide_hidden=false, bool(*leaf_filt_fxn)(const TreeNode *)=nullptr) const
 Renders the subtree starting at this node as a string containing an indentation-based depth-first representation.
 
uint32_t getLevel () const
 Gets the level of this node. 0 is root.
 
template<typename T >
uint32_t getRecursiveNodeCount () const
 Recursively gets the count of a nodes that are a subclass of a particular type (determined by dynamic_cast). Includes all descendants of this node in the tree, but excludes this node.
 
static TreeNodegetVirtualGlobalNode ()
 Gets the virtual global node singleton. This node can have no parent and no children. It receives notifications from all nodes in the simulator as if it were the parent of every node in the simulation that has no parent.
 

Public Notification System

uint32_t getPossibleNotifications (std::vector< NotificationInfo > &infos) const
 Gets information on the possible notifications generated by this node (excludes children).
 
void dumpPossibleNotifications (std::ostream &o) const noexcept
 Dumps a listing of the notifications which this node can generate to the ostream o.
 
template<typename DataT = ANY_TYPE>
uint32_t locateNotificationSources (std::vector< TreeNode * > &nodes, const std::string &name="")
 Gets all possible notification info from NotificationSources within this node's subtree.
 
template<typename DataT = ANY_TYPE>
void dumpLocatedNotificationSources (std::ostream &o, const std::string &name="")
 Retrieves the relevant NotificationSources from locateNotificationSources and prints them to the output o.
 
uint32_t getPossibleSubtreeNotifications (std::vector< NotificationInfo > &infos) const noexcept
 Gets information on the possible notifications generated by this node and all its descendants.
 
void dumpPossibleSubtreeNotifications (std::ostream &o) const noexcept
 Dumps a listing of the notifications which this node and its descendants can generate to the ostream o.
 
bool canGenerateNotification (const std::type_info &tinfo, const std::string *name) const
 Can this TreeNode generate a notification of the given type having the given name or pattern.
 
bool canGenerateNotification (const std::type_info &tinfo, const std::string &name) const
 Can this TreeNode generate a notification of the given type having the given name (does not require interned string - will intern automatically with StringManager).
 
bool canGenerateNotification (const NotificationInfo &info) const
 Can this TreeNode generate a notification of the given NotificationInfo.
 
bool canSubtreeGenerateNotification (const std::type_info &tinfo, const std::string *name) const
 Can this TreeNode or its descendants (of any distance) generate a notification of the given type having the given name.
 
bool canSubtreeGenerateNotification (const std::type_info &tinfo, const std::string &name) const
 Can this TreeNode or its descendants (of any distance) generate a notification of the given type having the given name (does not require interned string)
 
bool canSubtreeGenerateNotifications (const std::type_info &tinfo, const std::vector< const std::string * > &names) const
 Checks to see if any a subtree can generate any of several notification names which may be patterns.
 
template<typename DataT , typename T , void(T::*)(const TreeNode &, const TreeNode &, const DataT &) TMethod>
void registerForNotification (T *obj, const std::string &name, bool ensure_possible=true)
 Registers a callback method to listen for all notifications having the specified data type DataT and name (or any name if name is "") occuring on this node or any descendant (subtree).
 
template<typename DataT , typename T , void(T::*)(const DataT &) TMethod>
void registerForNotification (T *obj, const std::string &name, bool ensure_possible=true)
 
template<typename DataT , typename T , void(T::*)(const TreeNode &, const TreeNode &, const DataT &) TMethod>
void deregisterForNotification (T *obj, const std::string &name)
 Removes at most one registration made with registerForNotification.
 
template<typename DataT , typename T , void(T::*)(const DataT &) TMethod>
void deregisterForNotification (T *obj, const std::string &name)
 
bool hasObserversRegisteredForNotification (const std::type_info &tinfo, const std::string *name) const noexcept
 Determines if this TreeNode (not descendants) has any observers for this type of event and name.
 
void getDelegatesRegisteredForNotification (const std::type_info &tinfo, const std::string *name, std::vector< delegate > &dels) noexcept
 Gets the vector of delegates registered for a notification on this TreeNode.
 
static std::vector< const std::string * > parseNotificationNameString (const std::string &csl)
 Parses a comma-separated list of notification names (or patterns) separated by commas and ignoring whitespace around commas.
 
static bool notificationCategoryMatch (const std::string *query_id, const std::string *node_id)
 Checks if two notification categories match where one is an actual category.
 

Detailed Description

Node in a composite tree representing a sparta Tree item.

Warning
TreeNode construction is NOT thread-safe
Note
Children cannot be removed from their parents once attached
Not all TreeNodes in existance are required to be part of the same tree.
TreeNodes expect to be attached to a root node. See sparta::RootTreeNode for details. This root is required to act on the tree and hold some tree-wide properties. Multiple RootTreeNodes are expected to exist.

Because this class expects to be used with a composite pattern, several refinements exist elsewhere in sparta.

Important

Searching and getting child nodes is done by getChild, findChildren, and getChildAt only.

Teardown

TreeNodes cannot be removed from the tree once added until the Tree enters the TREE_TEARDOWN phase (see isTearingDown). Place the Tree's RootTreeNode into the teardown phase using sparta::RootTreeNode::enterTeardown.

Definition at line 204 of file TreeNode.hpp.

Member Typedef Documentation

◆ AliasVector

typedef std::vector<std::string> sparta::TreeNode::AliasVector

Vector of aliases (other names for this node)

Definition at line 248 of file TreeNode.hpp.

◆ ChildNameMapping

typedef std::multimap<std::string, TreeNode*> sparta::TreeNode::ChildNameMapping

Mapping of names, aliases, and groups to individual child nodes within one node. This must be in a deterministic order, so an ordered container (e.g. std::map) is required. A sorted contained is probably desirable, but not required.

Definition at line 256 of file TreeNode.hpp.

◆ ChildrenVector

Vector of TreeNode children.

Definition at line 243 of file TreeNode.hpp.

◆ ConstWeakPtr

typedef std::weak_ptr<const TreeNode> sparta::TreeNode::ConstWeakPtr

Weak pointer to a const TreeNode. Acquire with getWeakPtr.

Definition at line 271 of file TreeNode.hpp.

◆ DelegateVector

typedef std::vector<delegate> sparta::TreeNode::DelegateVector
protected

Vector of delegates representing a list of observers to notify.

Definition at line 3074 of file TreeNode.hpp.

◆ group_idx_type

Index within a group.

Definition at line 261 of file TreeNode.hpp.

◆ node_uid_type

Type of unique-identifier assigned to every node.

Definition at line 238 of file TreeNode.hpp.

◆ NotificationObserverMap

Map of delegate vectors containing all observers.

Definition at line 3079 of file TreeNode.hpp.

◆ SharedPtr

typedef std::shared_ptr<TreeNode> sparta::TreeNode::SharedPtr

Shared pointer to TreeNode. Acquire with WeakPtr::lock().

Definition at line 276 of file TreeNode.hpp.

◆ TagsMap

typedef std::map<const std::string*, std::vector<TreeNode*> > sparta::TreeNode::TagsMap

Map of strings (interned in StringManager) tags to TreeNodes.

Definition at line 281 of file TreeNode.hpp.

◆ WeakPtr

typedef std::weak_ptr<TreeNode> sparta::TreeNode::WeakPtr

Weak pointer to a TreeNode. Acquire with getWeakPtr.

Definition at line 266 of file TreeNode.hpp.

Constructor & Destructor Documentation

◆ TreeNode() [1/7]

sparta::TreeNode::TreeNode ( TreeNode &&  rhp)

Move constructor.

Precondition
rhp must not be fully finalized
rhp must not have any observers registered directly on it
Avoid move-constructing from TreeNodes with children as the children may fail to be re-added to this new TreeNode if they attempt to dynamic_cast this TreeNode's pointer to a subclass of TreeNode.

◆ TreeNode() [2/7]

sparta::TreeNode::TreeNode ( TreeNode parent,
const std::string &  name,
const std::string &  group,
group_idx_type  group_idx,
const std::string &  desc,
bool  is_indexable 
)

TreeNode full constructor. Initializes node and adds it as a child of an existing tree node (if parent is not null).

Warning
Subclasses should generally not use this constructor (or should pass a null parent instead) because this constructor can invoke addChild, which notifies observers that a child or parent is being added. Observers of these notifications tend to require fully constructed clases because they dynamically cast the TreeNode pointer to the intended tree type to find out its actual type. Then, it may examine the fields of the TreeNode subclass which may not yet be fully populated.
Parameters
parentTreeNode to which this will be added as a child. If this constructor is being invoked by a subclass, parent must be nullptr (or use a constructor with no parent argument). Subclass constructor is then responsible for adding the node.
nameName of this node. Name must satisfy validateName. May be NODE_NAME_NONE to indicate anonymous node. A group and group index is required for anonymous nodes. name must not be the same as any alias or name of another child of parent. It is HIGHLY recommended that name end in a number if there are multiple instances of similar objects at the same level in the tree (e.g. core0, core1). Even if only one such object exists at some level in the tree, having a numeric suffix now will ensure it is easy to adapt Python scripts to handle muliple instanecs later.
groupGroup name of this node. Must satisfy validateGroup. May be GROUP_NAME_NONE if a valid node name is given and group_idx == GROUP_IDX_NONE.
group_idxGroup index within group. Must satisfy validateGroup. Must be GROUP_IDX_NONE unless group != GROUP_NAME_NONE.
descDescription of this TreeNode. Must satisfy validateDesc
is_indexableIs this node indexable by its parent such that it can be accessed by group and index. Set this to false if children will have colliding group numbers and indexes (e.g. a banked register set). In almost all cases, this should be true.
Note
TreeNode construction is NOT thread safe

Example 1: Using groups to identify a sequence of related elements

* // given TreeNode* parent with name "parent"
* TreeNode foo2(&parent, "foo2", "foo", 2, "This is a Foo...")
* TreeNode foo3(&parent, "foo3", "foo", 3, "This is a Foo...")
* 

In a Python shell atop sparta, might allow the following means of accessing foo:

* >>> parent.foo
* <Group of 2 Nodes>
* >>> parent.foo2 # Node name
* <foo2 node>
* >>> parent.foo3
* <foo3 node>
* >>> parent.foo[2] # Node group[index]
* <foo2 node>
* >>> parent.foo[3]
* <foo3 node>
* >>> for n in parent.foo: print n # Iterate Node group
* <foo2 node>
* <foo3 node>
* \endvarbatim
*
* <h4>Example 2: Using groups for Nodes which have no siblings</h4>
* Even if you will only have one node having a certain name prefix at
* some point in the sparta tree (e.g. "soc"), it may make sense to make
* it indexable. One day, a multi-soc/board simulation may need to be
* created.
* \verbatim
* // given TreeNode* parent with name "parent"
* TreeNode foo(&parent, "foo", "foo", 0, "This is a Foo...")
* 

In a Python shell atop sparta, might allow the following means of accessing foo:

* >>> parent.foo # Name
* <foo node>
* >>> parent.foo[0] # Group
* <foo node>
* >>> for f in parent.foo: print f
* <foo node>
* 

◆ TreeNode() [3/7]

sparta::TreeNode::TreeNode ( TreeNode parent,
const std::string &  name,
const std::string &  group,
group_idx_type  group_idx,
const std::string &  desc 
)

TreeNode constructor with no is_indexable parameter [defaults to true].

See also
other sparta::TreeNode constructors

◆ TreeNode() [4/7]

sparta::TreeNode::TreeNode ( const std::string &  name,
const std::string &  group,
group_idx_type  group_idx,
const std::string &  desc 
)

TreeNode constructor with no parent Node.

See also
other sparta::TreeNode constructors

◆ TreeNode() [5/7]

sparta::TreeNode::TreeNode ( TreeNode parent,
const std::string &  name,
const std::string &  desc 
)

TreeNode constructor with no group information.

See also
other sparta::TreeNode constructors
Warning
Subclasses should generally not use this constructor (or should pass a null parent instead) because this constructor can invoke addChild, which requires a TreeNode subclass (at this) to be fully constructed

group defaults to GROUP_NAME_NONE. group_idx defaults to GROUP_IDX_NONE.

◆ TreeNode() [6/7]

sparta::TreeNode::TreeNode ( TreeNode parent,
const std::string &  group,
group_idx_type  group_idx,
const std::string &  desc 
)

TreeNode constructor for anonymous node with group information.

See also
other sparta::TreeNode constructors
Note
group and group_idx must be valid
Warning
Subclasses should generally not use this constructor (or should pass a null parent instead) because this constructor can invoke addChild, which requires a TreeNode subclass (at this) to be fully constructed

Name defaults to NODE_NAME_NONE. group and group_idx should be meaningful

◆ TreeNode() [7/7]

sparta::TreeNode::TreeNode ( const std::string &  name,
const std::string &  desc 
)

TreeNode constructor with no parent node or group information.

See also
other sparta::TreeNode constructors

group defaults to GROUP_NAME_NONE. group_idx defaults to GROUP_IDX_NONE.

◆ ~TreeNode()

virtual sparta::TreeNode::~TreeNode ( )
virtual

Virtual destructor.

Exceptions
SpartaExceptionif node is attached to a root (via isAttached) and tree is not in TREE_TEARDOWN phase

Member Function Documentation

◆ activateLink()

virtual void sparta::TreeNode::activateLink ( const std::string &  label)
virtual

Activate one of the links added with addLink.

Parameters
labelThe label of the tree node

What it means to activate a link can differ from simulator to simulator and each simulator that use the link notion is free to define the semantics of the link and what it means to active a link.

In case this method is not overriden, we assume that it has a resource and will let its resource know about what tree nodes are being shadowed.

◆ addAlias()

void sparta::TreeNode::addAlias ( const std::string &  alias)

Add a single alias for this node.

Parameters
aliasAlias to assign to this node. alias is subject to the same constraints as a node name and must satisfy validateName. Additionally, aliases must not be empty strings
Precondition
Node must not yet have a parent. When adding a node as a child, the parent checks for alias, name, group, and group+idx collisions amongst all its children
No alias with the same name may be present in this node
alias cannot match any name, alias, or group of another child of this node's parent.
Tree cannot be built (Not having a parent should hide this precondition)

◆ addAliases()

void sparta::TreeNode::addAliases ( const AliasVector v)

Adds each element of a vector of aliases to this node..

Parameters
vVector of alias strings. Each alias in the vector is subject to the conditions of addAlias
Precondition
See addAlias

◆ addChild() [1/2]

void sparta::TreeNode::addChild ( TreeNode child)

AddChild by reference for convenience.

Overloads addChild(TreeNode* child)

◆ addChild() [2/2]

void sparta::TreeNode::addChild ( TreeNode child,
bool  inherit_phase = true 
)

Adds a TreeNode to this node as a child.

Precondition
All subblasses of this instance should be constructed before calling this methods and none should be destructed. This ensures that the onAddingChild_ and onSettingParent_ callback hooks can be invoked with a child having valid RTTI data. See the C++11 standard: 12.7 Construction and destruction [class.cdtor] Paragraph 3.
Parameters
childborrowed pointer to TreeNode to add as a child. child must not already be a parent of *this. child cannot already be an immediate child of *this. Child cannot have the same name or alias as another name or alias of a child of *this (group names may be repeated though). Child must not be nullptr.
inherit_phaseDoes the child inherit its phase from the parent This should be true in almost all uses of the framework
Warning
child is a borrowed reference - child is not copied. child lifetime must exceed that of this instance.
Postcondition
Child must be added to this node and have this node set as its parent.
New child will be added to the end of the list. This is important for finalization because new nodes can be added while nodes are being iterated.
Exceptions
SpartaExceptionif the child cannot be added for any reason.
Warning
Do not call unless all subblasses of this instance have begun construction. No subclasses have completed destruction. This ensures that the onAddingChild_ and onSettingParent_ callback hooks can be invoked with a child having valid RTTI data. See the C++11 standard: 12.7 Construction and destruction [class.cdtor] Paragraph 3

Invokes onAddingChild_ before finally attaching the child. This gives subclasses a chance to either reject the node or perform some local actions like caching the child or determining its type.

Invokes setParent_ on the child which handles passing information about the new parent-child relationship to child's subtree.

◆ addLink()

virtual void sparta::TreeNode::addLink ( TreeNode node,
const std::string &  label 
)
virtual

Link this tree node with another tree node.

Parameters
nodeThe tree node to link with
labelThe label of the tree node

This method is a generic interface for linking a tree node to other tree nodes. Linking is not bi-directinal, linking a tree node A with tree node be by calling this method on A, links A with B but not B with A.

In case this method is not overriden, we assume that it has a resource and will let its resource know about what tree nodes are being shadowed.

Reimplemented in sparta::MirrorNotificationSource< NotificationDataT >.

◆ addTag()

void sparta::TreeNode::addTag ( const std::string &  tag)

Adds single tag to this node.

Parameters
tagTag to add to this node. Tag is subject to the same constraints as a node name and must satisfy validateName. Additionally, tags must not be empty strings
Note
Tags cannot be removed once added
Precondition
Tree cannot be in or past TREE_FINALIZED phase
No tag by this name may already be present. Since tag data may come from multiple places in the simulator source code, tags of the same name may have different semantics depending on who added them. This test ensures that one node does not have tags (meta-data) with conflicting semantics. Generally, the client should add each tag only once without checking to see if it already present. This will identify duplicate tags having different semantics
Postcondition
Adds tag to global_tags_map_. See findChildrenByTag

◆ addTags()

void sparta::TreeNode::addTags ( const std::vector< std::string > &  v)

Adds each elements of a vector of tags to this node.

Parameters
vVector of tag strings. Each tag in the vector is subject to the conditions of addTag
Precondition
See addTag

◆ areParametersLocked_()

bool sparta::TreeNode::areParametersLocked_ ( ) const
inlineprotected

This method informs whether the tree is past the lockdown phase for all LOCKED and HIDDEN parameters. Modifying LOCKED and HIDDEN parameters after this phase is disallowed. Tree can be locked down during TREE_BUILDING phase or TREE_CONFIGURING phase. During TREE_FINALIZING phase, all parameters are locked down as is.

Definition at line 2746 of file TreeNode.hpp.

◆ bindTreeEarly_()

void sparta::TreeNode::bindTreeEarly_ ( )
protected

Recursively invoke TreeNode::onBindTreeEarly_ and Resource::onBindTreeEarly_ (in that order for each node)

See also
sparta::RootTreeNode::bindTreeEarly

◆ bindTreeLate_()

void sparta::TreeNode::bindTreeLate_ ( )
protected

Recursively invoke TreeNode::onBindTreeEarly_ and Resource::onBindTreeLate_ (in that order for each node)

See also
sparta::RootTreeNode::bindTreeLate

◆ broadcastDeregistrationForNotificationListStringToChildren_()

void sparta::TreeNode::broadcastDeregistrationForNotificationListStringToChildren_ ( const std::type_info &  tinfo,
const std::string &  name,
TreeNode obs_node,
const delegate del,
const bool  private_only 
)
inlineprotected

Symmetric oppostie of broadcastRegistrationForNotificationListStringToChildren_.

Definition at line 3230 of file TreeNode.hpp.

Here is the call graph for this function:

◆ broadcastDeregistrationForNotificationToChildren_()

virtual void sparta::TreeNode::broadcastDeregistrationForNotificationToChildren_ ( const std::type_info &  tinfo,
const std::vector< const std::string * > &  name_ids,
TreeNode obs_node,
const delegate del,
const bool  allow_private 
)
protectedvirtual

Recursively notifies children that the notification described has lost one particular observer (del) which was observing at the observation point TreeNode obs_node with the delegate del.

This is the symmetric opposite of broadcastRegistrationForNotificationToChildren_

Override to use a non-standard child-list. By default, this method simply iterates this node's children and call itself recursively for each

◆ broadcastRegistrationForNotificationListStringToChildren_()

void sparta::TreeNode::broadcastRegistrationForNotificationListStringToChildren_ ( const std::type_info &  tinfo,
const std::string &  name,
TreeNode obs_node,
const delegate del,
const bool  private_only 
)
inlineprotected

Entry point to broadcastRegistrationForNotificationToChildren_ recursion. Breaks a name string.

Definition at line 3214 of file TreeNode.hpp.

Here is the call graph for this function:

◆ broadcastRegistrationForNotificationToChildren_()

virtual void sparta::TreeNode::broadcastRegistrationForNotificationToChildren_ ( const std::type_info &  tinfo,
const std::vector< const std::string * > &  name_ids,
TreeNode obs_node,
const delegate del,
const bool  allow_private 
)
protectedvirtual

Recursively notifies children that the notification described is now (or still is) being observed at the observation point TreeNode obs_node with the newly registered delegate del.

Parameters
[in]tinfoType info of the notification
[in]name_idsvector of pointers to names or glob-like treenode identifier patterns. that may or may not be interned with sparta::StringManager.
[in]obs_nodeNode at which observer was installed
[in]delDelegate to invoke when the notification posts

This method allows Notification nodes to keep a map of which TreeNodes are observing observing a notification and what delegates are registered to observe that notification. The delegates can then be invoked directly by notification sources when appropriate notifications are posted.

Override to use a non-standard child-list. By default, this method simply iterates this node's children.

◆ canGenerateNotification() [1/3]

bool sparta::TreeNode::canGenerateNotification ( const NotificationInfo info) const

Can this TreeNode generate a notification of the given NotificationInfo.

Note
Also checks origin to ensure that it points to this node.

◆ canGenerateNotification() [2/3]

bool sparta::TreeNode::canGenerateNotification ( const std::type_info &  tinfo,
const std::string &  name 
) const

Can this TreeNode generate a notification of the given type having the given name (does not require interned string - will intern automatically with StringManager).

This is a version of the other canGenerateNotification function which does not require name to be a string interned with StringManager. Though the other variant is faster, this can be more convenient.

◆ canGenerateNotification() [3/3]

bool sparta::TreeNode::canGenerateNotification ( const std::type_info &  tinfo,
const std::string *  name 
) const

Can this TreeNode generate a notification of the given type having the given name or pattern.

Parameters
tinfotype_info from typeid on the type of notification being queried.
namePointer to interned name or pattern of notifications to query (from StringManager::internString). If This value is StringManager::EMPTY, looks for notifications having any name. glob-like patterns are supported (see matchesGlobLike).
Returns
true if this node can post a notification having the given type T where tinfo=typeid(T) and having a notification name matching the parameter 'name'. If the parameter 'name' is StringManager::EMPTY, matches on any notification name.
Note
This method is effectively a const expression - It will invariably return the same result for the same inputs.

Example

bool bCanGenLogMsg =
n->canGenerateNotification(typeid(sparta::log::Message), StringManager::getStringManager().EMPTY);
bool bCanGenWarningLogMsg =
n->canGenerateNotification(typeid(sparta::log::Message), sparta::log::categories::WARN);
static StringManager & getStringManager()
Returns the StringManager singleton.
static const std::string *const WARN
Indicates a WARNING.
Contains a logging message header and content.
Definition Message.hpp:18

◆ canSubtreeGenerateNotification() [1/2]

bool sparta::TreeNode::canSubtreeGenerateNotification ( const std::type_info &  tinfo,
const std::string &  name 
) const

Can this TreeNode or its descendants (of any distance) generate a notification of the given type having the given name (does not require interned string)

This is a version of the other canGenerateNotification function which does not require name to be a string interned with StringManager. Though the other variant is faster, this can be more convenient.

◆ canSubtreeGenerateNotification() [2/2]

bool sparta::TreeNode::canSubtreeGenerateNotification ( const std::type_info &  tinfo,
const std::string *  name 
) const

Can this TreeNode or its descendants (of any distance) generate a notification of the given type having the given name.

Parameters
tinfotype_info from typeid on the type of notification being queried.
namePointer to interned name of notifications to query about (from StringManager::internString). If This value is StringManager::EMPTY, looks for notifications having any name.
Returns
true if this node can post a notification having the given type T where tinfo=typeid(T) and having a notification name matching the parameter 'name'. If the parameter 'name' is StringManager::EMPTY, matches on any notification name.
Warning
This searches the entire subtree and can be slow.

Uses canGenerateNotification at each node to check. Returns on first match.

Example

bool bCanGenLogMsg =
n->canSubtreeGenerateNotification(typeid(sparta::log::Message), StringManager::getStringManager().EMPTY);
bool bCanGenWarningLogMsg =
n->canSubtreeGenerateNotification(typeid(sparta::log::Message), sparta::log::categories::WARN);

◆ canSubtreeGenerateNotifications()

bool sparta::TreeNode::canSubtreeGenerateNotifications ( const std::type_info &  tinfo,
const std::vector< const std::string * > &  names 
) const

Checks to see if any a subtree can generate any of several notification names which may be patterns.

See also
canSubtreeGenerateNotifications

◆ createSearchRegexPattern()

static std::string sparta::TreeNode::createSearchRegexPattern ( const std::string &  pat)
static

Compute a regex pattern for a node child path containing any number of wildcard characters (not a dot-separated location) which can be used to test against child node names.

Parameters
patPattern for searching immediate children (e.g. "core*" or "core0")
Note
The caller is responsible for parsing a location string into alphanumeric child strings.
See also
hasWildcardCharacters

◆ deregisterForNotification() [1/2]

template<typename DataT , typename T , void(T::*)(const TreeNode &, const TreeNode &, const DataT &) TMethod>
void sparta::TreeNode::deregisterForNotification ( T *  obj,
const std::string &  name 
)
inline

Removes at most one registration made with registerForNotification.

See also
REGISTER_FOR_NOTIFICATION

Refer to registerForNotification for more information about parameters. To deregister an observer delegate registered through registerForNotification, pass the same arguments.

Definition at line 3693 of file TreeNode.hpp.

◆ deregisterForNotification() [2/2]

template<typename DataT , typename T , void(T::*)(const DataT &) TMethod>
void sparta::TreeNode::deregisterForNotification ( T *  obj,
const std::string &  name 
)
inline

Definition at line 3700 of file TreeNode.hpp.

◆ dumpDebugContent_()

void sparta::TreeNode::dumpDebugContent_ ( std::ostream &  out) const
protectednoexcept

Allows resources to write out detailed textual debugging information about the node. This is typically called by a simulator when shutting down due to an exception (or depending on simulator config). However, it could also be called at other times.

Parameters
outOutput osteam to which this node should write all of its debug state. Note that this is not necessarily the same ostream for all nodes and resources, so this should not be shared.
Precondition
Simulator can be in any phase
Note
The entire resource tree is accessible. Nothing has been destructed yet
If you need to print a message
Do not throw here. If simulation state is invalid, that should be detected in validatePostRun_.
The simulator will not continue to run for this device tree at this point.
Conventionally, this method should write to out only. Writing entirely new files from this method is unexpected by the user and violates one of the design principals of this library where the only simulator input and output files and named explicitly by the user. If you must create a new file, please name it clearly.
Exceptions
Mustnot throw!

◆ dumpLocatedNotificationSources()

template<typename DataT = ANY_TYPE>
void sparta::TreeNode::dumpLocatedNotificationSources ( std::ostream &  o,
const std::string &  name = "" 
)
inline

Retrieves the relevant NotificationSources from locateNotificationSources and prints them to the output o.

Template Parameters
DataTtype of notification to search for or ANY_TYPE. See locateNotificationSource.
Parameters
oostream to write found nodes to.

Definition at line 3470 of file TreeNode.hpp.

◆ dumpPossibleNotifications()

void sparta::TreeNode::dumpPossibleNotifications ( std::ostream &  o) const
noexcept

Dumps a listing of the notifications which this node can generate to the ostream o.

Parameters
oostream to which the notification info list will be dumped

◆ dumpPossibleSubtreeNotifications()

void sparta::TreeNode::dumpPossibleSubtreeNotifications ( std::ostream &  o) const
noexcept

Dumps a listing of the notifications which this node and its descendants can generate to the ostream o.

Parameters
oostream to which the noitification info list will be dumped

◆ enterConfig_()

void sparta::TreeNode::enterConfig_ ( )
protectednoexcept

Recursively enter TREE_CONFIGURING phase.

Exceptions
Cannotthrow /post res_ of this node contains allocated Resource unless there was an exception

◆ enterFinalized_()

void sparta::TreeNode::enterFinalized_ ( )
protected

Recursively enter TREE_FINALIZED phase.

Exceptions
SpartaExceptionif already in TREE_FINALIZED phase or beyond
Note
Can be called multiple times if tree did not fully finalize.
Postcondition
All nodes in three are set to TREE_FINALIZED phase

◆ enterFinalizing_()

void sparta::TreeNode::enterFinalizing_ ( )
protected

Recursively enter TREE_FINALIZING phase.

Exceptions
SpartaExceptionalready in TREE_FINALIZING phase or beyond
Postcondition
All nodes in tree are set to TREE_FINALIZED phase

◆ enterTeardown_()

void sparta::TreeNode::enterTeardown_ ( )
protectednoexcept

Recursively enter TREE_TEARDOWN phase while alerting nodes through onEnteringTeardown_ and alterting Resources through Resource::onStartingTeardown_. Nodes already in TREE_TEARDOWN phase will not be alerted (neither will their associated Resources). All nodes are visited regardless of their parent's phase.

Exceptions
Cannotthrow

◆ finalizeTree_()

void sparta::TreeNode::finalizeTree_ ( )
protected

Recursively create resources based on tree configuration. enter_finalize_ should be invoked after this method successfully completes for an entire tree. Finalizes in the order of construction.

Exceptions
exceptionif there is an error anywhere in the finalization procedure. No actions are rolled-back, but this method can be called again.
Postcondition
Any TreeNode not in TREE_FINALIZING will be moved into TREE_FINALIZING
res_ of this node contains allocated Resource unless there was an exception or the node did not try to create a resource.
Clock is permanently associated with this node and cacheable

◆ findAncestorByName()

sparta::TreeNode * sparta::TreeNode::findAncestorByName ( const std::string &  name)
inline

Find ancestor by name.

Parameters
nameThe name of the ancestor, can include wildcards understood by Sparta
Returns
If found, ancestor's TreeNode, otherwise nullptr

Definition at line 1154 of file TreeNode.hpp.

Here is the call graph for this function:

◆ findAncestorByTag()

sparta::TreeNode * sparta::TreeNode::findAncestorByTag ( const std::string &  tag)
inline

Find the first ancestor with a particular tag.

Parameters
tagthe tag we are searching for.

This method will traverse up the tree until it finds a TreeNode who's tag matches the searched tag. This does not, by any means, guarantee that the resource is actually available yet.

Returns
a pointer to the treenode with tag or nullptr if not found.

Definition at line 1203 of file TreeNode.hpp.

Here is the call graph for this function:

◆ findAncestorByType()

template<typename T >
sparta::TreeNode * sparta::TreeNode::findAncestorByType ( )
inline

Find ancestor by type.

Template Parameters
TThe Resource type to check for
Returns
If found, ancestor's TreeNode, otherwise nullptr

This method will traverse up the tree until it finds a TreeNode who's resource type matches the given type. This does not, by any means, guarantee that the resource is available for obtaining.

Warning
If your resource inherits from some base class, passing T=your base class will not find the result. For this case, consider using findAncestorByTag, and add a tag to your base.

Definition at line 1181 of file TreeNode.hpp.

Here is the call graph for this function:

◆ findAncestorResourceByType()

template<typename T >
T * sparta::TreeNode::findAncestorResourceByType ( )
inline

Find an ancestor's resource with a certain type.

Template Parameters
Tthe resource type you'd like to return.
Returns
if found a pointer to the closest ancestor's resource of type T. nullptr otherwise.

This method is similar to findAncestorByType but will return the parent's resource instead.

Definition at line 1226 of file TreeNode.hpp.

Here is the call graph for this function:

◆ findChildren() [1/2]

uint32_t sparta::TreeNode::findChildren ( const std::string &  pattern,
std::vector< TreeNode * > &  results 
)
inline

Version of findChildren with no replacements vector.

Definition at line 1431 of file TreeNode.hpp.

◆ findChildren() [2/2]

uint32_t sparta::TreeNode::findChildren ( const std::string &  pattern,
std::vector< TreeNode * > &  results,
std::vector< std::vector< std::string > > &  replacements 
)
inline

Finds all children starting at this node with a given pattern relative to this node by matching names an aliases. Appends each found child to <results>.

Note
this is not a full recursive search. All children found will be N levels below this node whrere N Is dependent on the number of '.' tokens in the search string.
Parameters
patternSearch pattern in a restricted glob format.
resultsAll children with identifiers matching the pattern (alias or name) are appended to the back of this vector. Order of results appended is implementation dependent and not guaranteed consistent. All children found from this invocation of findChildren (and any deeper recursion) will be adjacent in <results>.
replacementsVector of replacements made on wildcards in path in order to find children. For each result added to results, a vector element is added to replacements. That vector element vector contains as many replacements as there are wildcards in the pattern. To clarify results.size()=replacements.size() and If replacements.size() > 1, replacements[0].size() is the number of wildcards in pattern.
Postcondition
Appends all children that match pattern to results (does not clear). Order of children appended is not defined or guaranteed to be consistent.
Warning
May return duplicates if any upward traversal is done after multiple downward traversal (e.g. pattern is '*..a'). This occurs since each of the N children found with "*" recognizes the upward search pattern '.' (after another '.') and searches the parent for "a".
May return duplicates if multiple aliases refer to the same TreeNode.
Returns
The number of children found and appended to results.
Note
This is not full path matching . Patterns are extracted between each '.' and the ends of the pattern string. Each of these Extracted patterns is used to search in the current search context and either find the new child/parent to search within OR (if the end of the whole pattern has been reached), to find a node to add to the results output vector
This method is not const to allow the caller to modify the found TreeNodes
Exceptions
Doesnot throw. May print a warning when a pattern attempts to search up and the current node has no parent.
See also
locationMatchesPattern

The following glob wildcard patterns are supported

  • ? Match 0 or 1 characters
  • * Match 0 or more characters

The following additional patterns are supported

  • + One or more characters

The following glob patterns are not supported

  • {}
  • []
  • \ (since all names involved in search are alphanumeric and underscore)

For example:

// For the following tree:
//
// a
// / | \________
// / | \ \ \
// bee ca dee ee be
// \
// g
//
// With pointers to each node (e.g. TreeNode* a):
//
std::vector<sparta::TreeNode*> r;
std::vector<std::vector<std::string>> reps;
r.clear();
assert(a->findChildren("bee", r) == 1);
assert(r[0] == bee);
r.clear();
assert(a->findChildren("+ee", r, reps) == 2);
assert(find(r.begin(), r.end(), dee) != r.end()); // Order of results not guaranteed
assert(find(r.begin(), r.end(), bee) != r.end());
assert(reps.at(0).at(0) == "b");
assert(reps.at(1).at(0) == "d");
r.clear();
assert(a->findChildren("*ee", r) == 3);
assert(find(r.begin(), r.end(), dee) != r.end()); // Order of results not guaranteed
assert(find(r.begin(), r.end(), bee) != r.end());
assert(find(r.begin(), r.end(), ee) != r.end());
r.clear();
assert(a->findChildren("*e+", r) == 2);
assert(find(r.begin(), r.end(), dee) != r.end()); // Order of results not guaranteed
assert(find(r.begin(), r.end(), bee) != r.end());
r.clear();
assert(ca->findChildren("..dee.g", r) == 1);
assert(r[0] == g);

Definition at line 1421 of file TreeNode.hpp.

◆ findChildrenByTag()

uint32_t sparta::TreeNode::findChildrenByTag ( const std::string &  tag,
std::vector< TreeNode * > &  results,
int32_t  max_depth = -1 
)

Finds a set of all children having the selected tag which this node or descendants of this node within a distance of the given max_depth.

Parameters
tagNodes having this tag will be placed into results vector
resultsVector of to which all results found by this method will be appended. This vector is not cleared
max_depthMaximum depth of a ancestor/descendant relationship when filtring children. 0 means that any nodes returned must be the node on which this method is invoked, 1 means that any nodes returned can be this or immediate children, and so on. A max_depth of -1 means that there is no limit on ancestor-descendant distance

This search works by searching the global tag map for the specified tag and then filtering this list for nodes which are a descendants of the node on which this method is invoked.

◆ findDelegate_() [1/2]

template<typename DataT , typename T , void(T::*)(const TreeNode &, const TreeNode &, const DataT &) TMethod>
DelegateVector::iterator sparta::TreeNode::findDelegate_ ( DelegateVector dvec,
T *  obj,
const std::string &  target_name 
)
inlineprotected

Finds a delegate associated with the given type T, object pointer, DataT, and TMethod within a DelevateVector. The intent of this function is to help see if a delegate is already registered with a calback by checking all known information associated with that callback against the input arguments.

Parameters
[in]dvecVector of delegates to search
[in]objObject which owns the delegate
[in]target_nameName or pattern of notification type. that this is used as-is.
Returns
Iterator within delegate vector parameter dvec. Will be a valid iterator if no matching delegate is found. Otherwise, will be dvec.end().
Note
Performs string comparison for delegate target name

Definition at line 3134 of file TreeNode.hpp.

◆ findDelegate_() [2/2]

template<typename DataT , typename T , void(T::*)(const DataT &) TMethod>
DelegateVector::iterator sparta::TreeNode::findDelegate_ ( DelegateVector dvec,
T *  obj,
const std::string &  target_name 
)
inlineprotected

Definition at line 3149 of file TreeNode.hpp.

◆ findImmediateChildren_() [1/2]

virtual uint32_t sparta::TreeNode::findImmediateChildren_ ( std::regex &  expr,
std::vector< const TreeNode * > &  found,
std::vector< std::vector< std::string > > &  replacements,
bool  allow_private = false 
) const
virtual

Const-qualified variant of findImmediateChildren_.

Reimplemented in sparta::VirtualGlobalTreeNode.

◆ findImmediateChildren_() [2/2]

virtual uint32_t sparta::TreeNode::findImmediateChildren_ ( std::regex &  expr,
std::vector< TreeNode * > &  found,
std::vector< std::vector< std::string > > &  replacements,
bool  allow_private = false 
)
virtual

Finds immediate children with some identity (name or alias) matching a regex.

Parameters
exprExpression to match with child node identities
foundAll nodes with matching identities are appended to this vector. This vector is not cleared
Returns
Number of children found in this call
Note
Does not recurse

Reimplemented in sparta::VirtualGlobalTreeNode.

◆ getAliases()

const AliasVector & sparta::TreeNode::getAliases ( ) const

Gets a vector of all aliases of this node.

Note
This is a const vector matching the order and content of the internal alias list
Returns
const vector of alias strings referring to this node

◆ getAs() [1/4]

template<class T , typename = typename std::enable_if<std::is_pointer<T>::value>::type>
T sparta::TreeNode::getAs ( )
inline

Retrieves this node after casting to type const T.

Template Parameters
TType of child expected
Returns
const T* if this node was castable to const T* using dynamic_cast.
Exceptions
SpartaExceptionif this node could not be cast to T
Warning
This method performs a dynamic cast (for now) and should not be used in performance-critical code

Overload of getAs for non-const access with pointer T type.

Definition at line 1712 of file TreeNode.hpp.

Here is the call graph for this function:

◆ getAs() [2/4]

template<class T , typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
T * sparta::TreeNode::getAs ( )
inline

Retrieves this node after casting to type const T.

Template Parameters
TType of child expected
Returns
const T* if this node was castable to const T* using dynamic_cast.
Exceptions
SpartaExceptionif this node could not be cast to T
Warning
This method performs a dynamic cast (for now) and should not be used in performance-critical code

Overload of getAs for non-const access with non-pointer T type

Definition at line 1735 of file TreeNode.hpp.

◆ getAs() [3/4]

template<class T , typename = typename std::enable_if<std::is_pointer<T>::value>::type, class ConstT = typename ptr_to_const_obj_ptr<T>::type>
ConstT sparta::TreeNode::getAs ( ) const
inline

Retrieves this node after casting to type T.

Template Parameters
TType of child expected
Returns
T* if this node was castable to T* using dynamic_cast.
Exceptions
SpartaExceptionif this node could not be cast to T
Warning
This method performs a dynamic cast (for now) and should not be used in performance-critical code

This could eventually be optimized or used to provide meaningful errors by storing type information in TreeNode.

Definition at line 1674 of file TreeNode.hpp.

Here is the call graph for this function:

◆ getAs() [4/4]

template<class T , typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
const T * sparta::TreeNode::getAs ( ) const
inline

Retrieves this node after casting to type const T.

Template Parameters
TType of child expected
Returns
const T* if this node was castable to const T* using dynamic_cast.
Exceptions
SpartaExceptionif this node could not be cast to T
Warning
This method performs a dynamic cast (for now) and should not be used in performance-critical code

Overload of getAs for const access with a pointer T type.

Definition at line 1697 of file TreeNode.hpp.

◆ getChild() [1/2]

TreeNode * sparta::TreeNode::getChild ( const std::string &  name,
bool  must_exist = true 
)
inline

Retrieves a child with this dotted path name.

Note
this is not a full recursive search. The child, if found, will be N levels below this node where N Is dependent on the number of '.' tokens in the search string.
Parameters
namepath to child. This may be a single name or a dotted path refering to a node several levels below this node.
must_existIf true, requires the child to exist by throwing an exception if it does not. If false, allows the method to return nullptr when no child is found.
Returns
A valid TreeNode* if child is found by name. If child cannot be found and must_exist==true, throws SpartaException. Otherwise returns nullptr.
Note
no pattern matching supported in this method
if a name matches on both an alias and a TreeNode name, the TreeNode name will take precedence
Exceptions
SpartaExceptionif child is not found and must_exist==true

Example:

assert(node.getName() == "root");
assert(node.getChild("a.b.c").getName() == "c");

Definition at line 1531 of file TreeNode.hpp.

◆ getChild() [2/2]

const TreeNode * sparta::TreeNode::getChild ( const std::string &  name,
bool  must_exist = true 
) const
inline

Overloaded const-qualified.

Definition at line 1538 of file TreeNode.hpp.

◆ getChildAs() [1/4]

template<class T , typename = typename std::enable_if<std::is_pointer<T>::value>::type>
T sparta::TreeNode::getChildAs ( const std::string &  name,
bool  must_exist = true 
)
inline

Definition at line 1634 of file TreeNode.hpp.

◆ getChildAs() [2/4]

template<class T , typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
T * sparta::TreeNode::getChildAs ( const std::string &  name,
bool  must_exist = true 
)
inline

Definition at line 1655 of file TreeNode.hpp.

◆ getChildAs() [3/4]

template<class T , typename = typename std::enable_if<std::is_pointer<T>::value>::type, class ConstT = typename ptr_to_const_obj_ptr<T>::type>
const ConstT sparta::TreeNode::getChildAs ( const std::string &  name,
bool  must_exist = true 
) const
inline

Retrieves a child that is castable to T with the given dotted path.

Template Parameters
TType of child expected
Parameters
nameName of child. May be a dotted path indicating multiple levels of device-tree traversal.
must_existIf true, Causes an exception to be thrown if no child by this name could be found. If false, a nullptr is returned. Finding a child and failing to cast to T always causes an exception to be thrown
Returns
T* if a child of the correct name is found and it was castable to T* using dynamic_cast. If child cannot be found and must_exist==true, throws SpartaException. Otherwise returns nullptr.
Note
no pattern matching supported in this method, but dotted paths are acceptable.
Exceptions
SpartaExceptionif must_exist==true and either the child by the given name (path) could not be found or the found node was not castable to T

Definition at line 1606 of file TreeNode.hpp.

Here is the call graph for this function:

◆ getChildAs() [4/4]

template<class T , typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
const T * sparta::TreeNode::getChildAs ( const std::string &  name,
bool  must_exist = true 
) const
inline

Definition at line 1628 of file TreeNode.hpp.

◆ getChildAt()

TreeNode * sparta::TreeNode::getChildAt ( uint32_t  idx) const

Gets a child at a position in the children vector in the order in which they were added to this node.

Warning
Do not use this method for iterating child nodes for the purpose of searching. Use getChild* and findChildren* methods instead.
Exceptions
SpartaExceptionif idx is out of range.

This method is for iteration-purposes only (so that wrappers may avoid STL). The index used here is NOT a consistent property with any TreeNode or Resource.

◆ getChildren() [1/2]

const ChildrenVector sparta::TreeNode::getChildren ( ) const

Gets a vector of all children of this node in any group in the order in which they were added to this node.

Note
This is a const vector matching the order and content of the internal child list.
Warning
Do not use this method for iterating child nodes for the purpose of searching. Use getChild* and findChildren* methods instead.
Returns
const vector of TreeNode* children
Warning
This will only return the public children. Private children must be accessed via the TreeNodePrivateAttorney available to the framework for traversing the entire tree, public and private.

◆ getChildren() [2/2]

uint32_t sparta::TreeNode::getChildren ( std::vector< TreeNode * > &  results,
bool  ignore_builtin_group = true,
bool  ignore_anonymous_nodes = true 
)

Gets all children of this node in the order in which they were added to this node.

Parameters
resultsVector to which all children will be appended. This vector is not result.
ignore_builtin_groupIgnore any children in group GROUP_NAME_BUILTIN.
ignore_anonymous_nodesIgnore any children in group GROUP_NAME_
Returns
Number of children found
Warning
This will only return the public children. Private children must be accessed via the TreeNodePrivateAttorney available to the framework for traversing the entire tree, public and private.

◆ getChildrenIdentifiers()

uint32_t sparta::TreeNode::getChildrenIdentifiers ( std::vector< std::string > &  idents,
bool  ignore_builtin_group = true 
) const

Gets all child identifiers, aliases, group names, and group-aliases which can be used to refer to a child of this node.

Parameters
identsVector to fill with new identities. Vector is not cleared.
ignore_builtin_group=trueIf true, rejects the builtin group.
Returns
Number of identifiers added to idents
Postcondition
idents will be cleared and populated with names, aliases, and group names within this node.
Note
Order of names retrieved should be considered random. Ordering is subject to change between calls due to use of a hash map internally.
Warning
Groups cannot currenly be retrieved by getChild. Do not iterate these idents and invoke getChild.
Todo:
Allow groups to be retrieved witih getChild
Note
This method copies many strings. It should not be considered fast.
Anonymous children names will not appear in this list. Their group and aliases will, however.

This is useful for shell completion when browsing the children of a node.

◆ getChildrenOfType()

template<class T >
uint32_t sparta::TreeNode::getChildrenOfType ( std::vector< T * > &  results) const
inline

return all the children matching a particular type using dynamic cast.

Warning
This will only return the public children. Private children must be accessed via the TreeNodePrivateAttorney available to the framework for traversing the entire tree, public and private.

Definition at line 1136 of file TreeNode.hpp.

Here is the call graph for this function:

◆ getClock() [1/2]

const Clock * sparta::TreeNode::getClock ( ) const
inline

Definition at line 2053 of file TreeNode.hpp.

◆ getClock() [2/2]

Clock * sparta::TreeNode::getClock ( )
inlineoverridevirtual

Walks up parents (starting with self) until a parent with an associated local clock is found, then returns that clock.

Returns
The clock of the first ancestor (including self) which has a valid clock through getLocalClock. If no ancestor has a clock, returns nullptr
See also
getLocalClock

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Implements sparta::ResourceContainer.

Definition at line 2033 of file TreeNode.hpp.

Here is the call graph for this function:

◆ getDeepestMatchingPath()

std::string sparta::TreeNode::getDeepestMatchingPath ( const std::string &  path) const

Gets the deepest whole node location starting from this node that matches some part of path starting at its beginning.

Parameters
pathPath to node relative this this node.
Returns
Dotted node path to the deepest ancestor of this node whose location matches path from the beginning. If the node described by path exists, returns the a path to the node identified by path. Note that the returned string could differ in this case if path contained aliases.
Warning
This is an expensive operation as it is a recursive search. It should not be called at run-time.

Ths intent of this is to find out where a path given by a user (e.g. configuration file) diverged from the actual tree for feedback purposes

◆ getDelegatesRegisteredForNotification()

void sparta::TreeNode::getDelegatesRegisteredForNotification ( const std::type_info &  tinfo,
const std::string *  name,
std::vector< delegate > &  dels 
)
noexcept

Gets the vector of delegates registered for a notification on this TreeNode.

Parameters
tinfotypeid of the notification to be queried
nameName of the notification to be queried (Can be "" to ignore name)
delsVector to which all found delegates matching search parameters will be appended. This vector is not cleared

◆ getDesc()

const std::string & sparta::TreeNode::getDesc ( ) const

Gets the description of this node.

Returns
string description of this node

◆ getDisplayLocation()

std::string sparta::TreeNode::getDisplayLocation ( ) const

Returns the location of this node in the device tree which might not be usable for navigating the device tree (it cannot be used as an argument for getChild/findChildren).

Returns
Location string that is nice for presentation, even if not progamatically useful in the getChild/findChildren methods.

This differs from getLocation by representing nodes with groups and no names as "group[group_index]" instead of "name". This string cannot currently be used to find children by pattern or name because it refers to a group.

A motifivation for this method is to allow identification of elements in anonymous buffers and queue resources to simulator tools.

◆ getExtension()

ExtensionsBase * sparta::TreeNode::getExtension ( const std::string &  extension_name)

Get an extension object by type string. Returns nullptr if not found (unrecognized).

Parameters
extension_nameThe name of the extension to find

◆ getGroup() [1/2]

const std::string & sparta::TreeNode::getGroup ( ) const

Gets the group name of this node.

Returns
string group name of this node
See also
GROUP_NAME_NONE

◆ getGroup() [2/2]

uint32_t sparta::TreeNode::getGroup ( const std::string &  group,
std::vector< TreeNode * > &  results 
)

Gets all nodes in a child group.

Parameters
groupName of group to get children from. If GROUP_NAME_NONE, will retrieve only children with group=GROUP_NAME_NONE.
resultsVector of nodes to which results will be appended.
Returns
Number of nodes found in the group
Todo:
Optimize lookup by group using mappings

To get all children regardless of group, use getChildren

◆ getGroupIdx()

group_idx_type sparta::TreeNode::getGroupIdx ( ) const

Gets the group index of this node.

Returns
string group index of this node
See also
GROUP_IDX_NONE

◆ getGroupIndexMax()

group_idx_type sparta::TreeNode::getGroupIndexMax ( const std::string &  group)

Gets the largest index of a node in the given group.

Parameters
groupName of group to get the index from.
Returns
Largest group index in the given group, including anonymous nodes. If group is GROUP_NAME_NONE, searches for nodes with that group name (not in a group). If there are no nodes in the chosen group, returns GROUP_NAME_NONE.
Todo:
Optimize this count by storing group mappings

◆ getGroupNamePtr()

const std::string * sparta::TreeNode::getGroupNamePtr ( ) const

Gets the group name string pointer (interned in StringManager singleton) of this node.

Returns
string pointer to group name of this node which can be compared with other strings interned in StringManager
See also
GROUP_NAME_NONE

◆ getGroupSize()

uint32_t sparta::TreeNode::getGroupSize ( const std::string &  group)

Gets the number of nodes in a group.

Parameters
groupName of group to get children from. If GROUP_NAME_NONE, will retrieve only children with group=GROUP_NAME_NONE.
Returns
Number of children in this group, including anonymous nodes. Aliases do not affect this result
Todo:
Optimize this count by storing group sizes (or group vectors) in TreeNode.

To count all children regardless of group, use getNumChildren

◆ getIdentifiers()

std::vector< const std::string * > sparta::TreeNode::getIdentifiers ( ) const

Gets all the identifiers for this node (excluding groups)

Returns
A vector of string pointers. Elements are guaranteed to be non-null
Warning
These identifiers are pointers to strings in members and vectors of this TreeNode instance. Altering the name or aliases or group of this Node will invalidate the result vector of this call
The returned vector is re-built each call

◆ getLevel()

uint32_t sparta::TreeNode::getLevel ( ) const

Gets the level of this node. 0 is root.

Warning
This can change when the node is connected to a tree. Generally, this should only be queried once the Tree has exited the TREE_FINALIZED phase because level cannot cahnge after finalization. (see isFinalized)

This is computed based on the number of parents iterated until a node with no parents is reached.

◆ getLocalClock() [1/2]

Clock * sparta::TreeNode::getLocalClock ( )
inline

Gets the clock associated directly with this Node. This is useful for configuration and simulator debug, but not at run-time.

Note
In general, it is preferable to use getClock to find the closest attached clock in this Node's ancestry.
Returns
Clock directly attached to this Node (if any). Returning nullptr means no attached clock, however this Node is considered to be within the nearest ancestor's clock. getClock will find nearest ancestor's clock (or local clock, if present)

By default TreeNodes are not associated (or required to be associated) with a sparta::Clock. Subclasses may require this, however.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 2083 of file TreeNode.hpp.

◆ getLocalClock() [2/2]

const Clock * sparta::TreeNode::getLocalClock ( ) const
inline

Definition at line 2090 of file TreeNode.hpp.

◆ getLocation()

std::string sparta::TreeNode::getLocation ( ) const
finaloverridevirtual

◆ getName()

const std::string & sparta::TreeNode::getName ( ) const
overridevirtual

Gets the name of this node.

Returns
string name of this node

Implements sparta::PhasedObject.

◆ getNamePtr()

const std::string * sparta::TreeNode::getNamePtr ( ) const

Gets the name of this node's string pointer which isinterned in StringManager)

Returns
String pointer. Guaranteed not to be null

◆ getNextName()

static std::string sparta::TreeNode::getNextName ( const std::string &  name,
size_t &  pos 
)
static

Gets the next name between two '.' chars in a string starting at pos.

Parameters
nameName string to parse
posPosition in name to begin parsing. Will be updated to location of the next '.' found plus 1.
Returns
String between pos and the next '.' found.

Used for parsing tree paths:

size_t pos = 4;
assert(getNextName("top.a.b.c", pos) == 'a');
assert(pos == 6);
static std::string getNextName(const std::string &name, size_t &pos)
Gets the next name between two '.' chars in a string starting at pos.

◆ getNumChildren()

uint32_t sparta::TreeNode::getNumChildren ( ) const

Gets the number of children that this node has including those in the sparta builtins group.

Returns
Integer representing number of children in any group.
Warning
This will only return the public children. Private children must be accessed via the TreeNodePrivateAttorney available to the framework for traversing the entire tree, public and private.

◆ getParent() [1/2]

TreeNode * sparta::TreeNode::getParent ( )
inlinevirtual

Gets immediate parent of this node if one exists.

Returns
parent TreeNode if there is one. Otherwise returns 0.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Reimplemented in sparta::GlobalTreeNode, sparta::RootTreeNode, and sparta::VirtualGlobalTreeNode.

Definition at line 965 of file TreeNode.hpp.

◆ getParent() [2/2]

virtual const TreeNode * sparta::TreeNode::getParent ( ) const
inlinevirtual

Definition at line 972 of file TreeNode.hpp.

◆ getParentAs() [1/4]

template<class T , typename = typename std::enable_if<std::is_pointer<T>::value>::type>
T sparta::TreeNode::getParentAs ( bool  must_exist = true)
inline

Definition at line 1010 of file TreeNode.hpp.

◆ getParentAs() [2/4]

template<class T , typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
T * sparta::TreeNode::getParentAs ( bool  must_exist = true)
inline

Definition at line 1024 of file TreeNode.hpp.

◆ getParentAs() [3/4]

template<class T , typename = typename std::enable_if<std::is_pointer<T>::value>::type>
const T sparta::TreeNode::getParentAs ( bool  must_exist = true) const
inline

Retrieves a parent casted to type T* if this node has a parent.

Template Parameters
TType of parent to cast to
Parameters
must_existIf true, Causes an exception to be thrown if node has no parent or the parent cannot be dynamically cast to T*. If false, a nullptr is returned when this node has no parent that can be cast to T*.
Returns
Parent as a T* if the parent exists and was castable to T* using dynamic_cast. If this node has no parent which can be cast to T*, and must_exist == true, throws. Otherwise, returns nullptr
Exceptions
SpartaExceptionif must_exist==true and the parent was null or the parent could not be cast to a T*.

Definition at line 990 of file TreeNode.hpp.

Here is the call graph for this function:

◆ getParentAs() [4/4]

template<class T , typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
const T * sparta::TreeNode::getParentAs ( bool  must_exist = true) const
inline

Definition at line 1004 of file TreeNode.hpp.

◆ getPossibleNotifications()

uint32_t sparta::TreeNode::getPossibleNotifications ( std::vector< NotificationInfo > &  infos) const

Gets information on the possible notifications generated by this node (excludes children).

Parameters
infosVector of notification inormation to which this node's information will be added
Returns
Number of infos appended to the infos vector.
Postcondition
infos has NotificationInfo instances appended. Original content remains in place. Vector can only grow.

◆ getPossibleSubtreeNotifications()

uint32_t sparta::TreeNode::getPossibleSubtreeNotifications ( std::vector< NotificationInfo > &  infos) const
noexcept

Gets information on the possible notifications generated by this node and all its descendants.

Parameters
infosVector of notification information to which this node's information will be added
Returns
Number of infos appended to the infos vector
Postcondition
infos has NotificationInfo instances appended from this node and all descendants. Vector can only grow.

◆ getPreviousName_()

static std::string sparta::TreeNode::getPreviousName_ ( const std::string &  name,
size_t &  pos 
)
staticprotected

Gets the previous name between two '.' chars in a string starting at pos.

Parameters
nameName string to parse
posPosition in name to begin parsing in reverse. Must coincide with a '.' or end of string. Will be updated to location of the next '.' found. Set to npos if the beginning of the string is reached. To start parsing a string from the end, should be set to length of string.
Returns
String between (excluding) pos and the '.' found earlier in the string.

Used for parsing tree paths:

size_t pos = 5;
assert(getPreviousName_("top.a.b.c", pos) == 'a');
assert(pos == 3);
static std::string getPreviousName_(const std::string &name, size_t &pos)
Gets the previous name between two '.' chars in a string starting at pos.

◆ getRecursiveNodeCount()

template<typename T >
uint32_t sparta::TreeNode::getRecursiveNodeCount ( ) const
inline

Recursively gets the count of a nodes that are a subclass of a particular type (determined by dynamic_cast). Includes all descendants of this node in the tree, but excludes this node.

Definition at line 1854 of file TreeNode.hpp.

◆ getRoot()

TreeNode * sparta::TreeNode::getRoot ( )
virtual

Gets farthest ancestor of this node.

Returns
farthest ancestor TreeNode. May be this if node has no parent. Return value will never be nullptr
Note
returned TreeNode may not be an actual RootTreeNode

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ getScopeRoot() [1/2]

TreeNode * sparta::TreeNode::getScopeRoot ( )

Returns the root of the scope that this tree node is in.

◆ getScopeRoot() [2/2]

const TreeNode * sparta::TreeNode::getScopeRoot ( ) const

Returns the root of the scope that this tree node is in.

◆ getSimulation()

app::Simulation * sparta::TreeNode::getSimulation ( ) const

Gets the simulation (if any) associated with this tree.

Precondition
This node should be attached (isAttached) or this will return nullptr
Note
Function gets RootTreeNode of tree and asks it for Simulation pointer (if any)

◆ getTags()

const std::vector< const std::string * > & sparta::TreeNode::getTags ( ) const

Gets the set of tags associated with this TreeNode.

Note
This cannot change after finalization
Returns
const vector of const string pointers, which will never be null. These tags are stored as pointers into strings held by StringManager to save space and often improve comparison speed

Tags are useful for associating meta-data with a TreeNode and forming virtual groupings of nodes independent of hierarchy. For example, all nodes (e.g. counters and notification sources) having to do with power-modeling may have "power" tags indicating presence in a virtual "power" group.

◆ getVirtualGlobalNode()

static TreeNode * sparta::TreeNode::getVirtualGlobalNode ( )
static

Gets the virtual global node singleton. This node can have no parent and no children. It receives notifications from all nodes in the simulator as if it were the parent of every node in the simulation that has no parent.

Note
Caller must not delete this node.

This node is typically used to add logging taps that receive messages before the entire device tree hierarchy is defined. This allows warning messages from a newly-constructed node to be sent somewhere, even before that node is part of any device tree.

◆ getWeakPtr()

WeakPtr sparta::TreeNode::getWeakPtr ( )

Gets a weak pointer to this TreeNode. This weak pointer is guaranteed to expire when this TreeNode is destructed unless locked.

Returns
weak_ptr to this TreeNode. Guaranteed not to be expired at this time.
Warning
Do not store the shared_ptr result of a call to sparta::TreeNode::WeakPtr::lock because it will prevent weak references to this shared pointer from expiring when the TreeNode is actually deleted. Having a shared pointer to this node will NOT prevent its destruction

Example

TreeNode::WeakPtr wp = node->getWeakPtr();
...
if(!wp.expired()){ // Is weak pointer valid (node not yet deleted)
wp.lock()->getName(); // lock converts to shared pointer for use.
// Shared pointer is nullptr if p is dead.
}
std::weak_ptr< TreeNode > WeakPtr
Weak pointer to a TreeNode. Acquire with getWeakPtr.
Definition TreeNode.hpp:266

◆ hasChild()

bool sparta::TreeNode::hasChild ( const std::string &  name) const
inlinenoexcept

Determines if a child can be found with the given dotted path.

Parameters
nameDotted path to child
Note
no pattern matching supported in this method. Child-finding behavior is the same as getChild
Returns
true if the child can be found, false if not.
See also
getChild

Definition at line 1571 of file TreeNode.hpp.

◆ hasImmediateChild()

bool sparta::TreeNode::hasImmediateChild ( const TreeNode n) const
noexcept

Determines if the node n is an immediate child of this node.

Parameters
nNode to test for child-ness of this
Returns
true if n is an immediate child; false if not.

◆ hasObserversRegisteredForNotification()

bool sparta::TreeNode::hasObserversRegisteredForNotification ( const std::type_info &  tinfo,
const std::string *  name 
) const
noexcept

Determines if this TreeNode (not descendants) has any observers for this type of event and name.

Parameters
tinfotypeid of the notification to be queried
nameName of the notification to be queried (Can be "" to ignore name)

◆ hasTag()

bool sparta::TreeNode::hasTag ( const std::string *  interned_tag_name) const

Does this node have a specific tag (by string pointer interned with StringManager). This is faster than the alternate hasTag method because it relies only on pointer comparisons.

Parameters
[in]interned_tag_nameTag pointer. Caller must get this pointer argument from sparta StringManager or it may not match

◆ hasWildcardCharacters()

static bool sparta::TreeNode::hasWildcardCharacters ( const std::string &  name)
static

Determines if a given node name has any wildcard characters which will be substituted in createSearchRegexPattern.

This is useful for identifying which nodes are patterns and which are concrete node names. It is important to keep this in ssync with createSearchRegexPattern

◆ identityMatchesPattern_()

static bool sparta::TreeNode::identityMatchesPattern_ ( const std::string &  ident,
std::regex &  expr,
std::vector< std::string > &  replacements 
)
staticprotected

Performs pattern matching on a identity string.

Parameters
identRegex identity. This could be generated from an input glob pattern
exprExpression to compare against ident
replacementsReturns each captured replacement of a in the expression

◆ invokeDelegatesOn_()

template<typename DataT >
void sparta::TreeNode::invokeDelegatesOn_ ( TreeNode to_invoke,
const DataT &  data,
const std::string *  name_id 
)
inlineprotected

Protected wrapper for invokeDelegates_ which allows a TreeNode to invoke delegates on another TreeNode using itself as the origin.

Parameters
to_invokeTreeNodes whose delegates will be invoked (those which are appropriate for the specified DataT and name_id)

See invokeDelegates_ for other argument semantics

Definition at line 3250 of file TreeNode.hpp.

◆ isAnonymous()

bool sparta::TreeNode::isAnonymous ( ) const

Is this node anonymous.

Returns
true if node is anonymous

◆ isAttached()

virtual bool sparta::TreeNode::isAttached ( ) const
inlinevirtual

Is this node part of a device tree with a proper RootTreeNode at the root.

Returns
true if node is a child of a RootTreeNode regardless of how many tree levels separate them

Reimplemented in sparta::GlobalTreeNode, sparta::RootTreeNode, and sparta::VirtualGlobalTreeNode.

Definition at line 957 of file TreeNode.hpp.

◆ isBuiltin()

bool sparta::TreeNode::isBuiltin ( ) const

Is this node in the builtins group.

Returns
true if this node is in the GROUP_NAME_BUILTIN group.

◆ isDescendantOf()

bool sparta::TreeNode::isDescendantOf ( const TreeNode ancestor,
int32_t  max_depth = -1 
) const

Determines if this node is a descendant of the specified ancestor node within some number of generations (depth).

Parameters
ancestorTreeNode that will be tested for being a parent this TreeNode
max_depthMaximum depth (distance) between ancestor and this node that will allow this test to return true. A more distance ancestor/descendant relationship will cause this method to false. A max depth of 0 implies this node and ancestor must be the same node, a max_depth of 1 means that the ancestor must be an immediate parent or self, 2 means parent of parent or closer, and so on. max_depth of -1 means no limit.

◆ isExpired()

bool sparta::TreeNode::isExpired ( ) const

Is this expired (i.e. has it been the rhp of a move constructor)

Returns
true if node is expired

◆ isHidden()

bool sparta::TreeNode::isHidden ( ) const

Is this TreeNode supposed to be hidden during tree printouts This value does not have to be respected by anything using TreeNode and is mainly a UI/printout convenience.

Defaults to false at construction

◆ isNodeConstructed()

static bool sparta::TreeNode::isNodeConstructed ( const TreeNode )
static

Is a given node constructed?

Note
This is used for debugging double-frees

◆ isScopeRoot()

bool sparta::TreeNode::isScopeRoot ( ) const
inline

Returns true if this tree node is a scope root

Definition at line 2017 of file TreeNode.hpp.

◆ locateNotificationSources()

template<typename DataT = ANY_TYPE>
uint32_t sparta::TreeNode::locateNotificationSources ( std::vector< TreeNode * > &  nodes,
const std::string &  name = "" 
)
inline

Gets all possible notification info from NotificationSources within this node's subtree.

Template Parameters
DataTtype of data for which to search. This must be non-const, non-volatile, non-pointer, and non-reference.
Parameters
nodesResult set of nodes to which all found nodes will be appended. This vector is not cleared.
nameName of the NotificationSource to search for. Specifying "" locates any sourcee matching on DataT.

Example:

// Find any nodes that may post the sparta::Register::PostWriteAccess
// type regardless of the notification name.
std::vector<sparta::TreeNode*> results;
node->locateNotificationSources<sparta::Register::PostWriteAccess>(nodes);
// Find any nodes that may post any data structure with the notification
// name "post_write"
std::vector<sparta::TreeNode*> results;
node->locateNotificationSources(nodes, "post_write");
\code
// Find all notification sources at node or below
std::vector<sparta::TreeNode*> results;
node->locateNotificationSources(nodes);
Structure containing data for a Register post-write notification.
Definition Register.hpp:483

Definition at line 3444 of file TreeNode.hpp.

Here is the call graph for this function:

◆ locationMatchesPattern()

bool sparta::TreeNode::locationMatchesPattern ( const std::string &  pattern,
const TreeNode pat_loc 
) const

Determines if the given pattern (which may contain wildcards) can describe this node.

Parameters
patternPattern to compare this node's location against. This pattern CANNOT have any upward traversal (parent references).
pat_locTreeNode representing the starting point of pattern. This pat_loc node must be AT or ABOVE *this in the tree, otherwise this method will always report false.
Note
A surefire (but slower) way to implement this is to perform findChildren with the inputs and search the result set for *this. It is NOT trivial to write simple downward traversing comparison as one might expect because patterns can go down and then up. All of the paths downward must be tried even if they do not contain *this because a down,down,up,up,down pattern could go into a subtree which does not contain the target *this, but later come back up and then back down to *this.
This is not able to cross virtual parent-child relationships (e.g. in VirtualGlobalNode)
Exceptions
SpartaExceptionif pattern contains upward traversal

Example:

// RootTreeNode* r
// Created TreeNode* n
assert(n->getRoot() == r);
assert(n->getLocation() == "top.cpu0.regs");
assert(n->locationMatchesPattern("t?p.cpu*.regs", r) == true);
assert(n->locationMatchesPattern("", n) == true);

◆ lockdownParameters()

void sparta::TreeNode::lockdownParameters ( )
inline

Method to put the device tree in lockdown phase. All LOCKED and HIDDEN parameters are frozen after this point. Regular parameters are not affected by this phase. This method requires a Simulation pointer and will assert at compile time if anyone tries to lockdown the tree without the context of a Simulation.

Lockdown the tree node if Simulation is valid

Definition at line 430 of file TreeNode.hpp.

Here is the call graph for this function:

◆ makeSubtreePrivate()

void sparta::TreeNode::makeSubtreePrivate ( )
inline

Make the entire subtree private.

This will add 1 to privacy_level_ for every node below, this means it should work if B->C, where C is private on B, and B is added as a private child of A, A.privacy_level_ = 0, B.privacy_level_ = 1, C.privacy_level_ = 2 (C.privacy_level_ was previously == 1).

See documentation for the privacy_level_ variable to really understand what this is doing and why.

Definition at line 2000 of file TreeNode.hpp.

◆ matchesGlobLike()

static bool sparta::TreeNode::matchesGlobLike ( const std::string &  pattern,
const std::string &  other 
)
static

Determine if a glob-like search pattern matches some other string.

Parameters
[in]patternGlob-like pattern to search with. This is standard SPARTA tree identifier pattern syntax
[in]otherOther string with which pattern is being compared
Returns
true if pattern matches other, false if not.

◆ notificationCategoryMatch()

static bool sparta::TreeNode::notificationCategoryMatch ( const std::string *  query_id,
const std::string *  node_id 
)
static

Checks if two notification categories match where one is an actual category.

Parameters
[in]query_idpointer to StringManager interned string which may be a single category or a glob-like pattern. If StringManager.EMPTY, matches all patterns.
[in]node_idconcrete category. This is a name, not a pattern.

◆ parseNotificationNameString()

static std::vector< const std::string * > sparta::TreeNode::parseNotificationNameString ( const std::string &  csl)
static

Parses a comma-separated list of notification names (or patterns) separated by commas and ignoring whitespace around commas.

Parameters
[in]cslComma-separated list (e.g. "a,b,foo*"). Most common case will be a single name with no commas
Returns
List of interned string pointers (through sparta::StringManager)

◆ postPropagatingNotification_()

template<typename DataT >
void sparta::TreeNode::postPropagatingNotification_ ( const TreeNode origin,
const DataT &  data,
const std::string *  name_id 
)
inlineprotected

Starts a notification propagating up the tree.

Parameters
name_idPointer to interned name in StringManager. Compared against delegate name. The pointer is treated like a numeric ID for comparison.
Note
Invokes propagateNotification_ on this node after validating, then invokes propagateNotification_ on the global virtual node.

Definition at line 3091 of file TreeNode.hpp.

Here is the call graph for this function:

◆ recursGetDeepestMatchingPath_()

std::pair< uint32_t, std::string > sparta::TreeNode::recursGetDeepestMatchingPath_ ( const std::string &  path,
size_t  name_pos 
) const
protected

Finds the deepest node path mathing the input path. Implements getDeepestMatchingPath.

Returns
pair containing <match depth, match path> relative to this node

◆ registerForNotification() [1/2]

template<typename DataT , typename T , void(T::*)(const TreeNode &, const TreeNode &, const DataT &) TMethod>
void sparta::TreeNode::registerForNotification ( T *  obj,
const std::string &  name,
bool  ensure_possible = true 
)
inline

Registers a callback method to listen for all notifications having the specified data type DataT and name (or any name if name is "") occuring on this node or any descendant (subtree).

Note
Some parameters of this method can be automatically filled-in using the REGISTER_FOR_NOTIFICATION macro.
Template Parameters
DataTType of data object given to the notification callback function registered. This type must be a C++ typename of a type which is copyable, non-const, non-reference, and non-pointer. Useful values for this type can be found by locating sparta::NotificationSource nodes throughout the device tree and then by looking at sparta::NotificationSource::getNotificationTypeName. Note that ANY_TYPE is not a valid argument for DataT.
TClass of object on which callback member function will be invoked.
TMethodmember function pointer of class T that will be invoked when the specified notification is posted. This member function signature must be:
ClassName::func(// TreeNode from which the notification originated
const TreeNode& origin_node,
// TreeNode at which the notifications was observed, causing this callback
const TreeNode& observation_node,
// Notification event data
const datat& data)
Node in a composite tree representing a sparta Tree item.
Definition TreeNode.hpp:205
Parameters
nameName of notification being observed. If name is "", all notifications having a data type of DataT will cause this callback to be notified. Locating a notificationSource in the device tree and and using sparta::NotificationSource::getNotificationName can help to determine useful values for name.
ensure_possibleIf true, this method will check that one or more nodes in this node's subtree can generate the notification described by DataT and name. If false, this test is not performed.
Exceptions
SpartaExceptionif a ensure_possible=true and a registration is made on a DataT/name combination that cannot be posted by this the node's subtree (since there are no ancestor NotificationSource nodes).
Note
Cannot re-register with same arguments.
Todo:
Faster attachment of delegates to children. There is notable performance impact today, however.
Note
This method is potentially slow because all children may be walked to build a notification shortcut list, which is an optimization for the performance-critical notification-posting code
See also
REGISTER_FOR_NOTIFICATION

NotificationSources can be located throughout the simulation using the sparta::TreeNode::locateNotificationSources method.

The methods getPossibleSubtreeNotifications and dumpPossibleSubtreeNotifications can assist in finding NotificationSource nodes in the device tree.

Example:

struct MyClass {
void func(// TreeNode from which the notification originated
const TreeNode& origin_node,
// TreeNode at which the notifications was observed, causing this callback
const TreeNode& observation_node,
// Notification event data
const datat& data)
void func(const TreeNode&, const TreeNode&, const SomeData&) {}
}
// ...
MyClass my_class;
// ...
// Given NotificationSource<struct SomeData> node;
node->registerForNotification<MyClass, &MyClass::func>(my_class);
// ...
node->deregisterForNotification<MyClass, &MyClass::func>(my_class);

Definition at line 3671 of file TreeNode.hpp.

◆ registerForNotification() [2/2]

template<typename DataT , typename T , void(T::*)(const DataT &) TMethod>
void sparta::TreeNode::registerForNotification ( T *  obj,
const std::string &  name,
bool  ensure_possible = true 
)
inline

Definition at line 3678 of file TreeNode.hpp.

◆ removeChildForTeardown_()

void sparta::TreeNode::removeChildForTeardown_ ( TreeNode child)
protected

"Removes" the given child by invoking onDestroyingChild_ then removing this child from the children_ list

Precondition
Must be in teardown phase if this node is attached (isAttached)
Parameters
childChild to remove from this node. Must actually be a current child of SpartaException is thrown
Warning
It is not currently safe to continue accessing a tree from which a child was removed. This is a teardown utility for breaking parent-child references which can confuse the notification system during random-order desstruction of the tree. This method DOES NOT allow removal of nodes at runtime because it does not erase all traces of the child. For example, the name map will still exist with dangling pointers. A more thorough removal method is required to actually support removal
Note
This method does not care about phase. Presuably it will only be called from TreeNode destructors, which will detect any phase problems.
Exceptions
SpartaExceptionif child is not an actual child of this node

◆ removeFromParentForTeardown_()

void sparta::TreeNode::removeFromParentForTeardown_ ( TreeNode parent)
protected

Protected Wrapper for getParent()->removeChildForTeardown_ which allows subclases of TreeNode to indirectly invoke removeChildForTeardown_ with themselves as the argument.

Parameters
parentParent to remove this child from. Must be this TreeNode's parent. Must not be nullptr

◆ renderSubtree()

std::string sparta::TreeNode::renderSubtree ( int32_t  max_depth = -1,
bool  show_builtins = false,
bool  names_only = false,
bool  hide_hidden = false,
bool(*)(const TreeNode *)  leaf_filt_fxn = nullptr 
) const

Renders the subtree starting at this node as a string containing an indentation-based depth-first representation.

Returns
std::string representing the subtree.
Parameters
max_depthNumber of levels below this Node to traverse. 0 means this node only. Negative depth means no limit.
show_builtinsWhen false, hides all TreeNodes in the GROUP_NAME_BUILTIN group. If true, shows all nodes
names_onlyWhen true, renders names of nodes. Otherwise, renders string representation of nodes prints only this node.
hide_hiddenHides any nodes (and their subtrees) maked as hidden
leaf_filt_fxnFiltering function. If nullptr, has no effect. If not nullptr, this function is invoked on each LEAF node encountered to determine whether it should be displayed. If this function returns false, the leaf node is not rendered. If true, the leaf node is rendered. Non-leaf nodes are not subject to filtering, but will be omitted if they contain no leaves (at any depth) which pass the leaf filter function. Note that max_depth prohibits recursion past a certain depth, so nodes may not be shown even if they have ancestor leaves that would be visible (according to the filter) but are below the max_depth threshold.

◆ setClock()

virtual void sparta::TreeNode::setClock ( const Clock clk)
virtual

Assigns a clock to this node. This clock will then be accessed by any descendant which has no assigned clock or an ancestor with an assigned clock between that descendant and this node. getClock returns the Clock associated with the nearest ancestor.

Parameters
clkClock to assign. Must not be null.
Precondition
Must be in the TREE_BUILDING phase
Can only assign a non-NULL value once

Reimplemented in sparta::RootTreeNode.

◆ setExpectedParent_()

void sparta::TreeNode::setExpectedParent_ ( const TreeNode parent)
protected

Tracks a node as an expected parent without actually adding this node as a child. This is used almost exclusively for printing error messages which include a device-tree location BEFORE actually inserting this node into the device tree since node construction can fail.

Parameters
parentParent TreeNode that will act as the parent for the purposes of printing device-tree location for this node.
Precondition
Tree cannot already have a parent. It makes no sense to set an expected parent if the node alreay has a parent.
Postcondition
sparta::TreeNode::getLocation will reflect the location of this node as if it is part of the tree under the specified parent
Note
the expected parent node does not know about this instance.
An expected parent does not cause this node to behave as if it is part of a tree except when printing a location.
The expected parent will be set to nullptr once an actual parent is set through setParent_.

Typical usage is to invoke this at the very beginning of the constructor of a sparta::TreeNode subclass. This allows sparta::TreeNode::getLocation to function as if this node were actually part of a tree. After successful construction, addChild can be used to connect this node to a parent in the device tree. At that time, the expected parent is set back to nullptr.

Using an expected parent for the purposes of printing a device-tree location during construction is much cleaner and simpler than adding a child node to some parent and then trying to remove it if something goes wrong during construction.

◆ setScopeRoot()

void sparta::TreeNode::setScopeRoot ( )
inline

Make this tree node the root of a scope

Definition at line 2008 of file TreeNode.hpp.

◆ simulationTerminating_()

void sparta::TreeNode::simulationTerminating_ ( )
protected

Hook to allow simulation resources to clean-up before simulation is ended.

Precondition
Simulator will be in a state earlier than TREE_TEARDOWN phase
Note
The entire resource tree is accessible. Nothing has been destructed yet
The simulator will not continue to run for this device tree at this point.
This call may be followed by dumpDebugContent_ depending on the configuration of the simulator and any errors encountered.
This call will be eventually followed by onEnteringTeardown_ unless the application is corrupted or hard-terminated (i.e. std::terminate, exit call, or exception in a destructor when unwinding)
Exceptions
Anyexceptions related to post-run state

◆ stringize()

virtual std::string sparta::TreeNode::stringize ( bool  pretty = false) const
inlinevirtual

Create a string representation of this node.

Parameters
prettyPrint a more verbose, multi-line representaiton (if available).
Returns
string representation of this node "<" <location> ">"
Note
this representation contains some basic information and is not meant for deserialization.

Subclasses should override this with representations appropriate for their type.

Reimplemented in sparta::CounterBase, sparta::EventSet, sparta::RegisterBase::Field, sparta::Register, sparta::RegisterSet, sparta::log::MessageSource, sparta::NotificationSourceBase, sparta::memory::BlockingMemoryIFNode, sparta::ExportedPort, sparta::Clock, sparta::DynamicResourceTreeNode< ResourceT, ParamsT >, sparta::GlobalTreeNode, sparta::ParameterBase, sparta::ParameterSet, sparta::ResourceTreeNode, sparta::RootTreeNode, sparta::Counter, sparta::CycleCounter, sparta::ReadOnlyCounter, sparta::StatisticDef, sparta::StatisticSet, and sparta::Port.

Definition at line 723 of file TreeNode.hpp.

Here is the call graph for this function:

◆ stringizeTags()

void sparta::TreeNode::stringizeTags ( std::stringstream &  ss) const
inline

Render tags to a string in the form: " tags:[tag0, tag1]" If there are any tags. The leading space makes this a useful sub-utility of stringize because if there are no tags, returns empty string with no leading space.

Parameters
ssstringstream to write to

Definition at line 743 of file TreeNode.hpp.

◆ validateDesc()

void sparta::TreeNode::validateDesc ( const std::string &  desc)

Validates the given description string for this TreeNode.

Precondition
name_ must be assigned for this instance. It will be included in the exception message
Exceptions
SpartaExceptionif the string is invalid

Constraints:

  • desc must not be empty

◆ validateGroup()

void sparta::TreeNode::validateGroup ( const std::string &  name,
const std::string &  group,
group_idx_type  idx 
)

Validates the given group name string and group index for this TreeNode. Does not consider context (e.g. name collisions)

Parameters
nameNode name
groupGroup name
idxGroup index
Exceptions
SpartaExceptionif the group name and group index combination is invalid (i.e. already used by another node)

Constraints:

◆ validateName()

void sparta::TreeNode::validateName ( const std::string &  nm)

Validates the given name string for this TreeNode. Does not consider context (e.g. name collisions)

Exceptions
SpartaExceptionif the name is invalid.

Constraints:

  • Name must not exactly match any names in sparta::RESERVED_WORDS
  • Name must not begin with a decimal digit
  • Name must not contain two adjacent underscores
  • Name must contain only alphanumeric characters and underscores (see sparta::ALPHANUM_CHARS).

◆ validatePostRun_()

void sparta::TreeNode::validatePostRun_ ( const PostRunValidationInfo info) const
protected

Hook to check the state of the simulator post-run and throw exceptions if something is incorrect.

Precondition
Simulator post-run sanity checking will be enabled. If not enabled, this will never be called
Simulator will be in a state earlier than TREE_TEARDOWN phase
Note
The entire resource tree is accessible. Nothing has been destructed yet
The simulator will not continue to run for this device tree at this point.
This can be invoked multiple times during a simulation with different info content
This call may be followed by dumpDebugContent_ depending on the configuration of the simulator and any errors encountered.
This call will be eventually followed by onEnteringTeardown_ unless the application is corrupted or hard-terminated (i.e. std::terminate, exit call, or exception in a destructor when unwinding)
Exceptions
Anyexceptions related to post-run state

◆ validateTree_()

void sparta::TreeNode::validateTree_ ( )
protected

Iterates the finalized tree and validates each node (e.g. ensures statistics can be evaluated)

Precondition
Tree must be in TREE_FINALIZED phase
Exceptions
SpartaExceptionif any node cannot be validated

◆ verifyUniqueChildIdentifier_()

void sparta::TreeNode::verifyUniqueChildIdentifier_ ( const std::string &  ident,
bool  ignore_group_collision = false 
)
protected

Verifies that the given identifier is unique for all children of this node by comparing against names, groups, and aliases. Throws SpartaException if not unique.

Parameters
identIdentifier of child to check for uniqueness (e.g. a name or alias)
ignore_group_collisionIf true, collisions of keys where the existing value in the names_ map is a Grouping are ignored. (default false: throw exception on collision).
Exceptions
SpartaExceptionif a ident is not unique.

Friends And Related Symbol Documentation

◆ ClockManager

friend class ClockManager
friend

Allow ClockManager to directly change phase on nodes.

Definition at line 217 of file TreeNode.hpp.

◆ SpartaStaticInitializer

friend class SpartaStaticInitializer
friend

This class is responsible for instantiating the static container held by this TreeNode.

Definition at line 223 of file TreeNode.hpp.

◆ TreeNodePrivateAttorney

friend class TreeNodePrivateAttorney
friend

Friend an attorney pattern that can expose access to getAllChildren_ or other methods that bypass privacy_level_.

Definition at line 229 of file TreeNode.hpp.

◆ VirtualGlobalTreeNode

friend class VirtualGlobalTreeNode
friend

Allow this class access internals for handling notification observation registration/deregistration broadcasts in a way that does not fit the composite tree pattern.

Definition at line 212 of file TreeNode.hpp.

Member Data Documentation

◆ CHILD_FIND_THRESHOLD

const uint64_t sparta::TreeNode::CHILD_FIND_THRESHOLD = 100000
static

Threshold for number of findChildren calls after finalization before a warning message is printed about framework misuse.

This value should be large enough that a few accesses by tools or lookups for caching pointers to other objects are allowed, but small enough that a findChildren call happening every N cycles of execution in the simulator will be detected during runs that take more than a few minutes. Consider that Parameters are also part of a tree and ParameterSet or RegisterSet nodes may be the target of some getChild calls after finalization, but generaly these nodes should be cached in the requesting component.

Note
Reports applied after starting can search the tree, causing many accesses. This constant requires a large value to not print warnings in this situation
Todo:
getChild/findChildren should know the difference between report-based accesses and model-based accesses so that this can be conditionally incremented

Definition at line 392 of file TreeNode.hpp.

◆ CHILD_GET_THRESHOLD

const uint64_t sparta::TreeNode::CHILD_GET_THRESHOLD = 100000
static

Threshold for number of getChild calls after finalization before a warning message is printed about framework misuse.

See CHILD_FIND_THRESHOLD for explanation of threshold value choice

Definition at line 400 of file TreeNode.hpp.

◆ DEBUG_DUMP_SECTION_DIVIDER

const std::string sparta::TreeNode::DEBUG_DUMP_SECTION_DIVIDER
static

String dividing sections in a debug dump file.

Definition at line 324 of file TreeNode.hpp.

◆ GROUP_IDX_NONE

const group_idx_type sparta::TreeNode::GROUP_IDX_NONE = (group_idx_type)-1
static

GroupIndex indicating that a node has no group index because it belongs to no group.

Definition at line 303 of file TreeNode.hpp.

◆ GROUP_NAME_BUILTIN

constexpr char sparta::TreeNode::GROUP_NAME_BUILTIN[] = "_SPARTA_builtin_group_"
staticconstexpr

Reserved name for built-in nodes.

Nodes in this group are exempt from certain restrictions and filtered from printing and searching operations.

Definition at line 370 of file TreeNode.hpp.

◆ GROUP_NAME_NONE

constexpr char sparta::TreeNode::GROUP_NAME_NONE[] = ""
staticconstexpr

Group name indicating that a node belongs to no group.

Definition at line 314 of file TreeNode.hpp.

◆ LOCATION_NODE_SEPARATOR_ATTACHED

constexpr char sparta::TreeNode::LOCATION_NODE_SEPARATOR_ATTACHED = '.'
staticconstexpr

Separator character between node identifiers in a location string when the child is attached to the parent.

Warning
Do not change these as builtin logic and documentation depends on these constants.

Definition at line 337 of file TreeNode.hpp.

◆ LOCATION_NODE_SEPARATOR_EXPECTING

constexpr char sparta::TreeNode::LOCATION_NODE_SEPARATOR_EXPECTING = ','
staticconstexpr

Separator character between node identifiers in a location string when the child is being attached to the parent but has not been entirely attached (i.g. during construction of the child node)

Warning
Do not change these as builtin logic and documentation depends on these constants.

Definition at line 346 of file TreeNode.hpp.

◆ LOCATION_NODE_SEPARATOR_UNATTACHED

constexpr char sparta::TreeNode::LOCATION_NODE_SEPARATOR_UNATTACHED = '~'
staticconstexpr

Separator character preceding a node identifiers in a location string when that node has no parent and is not in the process of being attached to one.

Warning
Do not change these as builtin logic and documentation depends on these constants.

Definition at line 355 of file TreeNode.hpp.

◆ MAX_NODE_UID

const node_uid_type sparta::TreeNode::MAX_NODE_UID
static

Maximum value of node_uid_ before the framework throws an exception.

Definition at line 309 of file TreeNode.hpp.

◆ NODE_NAME_NONE

constexpr char sparta::TreeNode::NODE_NAME_NONE[] = ""
staticconstexpr

Node name for anonymous node.

Definition at line 319 of file TreeNode.hpp.

◆ NODE_NAME_VIRTUAL_GLOBAL

constexpr char sparta::TreeNode::NODE_NAME_VIRTUAL_GLOBAL[] = "_SPARTA_virtual_global_"
staticconstexpr

Node name for the virtual glopbal node.

Definition at line 329 of file TreeNode.hpp.

◆ RENDER_SUBTREE_INDENT

const uint32_t sparta::TreeNode::RENDER_SUBTREE_INDENT = 2
static

Spaces to indent for each tree level in sparta::TreeNode::renderSubtree.

Note
This is cosmetic only

Definition at line 362 of file TreeNode.hpp.

◆ TEARDOWN_ERROR_LIMIT

const uint32_t sparta::TreeNode::TEARDOWN_ERROR_LIMIT = 5
static

Number of teardown-phase-related messages that can be printed before the rest will be suppressed.

Definition at line 406 of file TreeNode.hpp.

◆ TREE_NODE_PATTERN_SUBS

const std::vector<std::pair<const char*, std::function<void (std::string&)> > > sparta::TreeNode::TREE_NODE_PATTERN_SUBS
static

List of pattern susbtitutions when creating a search pattern from a TreeNode name containing wildcards.

Definition at line 412 of file TreeNode.hpp.


The documentation for this class was generated from the following file: