]> www.ginac.de Git - ginac.git/blob - ginac/basic.h
Improve method of setting status_flags::dynallocated.
[ginac.git] / ginac / basic.h
1 /** @file basic.h
2  *
3  *  Interface to GiNaC's ABC. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2015 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  */
22
23 #ifndef GINAC_BASIC_H
24 #define GINAC_BASIC_H
25
26 #include "flags.h"
27 #include "ptr.h"
28 #include "assertion.h"
29 #include "registrar.h"
30
31 #include <cstddef> // for size_t
32 #include <map>
33 #include <set>
34 #include <typeinfo> // for typeid
35 #include <vector>
36 #include <utility>
37
38 namespace GiNaC {
39
40 class ex;
41 struct ex_is_less;
42 class symbol;
43 class numeric;
44 class relational;
45 class archive_node;
46 class print_context;
47
48 typedef std::vector<ex> exvector;
49 typedef std::set<ex, ex_is_less> exset;
50 typedef std::map<ex, ex, ex_is_less> exmap;
51
52 // Define this to enable some statistical output for comparisons and hashing
53 #undef GINAC_COMPARE_STATISTICS
54
55 #ifdef GINAC_COMPARE_STATISTICS
56 class compare_statistics_t {
57 public:
58         compare_statistics_t()
59          : total_compares(0), nontrivial_compares(0), total_basic_compares(0), compare_same_hashvalue(0), compare_same_type(0),
60            total_is_equals(0), nontrivial_is_equals(0), total_basic_is_equals(0), is_equal_same_hashvalue(0), is_equal_same_type(0),
61            total_gethash(0), gethash_cached(0) {}
62         ~compare_statistics_t();
63
64         unsigned long total_compares;
65         unsigned long nontrivial_compares;
66         unsigned long total_basic_compares;
67         unsigned long compare_same_hashvalue;
68         unsigned long compare_same_type;
69
70         unsigned long total_is_equals;
71         unsigned long nontrivial_is_equals;
72         unsigned long total_basic_is_equals;
73         unsigned long is_equal_same_hashvalue;
74         unsigned long is_equal_same_type;
75
76         unsigned long total_gethash;
77         unsigned long gethash_cached;
78 };
79
80 extern compare_statistics_t compare_statistics;
81 #endif
82
83
84 /** Function object for map(). */
85 struct map_function {
86         virtual ~map_function() {}
87         typedef const ex & argument_type;
88         typedef ex result_type;
89         virtual ex operator()(const ex & e) = 0;
90 };
91
92
93 /** Degenerate base class for visitors. basic and derivative classes
94  *  support Robert C. Martin's Acyclic Visitor pattern (cf.
95  *  http://objectmentor.com/publications/acv.pdf). */
96 class visitor {
97 protected:
98         virtual ~visitor() {}
99 };
100
101
102 /** This class is the ABC (abstract base class) of GiNaC's class hierarchy. */
103 class basic : public refcounted
104 {
105         GINAC_DECLARE_REGISTERED_CLASS_NO_CTORS(basic, void)
106         
107         friend class ex;
108         
109         // default constructor, destructor, copy constructor and assignment operator
110 protected:
111         basic() : flags(0) {}
112
113 public:
114         /** basic destructor, virtual because class ex will delete objects of
115          *  derived classes via a basic*. */
116         virtual ~basic()
117         {
118                 GINAC_ASSERT((!(flags & status_flags::dynallocated)) || (get_refcount() == 0));
119         }
120         basic(const basic & other);
121         const basic & operator=(const basic & other);
122
123 protected:
124         // new virtual functions which can be overridden by derived classes
125 public: // only const functions please (may break reference counting)
126
127         /** Create a clone of this object on the heap.  One can think of this as
128          *  simulating a virtual copy constructor which is needed for instance by
129          *  the refcounted construction of an ex from a basic. */
130         virtual basic * duplicate() const
131         {
132                 basic * bp = new basic(*this);
133                 bp->setflag(status_flags::dynallocated);
134                 return bp;
135         }
136
137         // evaluation
138         virtual ex eval(int level = 0) const;
139         virtual ex evalf(int level = 0) const;
140         virtual ex evalm() const;
141         virtual ex eval_integ() const;
142 protected:
143         virtual ex eval_ncmul(const exvector & v) const;
144 public:
145         virtual ex eval_indexed(const basic & i) const;
146
147         // printing
148         virtual void print(const print_context & c, unsigned level = 0) const;
149         virtual void dbgprint() const;
150         virtual void dbgprinttree() const;
151         virtual unsigned precedence() const;
152
153         // info
154         virtual bool info(unsigned inf) const;
155
156         // operand access
157         virtual size_t nops() const;
158         virtual ex op(size_t i) const;
159         virtual ex operator[](const ex & index) const;
160         virtual ex operator[](size_t i) const;
161         virtual ex & let_op(size_t i);
162         virtual ex & operator[](const ex & index);
163         virtual ex & operator[](size_t i);
164
165         // pattern matching
166         virtual bool has(const ex & other, unsigned options = 0) const;
167         virtual bool match(const ex & pattern, exmap & repls) const;
168 protected:
169         virtual bool match_same_type(const basic & other) const;
170 public:
171
172         // substitutions
173         virtual ex subs(const exmap & m, unsigned options = 0) const;
174
175         // function mapping
176         virtual ex map(map_function & f) const;
177
178         // visitors and tree traversal
179         virtual void accept(GiNaC::visitor & v) const
180         {
181                 if (visitor *p = dynamic_cast<visitor *>(&v))
182                         p->visit(*this);
183         }
184
185         // degree/coeff
186         virtual bool is_polynomial(const ex & var) const;
187         virtual int degree(const ex & s) const;
188         virtual int ldegree(const ex & s) const;
189         virtual ex coeff(const ex & s, int n = 1) const;
190
191         // expand/collect
192         virtual ex expand(unsigned options = 0) const;
193         virtual ex collect(const ex & s, bool distributed = false) const;
194
195         // differentiation and series expansion
196 protected:
197         virtual ex derivative(const symbol & s) const;
198 public:
199         virtual ex series(const relational & r, int order, unsigned options = 0) const;
200
201         // rational functions
202         virtual ex normal(exmap & repl, exmap & rev_lookup, int level = 0) const;
203         virtual ex to_rational(exmap & repl) const;
204         virtual ex to_polynomial(exmap & repl) const;
205
206         // polynomial algorithms
207         virtual numeric integer_content() const;
208         virtual ex smod(const numeric &xi) const;
209         virtual numeric max_coefficient() const;
210
211         // indexed objects
212         virtual exvector get_free_indices() const;
213         virtual ex add_indexed(const ex & self, const ex & other) const;
214         virtual ex scalar_mul_indexed(const ex & self, const numeric & other) const;
215         virtual bool contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const;
216
217         // noncommutativity
218         virtual unsigned return_type() const;
219         virtual return_type_t return_type_tinfo() const;
220
221         // functions for complex expressions
222         virtual ex conjugate() const;
223         virtual ex real_part() const;
224         virtual ex imag_part() const;
225
226         // functions that should be called from class ex only
227 protected:
228         virtual int compare_same_type(const basic & other) const;
229         virtual bool is_equal_same_type(const basic & other) const;
230
231         virtual unsigned calchash() const;
232         
233         // non-virtual functions in this class
234 public:
235         /** Like print(), but dispatch to the specified class. Can be used by
236          *  implementations of print methods to dispatch to the method of the
237          *  superclass.
238          *
239          *  @see basic::print */
240         template <class T>
241         void print_dispatch(const print_context & c, unsigned level) const
242         {
243                 print_dispatch(T::get_class_info_static(), c, level);
244         }
245
246         void print_dispatch(const registered_class_info & ri, const print_context & c, unsigned level) const;
247
248         /** Save (serialize) the object into archive node.
249          *
250          * Losely speaking, this method turns an expression into a byte
251          * stream (which can be saved and restored later on, or sent via
252          * network, etc.)
253          */
254         virtual void archive(archive_node& n) const;
255         /** Load (deserialize) the object from an archive node.
256          *
257          *  @note This method is essentially a constructor. However,
258          *  constructors can't be virtual. So, if unarchiving routines
259          *  are implemented as constructors one would need to define such
260          *  a constructor in every class, even if all it does is simply
261          *  calling constructor of a superclass.
262          */
263         virtual void read_archive(const archive_node& n, lst& syms); // no const
264
265         ex subs_one_level(const exmap & m, unsigned options) const;
266         ex diff(const symbol & s, unsigned nth = 1) const;
267         int compare(const basic & other) const;
268         bool is_equal(const basic & other) const;
269         const basic & hold() const;
270
271         unsigned gethash() const
272         {
273 #ifdef GINAC_COMPARE_STATISTICS
274                 compare_statistics.total_gethash++;
275 #endif
276                 if (flags & status_flags::hash_calculated) {
277 #ifdef GINAC_COMPARE_STATISTICS
278                         compare_statistics.gethash_cached++;
279 #endif
280                         return hashvalue;
281                 } else {
282                         return calchash();
283                 }
284         }
285
286         /** Set some status_flags. */
287         const basic & setflag(unsigned f) const {flags |= f; return *this;}
288
289         /** Clear some status_flags. */
290         const basic & clearflag(unsigned f) const {flags &= ~f; return *this;}
291
292 protected:
293         void ensure_if_modifiable() const;
294
295         void do_print(const print_context & c, unsigned level) const;
296         void do_print_tree(const print_tree & c, unsigned level) const;
297         void do_print_python_repr(const print_python_repr & c, unsigned level) const;
298         
299         // member variables
300 protected:
301         mutable unsigned flags;             ///< of type status_flags
302         mutable unsigned hashvalue;         ///< hash value
303 };
304
305 // global variables
306
307 extern int max_recursion_level;
308
309
310 // convenience type checker template functions
311
312 /** Check if obj is a T, including base classes. */
313 template <class T>
314 inline bool is_a(const basic &obj)
315 {
316         return dynamic_cast<const T *>(&obj) != nullptr;
317 }
318
319 /** Check if obj is a T, not including base classes. */
320 template <class T>
321 inline bool is_exactly_a(const basic & obj)
322 {
323         return typeid(T) == typeid(obj);
324 }
325
326 /** Constructs a new (class basic or derived) B object on the heap.
327  *
328  *  This function picks the object's ctor based on the given argument types.
329  *
330  *  This helps the constructor of ex from basic (or a derived class B) because
331  *  then the constructor doesn't have to duplicate the object onto the heap.
332  *  See ex::construct_from_basic(const basic &) for more information.
333  */
334 template<class B, typename... Args>
335 inline B & dynallocate(Args &&... args)
336 {
337         return const_cast<B &>(static_cast<const B &>((new B(std::forward<Args>(args)...))->setflag(status_flags::dynallocated)));
338 }
339 /** Constructs a new (class basic or derived) B object on the heap.
340  *
341  *  This function is needed for GiNaC classes which have public ctors from
342  *  initializer lists of expressions (which are not a type and not captured
343  *  by the variadic template version).
344  */
345 template<class B>
346 inline B & dynallocate(std::initializer_list<ex> il)
347 {
348         return const_cast<B &>(static_cast<const B &>((new B(il))->setflag(status_flags::dynallocated)));
349 }
350
351 } // namespace GiNaC
352
353 #endif // ndef GINAC_BASIC_H