The Sparta Modeling Framework
Loading...
Searching...
No Matches
NotificationSource.hpp
1// <NotificationSource> -*- C++ -*-
2
3#pragma once
4
5#include <array>
6#include <cstdint>
7#include <functional>
8#include <iostream>
9#include <sstream>
10#include <type_traits>
11#include <vector>
12
16#include "sparta/utils/StringManager.hpp"
18
19namespace sparta
20{
21
63 #define REGISTER_FOR_THIS(func) \
64 registerForThis<typename std::remove_reference<decltype(*this)>::type, \
65 &std::remove_reference<decltype(*this)>::type::func>(this);
66
72 #define DEREGISTER_FOR_THIS(func) \
73 deregisterForThis<typename std::remove_reference<decltype(*this)>::type, \
74 &std::remove_reference<decltype(*this)>::type::func>(this);
75
76 template<typename T>
77 class MirrorNotificationSource;
78
86 {
87 public:
93 template <typename T>
97
101
112
119 typedef std::function<void (NotificationSourceBase const &, uint32_t)> callback_t;
120
168
170 callback_t callback_;
171 TreeNode::ConstWeakPtr tree_node_weak_ptr_;
173
174 public:
175
178 callback_t callback)
179 : type_(type),
180 callback_(callback),
181 tree_node_weak_ptr_(ns.getWeakPtr()),
182 ns_(ns)
183 {
184 ObservationStateCallbackPrivateInterface::registerObservationStateChangeCallback_(ns_, this);
185 }
186
188 {
189 // Deregister from notification ONLY if the node has not been destroyed already
190 if (tree_node_weak_ptr_.expired() == false) {
191 ObservationStateCallbackPrivateInterface::deregisterObservationStateChangeCallback_(ns_, this);
192 }
193 }
194
197 ObservationStateCallback& operator= (const ObservationStateCallback&) = delete;
198
202 ObservationStateChange getType() const { return type_; }
203
208 uint32_t observers) const
209 {
210 callback_(ns, observers);
211 }
212
216 void dump(std::ostream& o) const {
217 o << "<ObservationStateCallback type=" << static_cast<int>(type_) << " node=";
218 if(tree_node_weak_ptr_.expired()){
219 o << "EXPIRED";
220 }else{
221 o << tree_node_weak_ptr_.lock()->getLocation();
222 }
223 o << ">";
224 }
225 };
226
232 private:
233 static void registerObservationStateChangeCallback_(NotificationSourceBase & ns,
234 ObservationStateCallback* const cbobject)
235 {
236 ns.registerObservationStateChangeCallback_(cbobject);
237 }
238
239
240 static void deregisterObservationStateChangeCallback_(NotificationSourceBase & ns,
241 ObservationStateCallback* const cbobject)
242 {
243 ns.deregisterObservationStateChangeCallback_(cbobject);
244 }
245
247 };
248
250
253
257
277 const std::string& name,
278 const std::string& group,
279 TreeNode::group_idx_type group_idx,
280 const std::string& desc,
281 const std::string* notification_name_id,
282 const std::type_info& notification_tinfo) :
283 TreeNode(name, group, group_idx, desc),
284 noti_id_(notification_name_id),
285 noti_tinfo_(notification_tinfo),
286 observed_(false),
287 num_posts_(0)
288 {
289 if(nullptr == parent){
290 throw SpartaException("NotificationSourceBase ")
291 << getLocation() << " must be constructed with a parent";
292 }
293
294 setExpectedParent_(parent);
295
296 if(nullptr == notification_name_id){
297 throw SpartaException("NotificationSourceBase ")
298 << getLocation() << " cannot be constructed with a null notification_name_id";
299 }
300
301 // Other initialization here
302 // ...
303
304 validateNotificationName(*notification_name_id);
305
306 parent->addChild(this);
307
308 determineObs_Nodes_();
309 }
310
316 const std::string& name,
317 const std::string& group,
318 TreeNode::group_idx_type group_idx,
319 const std::string& desc,
320 const std::string& notification_name,
321 const std::type_info& notification_tinfo) :
322 NotificationSourceBase(parent, name, group, group_idx, desc,
323 StringManager::getStringManager().internString(notification_name),
324 notification_tinfo)
325 { }
326
327
332
337 bool observed() const noexcept {
338 return observed_;
339 }
340
351 static void validateNotificationName(const std::string& nm)
352 {
353 for(const char* rsrv : RESERVED_WORDS){
354 if(nm == rsrv){
355 throw SpartaException("Notification name \"")
356 << nm << "\" is a reserved word. ";
357 }
358 }
359
360 if(nm.size() > 0 && nm[0] == '_'){
361 throw SpartaException(" Notification name \"")
362 << nm << "\" begins with an '_' which is not permitted";
363 }
364
365 if(nm.find("__") != std::string::npos){
366 throw SpartaException(" Notification name \"")
367 << nm << "\" contains two adjacent underscores which is not permitted";
368 }
369
370 if(nm.find_first_of(DIGIT_CHARS) == 0){
371 throw SpartaException(" Notification name \"")
372 << nm << "\" begins with a '" << nm[nm.size()-1] << "' character which is not permitted. "
373 << "A Notification name must not begin with a decimal digit.";
374 }
375
376 size_t pos = nm.find_first_not_of(ALPHANUM_CHARS);
377 if(pos != std::string::npos){
378 throw SpartaException("Notification name \"")
379 << nm << "\" contains a '" << nm[pos] << "', which is not permitted. "
380 << "A Notification name must contain only alphanumeric characters and underscores.";
381 }
382 }
383
386
390
397 const std::string* getNotificationID() const {
398 return noti_id_;
399 }
400
405 const std::string& getNotificationName() const {
406 return *noti_id_;
407 }
408
413 const std::type_info& getNotificationType() const {
414 return noti_tinfo_;
415 }
416
422 const std::string getNotificationTypeName() const {
423 return demangle(noti_tinfo_.name());
424 }
425
428
438 const std::vector<TreeNode*>& getObservationPoints() const {
439 return obs_nodes_;
440 }
441
451 uint32_t getNumObservationPoints() const {
452 return obs_nodes_.size();
453 }
454
460 uint32_t getNumObservers() const {
461 return dels_.size();
462 }
463
467 uint64_t getNumPosts() const {
468 return num_posts_;
469 }
470
471 protected:
472
473 const std::string* noti_id_;
474 const std::type_info& noti_tinfo_;
475
480 std::vector<TreeNode*> obs_nodes_;
481
490 std::vector<delegate> dels_;
491
493
498 mutable uint64_t num_posts_;
499
500 // Override from TreeNode
502 virtual void notificationObserverAdded_(const std::type_info& tinfo,
503 const std::string* name_id,
504 TreeNode* obs_node,
505 const delegate* del) override {
506 // Expected to only see observation on the notification that this source can
507 // generate. If these assertions are hit, then the framework is broken or
508 // canGenerateNotification_ is incorrect
509 sparta_assert(tinfo == noti_tinfo_);
510 sparta_assert(name_id == noti_id_ || name_id == StringManager::getStringManager().EMPTY);
511
512 // Add the observation point node if unique
513 auto itr = std::find(obs_nodes_.begin(), obs_nodes_.end(), obs_node);
514 if(itr == obs_nodes_.end()){
515 obs_nodes_.push_back(obs_node);
516 }
517
518 dels_.push_back(*del);
519
520 const bool was_observed = observed_;
521 observed_ = true;
522
523 // Callback happen after state changes are complete (or before) in order to allow recursion
524 if(not was_observed){
525 invokeObservationStateChangeCallbacks_(ObservationStateChange::SOLE_OBSERVER_REGISTERING);
526 }
527 invokeObservationStateChangeCallbacks_(ObservationStateChange::OBSERVER_REGISTERING);
528 }
529
530 // Override from TreeNode
532 virtual void notificationObserverRemoved_(const std::type_info& tinfo,
533 const std::string* name_id,
534 TreeNode* obs_node,
535 const delegate* del) override {
536 // Expected to only see observation on the notification that this source can
537 // generate. If these assertions are hit, then the framework is broken or
538 // canGenerateNotification_ is incorrect
539 sparta_assert(tinfo == noti_tinfo_);
540 sparta_assert(name_id == noti_id_ || name_id == StringManager::getStringManager().EMPTY);
541
542 const bool was_observed = observed_;
543
544 auto delitr = std::find(dels_.begin(), dels_.end(), *del);
545 if(delitr != dels_.end()){
546 dels_.erase(delitr);
547 }
548
549 observed_ = dels_.size() > 0;
550
551 // Remove the observation point node if no delegates refer to it any more
552 bool remaining = false;
553 for(auto d : dels_){
554 if(d.getObservationPoint() == obs_node){
555 remaining = true;
556 break;
557 }
558 }
559 if(false == remaining){
560 auto itr = std::find(obs_nodes_.begin(), obs_nodes_.end(), obs_node);
561 if(itr != obs_nodes_.end()){
562 obs_nodes_.erase(itr);
563 }
564 }
565
566 // Callback happen after state changes are complete (or before) in order to allow recursion
567 // Reverse order of callback from notificationObserverAdded_.
568 invokeObservationStateChangeCallbacks_(ObservationStateChange::OBSERVER_DEREGISTERING);
569 if(was_observed && not observed_){
570 invokeObservationStateChangeCallbacks_(ObservationStateChange::SOLE_OBSERVER_DEREGISTERING);
571 }
572 }
573
574 // Override from TreeNode
575 // Returns true only for matches on node's notification ID or the input pattern
576 bool canGenerateNotification_(const std::type_info& tinfo,
577 const std::string* id,
578 const std::string*& match) const override {
579 if(noti_tinfo_ != tinfo && tinfo != typeid(sparta::TreeNode::ANY_TYPE)){
580 return false;
581 }
582
584 match = noti_id_;
585 return true;
586 }
587
588 return false;
589 }
590
591 // Override from TreeNode
592 virtual std::string stringize(bool pretty=false) const override {
593 (void) pretty;
594 std::stringstream ss;
595 ss << '<' << getLocation() << " name:\""
596 << getNotificationName() << "\" datat:(" << getNotificationTypeName()
597 << ") " << " observers:" << getNumObservers()
598 << " posted:" << getNumPosts() << '>';
599 return ss.str();
600 }
601 private:
602
603 // Override from TreeNode
604 virtual void onAddedAsChild_() noexcept override final {
605 determineObs_Nodes_();
606 }
607
608
618 void determineObs_Nodes_() {
619 obs_nodes_.clear();
620 dels_.clear();
621 observed_ = false;
622
623 TreeNode* node = this;
624 while(node){
625 node->getDelegatesRegisteredForNotification(noti_tinfo_, noti_id_, dels_);
626 if(node->hasObserversRegisteredForNotification(noti_tinfo_, noti_id_)){
627 obs_nodes_.push_back(node);
628 }
629 node = node->getParent();
630 }
631
632 node = getVirtualGlobalNode();
633 node->getDelegatesRegisteredForNotification(noti_tinfo_, noti_id_, dels_);
634 if(node->hasObserversRegisteredForNotification(noti_tinfo_, noti_id_)){
635 obs_nodes_.push_back(node);
636 }
637
638 // Update observed flag
639 observed_ = dels_.size() > 0;
640 }
641
642 // Override from TreeNode
643 // Adds this node's notification info
644 void getPossibleNotifications_(std::vector<NotificationInfo>& infos) const override {
645 infos.emplace_back(this, &noti_tinfo_, noti_id_);
646 }
647
651 void registerObservationStateChangeCallback_(ObservationStateCallback* const hook) {
652 // User errors
653 sparta_assert(in_observation_state_change_callback_ == false,
654 "cannot add observation state change callbacks from within a callback");
655
656 // Internal errors
657 sparta_assert(hook); // Internal-only hook argument is null somehow?
658 sparta_assert(std::find(obs_state_change_cbs_.begin(), obs_state_change_cbs_.end(), hook) == obs_state_change_cbs_.end(),
659 "Internal notification hook " << *hook
660 << " was installed a second time to notification source " << *this);
661
662 // Track it in a list
663 obs_state_change_cbs_.emplace_back(hook);
664 }
665
669 void deregisterObservationStateChangeCallback_(ObservationStateCallback* const hook) {
670 // User errors
671 sparta_assert(in_observation_state_change_callback_ == false,
672 "cannot remove observation state change callbacks from within a callback");
673
674 const auto itr = std::find(obs_state_change_cbs_.begin(), obs_state_change_cbs_.end(), hook);
675
676 // Internal error checking
677 sparta_assert(itr != obs_state_change_cbs_.end(),
678 "Internal notification hook " << *hook
679 << " was not found while attemptint to deregister it from notification source " << *this);
680
681 // Remove it so it is no longer called
682 obs_state_change_cbs_.erase(itr);
683 }
684
690 void invokeObservationStateChangeCallbacks_(ObservationStateChange to_call) {
691 // User Error
692 sparta_assert(in_observation_state_change_callback_ == false,
693 "cannot recursively invoke observation state change callbacks from within a "
694 "callback. User may be changing Notification Observers in response to "
695 "changes in observation state. This is not allowed");
696
697 in_observation_state_change_callback_ = true;
698
699 // Break on first exception!
700 try {
701 for(ObservationStateCallback const * cb : obs_state_change_cbs_){
702 if(cb->getType() == to_call){
703 (*cb)(*this, getNumObservers());
704 }
705 }
706 } catch (...) {
707 in_observation_state_change_callback_ = false;
708
709 throw; // Re-throw
710 }
711
712 in_observation_state_change_callback_ = false;
713 }
714
723 std::vector<ObservationStateCallback*> obs_state_change_cbs_;
724
733 bool in_observation_state_change_callback_ = false;
734 };
735
736
745 template <typename NotificationDataT>
747 {
748 public:
749
750 typedef NotificationDataT data_type;
751 typedef NotificationDataT const const_data_type;
752
756
770 const std::string& name,
771 const std::string& group,
772 TreeNode::group_idx_type group_idx,
773 const std::string& desc,
774 const std::string* notification_name_id) :
775 NotificationSourceBase(parent, name, group, group_idx,
776 desc, notification_name_id,
777 typeid(NotificationDataT))
778 {
779 static_assert(std::is_same<
780 typename std::remove_cv<
781 typename std::remove_reference<
782 typename std::remove_pointer<NotificationDataT>::type
783 >::type
784 >::type,
785 NotificationDataT
786 >::value,
787 "NotificationDataT must NOT be a const, volatile, pointer, or reference"
788 "type. It violates at least one of these restrictions");
789
790 // Other initialization here
791 // ...
792 }
793
794 // Alternate constructor
796 const std::string& name,
797 const std::string& group,
798 TreeNode::group_idx_type group_idx,
799 const std::string& desc,
800 const std::string& notification_name) :
801 NotificationSource(parent,
802 name,
803 group,
804 group_idx,
805 desc,
806 StringManager::getStringManager().internString(notification_name))
807 {
808 // Initialization handled in constructor delegation
809 }
810
811 // Alternate constructor
813 const std::string& name,
814 const std::string& desc,
815 const std::string* notification_name_id) :
816 NotificationSource(parent,
817 name,
820 desc,
821 notification_name_id)
822 {
823 // Initialization handled in constructor delegation
824 }
825
826 // Alternate constructor
828 const std::string& name,
829 const std::string& desc,
830 const std::string& notification_name) :
831 NotificationSource(parent,
832 name,
835 desc,
836 StringManager::getStringManager().internString(notification_name))
837 {
838 // Initialization handled in constructor delegation
839 }
840
841 // Alternate constructor with anonymous name
843 const std::string& group,
844 TreeNode::group_idx_type group_idx,
845 const std::string& desc,
846 const std::string* notification_name_id) :
847 NotificationSource(parent,
848 "",
849 group,
850 group_idx,
851 desc,
852 notification_name_id)
853 {
854 // Initialization handled in constructor delegation
855 }
856
857 // Alternate constructor with anonymous name
859 const std::string& group,
860 TreeNode::group_idx_type group_idx,
861 const std::string& desc,
862 const std::string& notification_name) :
863 NotificationSource(parent,
864 "",
865 group,
866 group_idx,
867 desc,
868 StringManager::getStringManager().internString(notification_name))
869 {
870 // Initialization handled in constructor delegation
871 }
872
878
879
880
884
927 template <typename T, void (T::*TMethod)(const TreeNode&, const TreeNode&, const_data_type&)>
931
932 // Overload accepting a class member function signature having only a data argument
933 template <typename T, void (T::*TMethod)(const_data_type&)>
934 void registerForThis(T* obj) {
936 }
937
946 template <typename T, void (T::*TMethod)(const TreeNode&, const TreeNode&, const_data_type&)>
950
951 // Overload accepting a class member function signature having only a data argument
952 template <typename T, void (T::*TMethod)(const_data_type&)>
953 void deregisterForThis(T* obj) {
955 }
956
961 void postNotification(const NotificationDataT& data) const {
962 ++num_posts_;
963
964 // Could notify observers at this node and above through TreeNode's propagation interface
965 //sparta_assert(getParent() != nullptr,
966 // "Cannot postNotification from NotificationSource " << getLocation() << " because parent is null");
967 //postPropagatingNotification_(this, data, noti_id_);
968
969 // Could Notify all observing TreeNodes and allow them to invoke delegates
970 //for(TreeNode* o_node : obs_nodes_){
971 // invokeDelegatesOn_(o_node, data, noti_id_);
972 //}
973
974 // Directly invoke all applicable delegates.
975 // Note that this works even if ancestors are destroyed because
976 // deregistration does not take place.
977 for(const delegate& d : dels_){
978 d(*this, data);
979 }
980 }
981
984 };
985
1001 {
1002 public:
1003 using NotificationSource<std::string>::NotificationSource;
1004
1005 void setFormatString(const std::string& format_str)
1006 {
1007 // The format_str looks something like "%s_$i.json".
1008 // In the event that we have multiple reports setup
1009 // to be triggered by the same notif source, we need
1010 // to ensure that the format specifiers are the same
1011 // for all ReportDescriptor dest_file's we are given.
1012 auto specs = parseFormatSpecifiers_(format_str);
1013 if (!parsed_specs_.empty())
1014 {
1015 sparta_assert(specs == parsed_specs_);
1016 }
1017 else
1018 {
1019 parsed_specs_ = specs;
1020 }
1021
1022 format_str_ = format_str;
1023 }
1024
1025 bool hasFormatString() const {
1026 return !format_str_.empty();
1027 }
1028
1036 template <typename... Args>
1037 void postNotification(Args... args) const
1038 {
1039 sparta_assert(!format_str_.empty(),
1040 "setFormatString() must be called before postNotification() on " << getLocation());
1041
1042 constexpr std::array<SpecType, sizeof...(Args)> expected_types { specTypeFor_<Args>()... };
1043
1044 if(parsed_specs_.size() != sizeof...(Args)){
1045 throw SpartaException("Sprintf format string \"")
1046 << format_str_ << "\" for " << getLocation() << " has " << parsed_specs_.size()
1047 << " specifier(s) but " << sizeof...(Args) << " argument(s) were given";
1048 }
1049
1050 for(std::size_t i = 0; i < parsed_specs_.size(); ++i){
1051 if(parsed_specs_[i] != expected_types[i]){
1052 throw SpartaException("Sprintf format string \"")
1053 << format_str_ << "\" for " << getLocation()
1054 << " has a type mismatch at specifier index " << i;
1055 }
1056 }
1057
1058 // One stream-to-ostringstream lambda per argument, invoked in order as specifiers are encountered
1059 const std::array<std::function<void(std::ostringstream&)>, sizeof...(Args)> streamers {
1060 [&args](std::ostringstream& o){ o << args; }...
1061 };
1062
1063 std::ostringstream oss;
1064 std::size_t arg_idx = 0;
1065 for(std::size_t i = 0; i < format_str_.size(); ++i){
1066 if(format_str_[i] != '%'){
1067 oss << format_str_[i];
1068 continue;
1069 }
1070
1071 const char spec = format_str_[++i];
1072 if(spec == '%'){
1073 oss << '%';
1074 }else{
1075 streamers[arg_idx++](oss);
1076 }
1077 }
1078
1080 }
1081
1082 private:
1083 enum class SpecType { STRING, INT };
1084
1085 // Maps an argument type to the specifier it must match (%i for non-bool integrals, %s otherwise)
1086 template <typename T>
1087 static constexpr SpecType specTypeFor_()
1088 {
1089 using PlainT = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
1090 if constexpr (std::is_integral<PlainT>::value && !std::is_same<PlainT, bool>::value){
1091 return SpecType::INT;
1092 }else{
1093 return SpecType::STRING;
1094 }
1095 }
1096
1097 // Runtime scan of format_str for %s/%i/%% specifiers, in order of appearance
1098 static std::vector<SpecType> parseFormatSpecifiers_(const std::string& format_str)
1099 {
1100 std::vector<SpecType> specs;
1101 for(std::size_t i = 0; i < format_str.size(); ++i){
1102 if(format_str[i] != '%'){
1103 continue;
1104 }
1105
1106 if(i + 1 >= format_str.size()){
1107 throw SpartaException("Sprintf format string \"")
1108 << format_str << "\" ends with a lone '%' character";
1109 }
1110
1111 const char spec = format_str[++i];
1112 switch(spec){
1113 case 's':
1114 specs.push_back(SpecType::STRING);
1115 break;
1116 case 'i':
1117 specs.push_back(SpecType::INT);
1118 break;
1119 case '%':
1120 break; // Literal '%', not a specifier
1121 default:
1122 throw SpartaException("Sprintf format string \"")
1123 << format_str << "\" contains unsupported specifier '%" << spec
1124 << "'. Only %s and %i are supported";
1125 }
1126 }
1127 return specs;
1128 }
1129
1130 std::string format_str_;
1131 std::vector<SpecType> parsed_specs_;
1132 };
1133
1138 class ReportROI : public NotificationSource<uint64_t>
1139 {
1140 public:
1142
1144 void setActiveROI(uint64_t roi)
1145 {
1146 active_roi_ = roi;
1147 postNotification(roi);
1148 }
1149
1151 uint64_t getActiveROI() const
1152 {
1153 return active_roi_;
1154 }
1155
1156 bool hasActiveROI() const
1157 {
1158 return active_roi_.isValid();
1159 }
1160
1161 private:
1162 utils::ValidValue<uint64_t> active_roi_;
1163 };
1164
1173 template<typename NotificationDataT>
1175 {
1176 typedef std::vector<NotificationSourceBase*> SrcList;
1177 public:
1194 const std::string& name,
1195 const std::string& group,
1196 TreeNode::group_idx_type group_idx,
1197 const std::string& desc,
1198 const std::string* notification_name_id):
1199 NotificationSourceBase(parent, name, group, group_idx, desc,
1200 notification_name_id,
1201 typeid(NotificationDataT))
1202 {}
1203
1209 const std::string& name,
1210 const std::string& group,
1211 TreeNode::group_idx_type group_idx,
1212 const std::string& desc,
1213 const std::string& notification_name) :
1214 NotificationSourceBase(parent, name, group, group_idx,
1215 desc,
1216 notification_name,
1217 typeid(NotificationDataT))
1218 {}
1219
1220 // Alternate constructor
1222 const std::string& name,
1223 const std::string& desc,
1224 const std::string& notification_name) :
1226 name,
1229 desc,
1230 StringManager::getStringManager().internString(notification_name))
1231 {}
1232
1244 void addLink(TreeNode *node, const std::string &label) override final
1245 {
1246 (void)label; // We do not care about the label.
1247 sparta_assert(node != nullptr);
1248 const uint32_t prev_size = concretes_.size();
1249 findMatchingSourcesBelowNode_(*node, concretes_);
1250 // Make sure we found atleast 1 node that we are shadowing,
1251 // otherwise this MirrorNotificationSource is not linked to
1252 // anyone and should be taken out.
1253 if (concretes_.size() - prev_size == 0)
1254 {
1255 SpartaException ex("MirrorNotificationSource \"");
1256 ex << getName() << "\" was unable to bind to any real NotificationSources"
1257 << " found under the nodes provided to addLink().";
1258 throw ex;
1259 }
1260 }
1261 private:
1262
1267 void findMatchingSourcesBelowNode_(sparta::TreeNode& node,
1268 SrcList& bases)
1269 {
1270 auto* as_src = dynamic_cast<NotificationSourceBase*>(&node);
1271 if (as_src)
1272 {
1273 // If this MirrorNotificationSource happened to live under the search
1274 // of node, then we would certainly not want to add ourselves as a
1275 // concrete instance!
1276 if (as_src != this)
1277 {
1278 // We won't mirror anything that isn't explicitly allowed by the concrete
1279 // source.
1280 if (as_src->getNotificationID() == getNotificationID() &&
1281 as_src->getNotificationType() == getNotificationType())
1282 {
1283 bases.emplace_back(dynamic_cast<NotificationSourceBase*>(&node));
1284 }
1285 }
1286 }
1287
1288 for (auto n : node.getChildren())
1289 {
1290 findMatchingSourcesBelowNode_(*n, bases);
1291 }
1292
1293 }
1294 // Override from TreeNode
1296 void notificationObserverAdded_(const std::type_info& tinfo,
1297 const std::string* name_id,
1298 TreeNode* obs_node,
1299 const delegate* del) override final
1300 {
1301 if (del->revealsOrigin())
1302 {
1303 SpartaException ex("Cannot register for notification \"");
1304 ex << *name_id << "\"" << " because this notification source "
1305 << "is only shadowing a private concrete notification source. "
1306 << "The callback signature type would reveal access to a private node "
1307 << "and be misleading. We do not support this feature at this time.";
1308 throw ex;
1309 }
1310
1311 if (concretes_.size() == 0)
1312 {
1313 SpartaException ex ("Cannot register for notification \"");
1314 ex << *name_id << "\" because this is a MirrorNotificationSource "
1315 << "that is not linked to any concrete sources. It is possible you "
1316 << "are registering for the notification too early and should be registering "
1317 << "during onBindTreeLate_()";
1318 throw ex;
1319 }
1320 for(auto concrete : concretes_)
1321 {
1322 concrete->notificationObserverAdded_(tinfo, name_id,
1323 obs_node, del);
1324 }
1325 }
1326 // Override from TreeNode
1328 void notificationObserverRemoved_(const std::type_info& tinfo,
1329 const std::string* name_id,
1330 TreeNode* obs_node,
1331 const delegate* del) override final
1332 {
1333 if (concretes_.size() == 0)
1334 {
1335 SpartaException ex ("Cannot deregister for notification \"");
1336 ex << *name_id << "\" because this is a MirrorNotificationSource "
1337 << "that is not linked to any concrete sources. It is possible you "
1338 << "are deregistering for the notification too early and should be registering "
1339 << "during onBindTreeLate_()";
1340 throw ex;
1341 }
1342
1343 for(auto concrete : concretes_)
1344 {
1345 concrete->notificationObserverRemoved_(tinfo, name_id,
1346 obs_node, del);
1347 }
1348 }
1349 // Override from TreeNode
1350 // Returns true only for matches on node's notification ID or the input pattern
1351 bool canGenerateNotification_(const std::type_info& tinfo,
1352 const std::string* id,
1353 const std::string*& match) const override final
1354 {
1355 if (concretes_.size() == 0)
1356 {
1357 return false;
1358 }
1359 bool can_generate = true;
1360 for (auto noti_src : concretes_)
1361 {
1362 can_generate &= noti_src->canGenerateNotification_(tinfo, id, match);
1363 }
1364 return can_generate;
1365 }
1366
1373 void validateNode_() const override final
1374 {
1375 if (concretes_.size() == 0)
1376 {
1377 SpartaException ex("Unbound MirrorNotificationSource ");
1378 ex << getName() << " was never bound to concrete notification sources.";
1379 throw ex;
1380 }
1381 }
1382
1383 // Override from TreeNode
1384 virtual std::string stringize(bool pretty=false) const override final {
1385 (void) pretty;
1386 std::stringstream ss;
1388 ss << " shadows: ";
1389 try{
1390 ss << concretes_.size() << " sources ";
1391 }
1392 catch (SpartaException&)
1393 {
1394 ss << "[UNAVAILABLE]";
1395 }
1396 return ss.str();
1397 }
1399 SrcList concretes_;
1400 };
1401
1402 inline std::ostream& operator<<(std::ostream& o, const NotificationSourceBase::ObservationStateCallback& osc)
1403 {
1404 osc.dump(o);
1405 return o;
1406 }
1407
1408 inline std::ostream& operator<<(std::ostream& o, const NotificationSourceBase::ObservationStateCallback* osc)
1409 {
1410 if(osc == nullptr){
1411 o << "nullptr";
1412 }else{
1413 o << *osc;
1414 }
1415 return o;
1416 }
1417
1418} // namespace sparta
1419
Set of macros for Sparta assertions. Caught by the framework.
#define sparta_assert(...)
Simple variadic assertion that will throw a sparta_exception if the condition fails.
Exception class for all of Sparta.
Basic Node framework in sparta device tree composite pattern.
#define RESERVED_WORDS
Reserved words in Python language, Python builtins, and other reservations. TreeNode names and groups...
Definition TreeNode.hpp:69
#define ALPHANUM_CHARS
Enables tracing of TreeNode lifetimes in a set of output txt files.
Definition TreeNode.hpp:58
#define DIGIT_CHARS
Digit characters (for valid TreeNode groups)
Definition TreeNode.hpp:62
File that defines a ValidValue.
essentially a pass through notification source that is a placeholder in a shadow tree.
MirrorNotificationSource(TreeNode *parent, const std::string &name, const std::string &group, TreeNode::group_idx_type group_idx, const std::string &desc, const std::string *notification_name_id)
MirrorNotificationSource.
void addLink(TreeNode *node, const std::string &label) override final
MirrorNotificationSource(TreeNode *parent, const std::string &name, const std::string &group, TreeNode::group_idx_type group_idx, const std::string &desc, const std::string &notification_name)
Alternate construct that accepts a notification name string instead of an interned string pointer.
Controlled interface to NotificationSourceBase for regiistering and deregistering observation state c...
Callback for observation-state of a NotificationSourceBase.
void operator()(NotificationSourceBase const &ns, uint32_t observers) const
Invoked the callback function.
void dump(std::ostream &o) const
Dump string description to an ostream.
ObservationStateChange getType() const
Get tyhe type of change associated with this callback instance.
A TreeNode that generates a single specific type of notification which propagates up a tree of TreeNo...
virtual ~NotificationSourceBase()
Destructor.
static void validateNotificationName(const std::string &nm)
Validates the given notification name string.
bool observed_
Cached value of obs_nodes_.size() > 0 for faster queries.
friend class ObservationStateCallbackInterface
Allow controlled interaction with some members of this class.
bool canGenerateNotification_(const std::type_info &tinfo, const std::string *id, const std::string *&match) const override
Implements TreeNode::canGenerateNotification. Node subclasses which will post notifications must impl...
const std::string & getNotificationName() const
Returns the notification name string for slow string comparison or printing.
ObservationStateChange
Various hook types for which one can register internal callbacks on this notificaiton source.
@ SOLE_OBSERVER_REGISTERING
A sole observer is being registered to observe this notification source. This is a transition from 0 ...
@ OBSERVER_REGISTERING
An observer is being registered to observe this notification source. This may be the first,...
@ SOLE_OBSERVER_DEREGISTERING
A sole observer is being de-registered from observing this notification source. This is a transition ...
@ OBSERVER_DEREGISTERING
An observer is being de-registered from observing this notification source. This may be the first,...
uint32_t getNumObservers() const
Returns the number of delegates affected by postings of this notification.
std::vector< TreeNode * > obs_nodes_
Vector of TreeNodes at which the notification that this node can generate is being observed.
bool observed() const noexcept
Is this NotificationSourceBase being observed at this node or an ancestor of any distance.
virtual void notificationObserverRemoved_(const std::type_info &tinfo, const std::string *name_id, TreeNode *obs_node, const delegate *del) override
NotificationSourceBase(TreeNode *parent, const std::string &name, const std::string &group, TreeNode::group_idx_type group_idx, const std::string &desc, const std::string *notification_name_id, const std::type_info &notification_tinfo)
NotificationSourceBase.
virtual std::string stringize(bool pretty=false) const override
Create a string representation of this node.
std::function< void(NotificationSourceBase const &, uint32_t)> callback_t
Observation state change callback function signature.
const std::type_info & noti_tinfo_
Type of notification data.
virtual void notificationObserverAdded_(const std::type_info &tinfo, const std::string *name_id, TreeNode *obs_node, const delegate *del) override
uint64_t getNumPosts() const
Returns the number of notifications posted by this node.
NotificationSourceBase(TreeNode *parent, const std::string &name, const std::string &group, TreeNode::group_idx_type group_idx, const std::string &desc, const std::string &notification_name, const std::type_info &notification_tinfo)
Alternate construct that accepts a notification name string instead of an interned string pointer.
uint32_t getNumObservationPoints() const
Returns the number of observation points affecting this notification source.
const std::string getNotificationTypeName() const
Gets the demangled name of the C++ notification type which this NotificationSource can emit.
const std::vector< TreeNode * > & getObservationPoints() const
Returns the vector of observation points on this notification source.
const std::type_info & getNotificationType() const
Returns std::type_info from typeid() on the notification data type which this NotificationSource can ...
uint64_t num_posts_
Number of messages posted whether observed or not.
const std::string * noti_id_
Name of notification generated. Should be similar to node name.
std::vector< delegate > dels_
Vector of delegates directly observing this notification source.
const std::string * getNotificationID() const
Returns notification ID (string pointer from Notification ID interned in sparta::StringManager)
A TreeNode that generates a specific type of notification which propagates up a tree of TreeNodes (us...
void deregisterForThis(T *obj)
Deregisters a callback method that was registered with registerForThis.
void postNotification(const NotificationDataT &data) const
Post with reference to data with parent as message origin.
void registerForThis(T *obj)
Registers a callback method to listen for the notification generated by this NotificationSource....
NotificationDataT data_type
Type of notification data generated by this instance.
NotificationSource(TreeNode *parent, const std::string &name, const std::string &group, TreeNode::group_idx_type group_idx, const std::string &desc, const std::string *notification_name_id)
NotificationSource.
NotificationDataT const const_data_type
Const qualified data type.
Notification source that announces the active report region of interest (ROI). Setting the active ROI...
uint64_t getActiveROI() const
void setActiveROI(uint64_t roi)
Remember the given ROI and post it to observers.
Used to construct and throw a standard C++ exception. Inherits from std::exception.
Accepts a sprintf-style format string like "%s_%i.json" and uses the arguments given to postNotificat...
void postNotification(Args... args) const
Formats the current format string (see setFormatString) with args and posts the resulting std::string...
Manages string internment for SPARTA. This allows strings to be compared by pointer once interned.
static StringManager & getStringManager()
Returns the StringManager singleton.
Temporary delegate for notificaiton invokation until the implementation is working....
Node in a composite tree representing a sparta Tree item.
Definition TreeNode.hpp:204
std::string getLocation() const override final
static constexpr char GROUP_NAME_NONE[]
Group name indicating that a node belongs to no group.
Definition TreeNode.hpp:313
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.
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 ...
TreeNode()=delete
Not default-constructable.
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...
void addChild(TreeNode *child, bool inherit_phase=true)
Adds a TreeNode to this node as a child.
uint32_t group_idx_type
Index within a group.
Definition TreeNode.hpp:260
void deregisterForNotification(T *obj, const std::string &name)
Removes at most one registration made with registerForNotification.
WeakPtr getWeakPtr()
Gets a weak pointer to this TreeNode. This weak pointer is guaranteed to expire when this TreeNode is...
static TreeNode * getVirtualGlobalNode()
Gets the virtual global node singleton. This node can have no parent and no children....
static constexpr group_idx_type GROUP_IDX_NONE
GroupIndex indicating that a node has no group index because it belongs to no group.
Definition TreeNode.hpp:302
std::vector< delegate > DelegateVector
Vector of delegates representing a list of observers to notify.
const std::string & getName() const override
Gets the name of this node.
void setExpectedParent_(const TreeNode *parent)
Tracks a node as an expected parent without actually adding this node as a child. This is used almost...
std::weak_ptr< const TreeNode > ConstWeakPtr
Weak pointer to a const TreeNode. Acquire with getWeakPtr.
Definition TreeNode.hpp:270
constexpr bool isValid() const
Is this value valid.
Macros for handling exponential backoff.
std::ostream & operator<<(std::ostream &o, const SimulationInfo &info)
ostream insertion operator for SimulationInfo
std::string demangle(const std::string &name) noexcept
Demangles a C++ symbol.
Definition Utils.hpp:214
Type for indicating that ANY notification source type should be included in a search performed by loc...
Definition TreeNode.hpp:289