#pragma once #include namespace ast { class Node { public: virtual ~Node() = default; enum class ref_type { strong, weak }; void increment(ref_type ref) { switch (ref) { case ref_type::strong: strong_ref++; break; case ref_type::weak : weak_ref ++; break; } } void decrement(ref_type ref) { switch (ref) { case ref_type::strong: strong_ref--; break; case ref_type::weak : weak_ref --; break; } if(!strong_ref && !weak_ref) { delete this; } } template friend auto mutate(const node_t * node); private: size_t strong_ref = 0; size_t weak_ref = 0; }; // Mutate a node, non-member function to avoid static type // problems and be able to use auto return template auto mutate(const node_t * node) { assertf( node->strong_count >= 1, "Error: attempting to mutate a node that appears to have been linked" ); if (node->strong_count == 1) { return const_cast(node); } assertf( node->weak_count == 0, "Error: mutating node with weak references to it will invalided some references" ); return node->clone(); } // All accept routines should look as follows : // virtual void accept( Visitor &v ) override { // return v.visit(this); // } // Using the following wrapper to handle the node type template< typename node_t > auto visit_this( visitor & v, node_t * node ) { ptr p; p.node = node; auto r = v.visit(p); p.node = nullptr; return r; } // Base class for the smart pointer types // should never really be used. template< typename node_t, enum Node::ref_type ref_t> class ptr_base { public: ptr_base() : node(nullptr) {} ptr_base( node_t * n ) : node(n) { if( !node ) node->increment(ref_t); } ~ptr_base() { if( node ) node->decrement(ref_t); } template< enum Node::ref_type o_ref_t > ptr_base( const ptr_base & o ) : node(o.node) { if( !node ) return; node->increment(ref_t); } template< enum Node::ref_type o_ref_t > ptr_base( ptr_base && o ) : node(o.node) { if( node ) node->increment(ref_t); if( node ) node->decrement(o_ref_t); } template< enum Node::ref_type o_ref_t > ptr_base & operator=( const ptr_base & o ) { assign(o.node); return *this; } template< enum Node::ref_type o_ref_t > ptr_base & operator=( ptr_base && o ) { if(o.node == node) return *this; assign(o.node); if( node ) node->decrement(o_ref_t); return *this; } const node_t * get() const { return node; } const node_t * operator->() const { return node; } const node_t & operator* () const { return *node; } operator bool() const { return node; } private: void assign(node_t * other ) { if( other ) other->increment(ref_t); if( node ) node ->decrement(ref_t); node = other; } protected: node_t * node; }; template< typename node_t > using ptr = ptr_base< node_t, Node::ref_type::strong >; template< typename node_t > using readonly = ptr_base< node_t, Node::ref_type::weak >; }