3 * Implementation of GiNaC's ABC. */
6 * GiNaC Copyright (C) 1999-2001 Johannes Gutenberg University Mainz, Germany
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.
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.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
40 GINAC_IMPLEMENT_REGISTERED_CLASS_NO_CTORS(basic, void)
43 // default ctor, dtor, copy ctor assignment operator and helpers
48 basic::basic(const basic & other) : tinfo_key(TINFO_basic), flags(0), refcount(0)
50 debugmsg("basic copy ctor", LOGLEVEL_CONSTRUCT);
54 const basic & basic::operator=(const basic & other)
56 debugmsg("basic operator=", LOGLEVEL_ASSIGNMENT);
66 // none (all conditionally inlined)
72 // none (all conditionally inlined)
78 /** Construct object from archive_node. */
79 basic::basic(const archive_node &n, const lst &sym_lst) : flags(0), refcount(0)
81 debugmsg("basic ctor from archive_node", LOGLEVEL_CONSTRUCT);
83 // Reconstruct tinfo_key from class name
84 std::string class_name;
85 if (n.find_string("class", class_name))
86 tinfo_key = find_tinfo_key(class_name);
88 throw (std::runtime_error("archive node contains no class name"));
91 /** Unarchive the object. */
92 ex basic::unarchive(const archive_node &n, const lst &sym_lst)
94 return (new basic(n, sym_lst))->setflag(status_flags::dynallocated);
97 /** Archive the object. */
98 void basic::archive(archive_node &n) const
100 n.add_string("class", class_name());
104 // functions overriding virtual functions from bases classes
110 // new virtual functions which can be overridden by derived classes
115 /** Output to ostream formatted as parsable (as in ginsh) input.
116 * Generally, superfluous parenthesis should be avoided as far as possible. */
117 void basic::print(std::ostream & os, unsigned upper_precedence) const
119 debugmsg("basic print",LOGLEVEL_PRINT);
120 os << "[basic object]";
123 /** Output to ostream in ugly raw format, so brave developers can have a look
124 * at the underlying structure. */
125 void basic::printraw(std::ostream & os) const
127 debugmsg("basic printraw",LOGLEVEL_PRINT);
128 os << "[basic object]";
131 /** Output to ostream formatted in tree- (indented-) form, so developers can
132 * have a look at the underlying structure. */
133 void basic::printtree(std::ostream & os, unsigned indent) const
135 debugmsg("basic printtree",LOGLEVEL_PRINT);
136 os << std::string(indent,' ') << "type=" << class_name()
137 << ", hash=" << hashvalue
138 << " (0x" << std::hex << hashvalue << std::dec << ")"
139 << ", flags=" << flags
140 << ", nops=" << nops() << std::endl;
141 for (unsigned i=0; i<nops(); ++i) {
142 op(i).printtree(os,indent+delta_indent);
146 /** Output to ostream formatted as C-source.
148 * @param os a stream for output
149 * @param type variable type (one of the csrc_types)
150 * @param upper_precedence operator precedence of caller
151 * @see ex::printcsrc */
152 void basic::printcsrc(std::ostream & os, unsigned type, unsigned upper_precedence) const
154 debugmsg("basic print csrc", LOGLEVEL_PRINT);
157 /** Little wrapper arount print to be called within a debugger.
158 * This is needed because you cannot call foo.print(cout) from within the
159 * debugger because it might not know what cout is. This method can be
160 * invoked with no argument and it will simply print to stdout.
162 * @see basic::print*/
163 void basic::dbgprint(void) const
165 this->print(std::cerr);
166 std::cerr << std::endl;
169 /** Little wrapper arount printtree to be called within a debugger.
171 * @see basic::dbgprint
172 * @see basic::printtree */
173 void basic::dbgprinttree(void) const
175 this->printtree(std::cerr,0);
178 /** Create a new copy of this on the heap. One can think of this as simulating
179 * a virtual copy constructor which is needed for instance by the refcounted
180 * construction of an ex from a basic. */
181 basic * basic::duplicate() const
183 debugmsg("basic duplicate",LOGLEVEL_DUPLICATE);
184 return new basic(*this);
187 /** Information about the object.
189 * @see class info_flags */
190 bool basic::info(unsigned inf) const
192 // all possible properties are false for basic objects
196 /** Number of operands/members. */
197 unsigned basic::nops() const
199 // iterating from 0 to nops() on atomic objects should be an empty loop,
200 // and accessing their elements is a range error. Container objects should
205 /** Return operand/member at position i. */
206 ex basic::op(int i) const
208 return (const_cast<basic *>(this))->let_op(i);
211 /** Return modifyable operand/member at position i. */
212 ex & basic::let_op(int i)
214 throw(std::out_of_range("op() out of range"));
217 ex basic::operator[](const ex & index) const
219 if (is_exactly_of_type(*index.bp,numeric))
220 return op(static_cast<const numeric &>(*index.bp).to_int());
222 throw(std::invalid_argument("non-numeric indices not supported by this type"));
225 ex basic::operator[](int i) const
230 /** Search ocurrences. An object 'has' an expression if it is the expression
231 * itself or one of the children 'has' it. As a consequence (according to
232 * the definition of children) given e=x+y+z, e.has(x) is true but e.has(x+y)
234 bool basic::has(const ex & other) const
236 GINAC_ASSERT(other.bp!=0);
237 if (is_equal(*other.bp)) return true;
239 for (unsigned i=0; i<nops(); i++)
240 if (op(i).has(other))
247 /** Return degree of highest power in symbol s. */
248 int basic::degree(const symbol & s) const
253 /** Return degree of lowest power in symbol s. */
254 int basic::ldegree(const symbol & s) const
259 /** Return coefficient of degree n in symbol s. */
260 ex basic::coeff(const symbol & s, int n) const
262 return n==0 ? *this : _ex0();
265 /** Sort expression in terms of powers of some symbol.
266 * @param s symbol to sort in. */
267 ex basic::collect(const symbol & s) const
270 for (int n=this->ldegree(s); n<=this->degree(s); n++)
271 x += this->coeff(s,n)*power(s,n);
276 /** Perform automatic non-interruptive symbolic evaluation on expression. */
277 ex basic::eval(int level) const
279 // There is nothing to do for basic objects:
283 /** Evaluate object numerically. */
284 ex basic::evalf(int level) const
286 // There is nothing to do for basic objects:
290 /** Substitute a set of symbols by arbitrary expressions. The ex returned
291 * will already be evaluated. */
292 ex basic::subs(const lst & ls, const lst & lr) const
297 /** Default interface of nth derivative ex::diff(s, n). It should be called
298 * instead of ::derivative(s) for first derivatives and for nth derivatives it
299 * just recurses down.
301 * @param s symbol to differentiate in
302 * @param nth order of differentiation
304 ex basic::diff(const symbol & s, unsigned nth) const
306 // trivial: zeroth derivative
310 // evaluate unevaluated *this before differentiating
311 if (!(flags & status_flags::evaluated))
312 return ex(*this).diff(s, nth);
314 ex ndiff = this->derivative(s);
315 while (!ndiff.is_zero() && // stop differentiating zeros
317 ndiff = ndiff.diff(s);
323 exvector basic::get_indices(void) const
325 return exvector(); // return an empty exvector
328 ex basic::simplify_ncmul(const exvector & v) const
330 return simplified_ncmul(v);
335 /** Default implementation of ex::diff(). It simply throws an error message.
337 * @exception logic_error (differentiation not supported by this type)
339 ex basic::derivative(const symbol & s) const
341 throw(std::logic_error("differentiation not supported by this type"));
344 /** Returns order relation between two objects of same type. This needs to be
345 * implemented by each class. It may never return anything else than 0,
346 * signalling equality, or +1 and -1 signalling inequality and determining
347 * the canonical ordering. */
348 int basic::compare_same_type(const basic & other) const
350 return compare_pointers(this, &other);
353 /** Returns true if two objects of same type are equal. Normally needs
354 * not be reimplemented as long as it wasn't overwritten by some parent
355 * class, since it just calls compare_same_type(). The reason why this
356 * function exists is that sometimes it is easier to determine equality
357 * than an order relation and then it can be overridden. */
358 bool basic::is_equal_same_type(const basic & other) const
360 return this->compare_same_type(other)==0;
363 unsigned basic::return_type(void) const
365 return return_types::commutative;
368 unsigned basic::return_type_tinfo(void) const
373 /** Compute the hash value of an object and if it makes sense to store it in
374 * the objects status_flags, do so. The method inherited from class basic
375 * computes a hash value based on the type and hash values of possible
376 * members. For this reason it is well suited for container classes but
377 * atomic classes should override this implementation because otherwise they
378 * would all end up with the same hashvalue. */
379 unsigned basic::calchash(void) const
381 unsigned v = golden_ratio_hash(tinfo());
382 for (unsigned i=0; i<nops(); i++) {
383 v = rotate_left_31(v);
384 v ^= (const_cast<basic *>(this))->op(i).gethash();
387 // mask out numeric hashes:
390 // store calculated hash value only if object is already evaluated
391 if (flags & status_flags::evaluated) {
392 setflag(status_flags::hash_calculated);
399 /** Expand expression, i.e. multiply it out and return the result as a new
401 ex basic::expand(unsigned options) const
403 return this->setflag(status_flags::expanded);
408 // non-virtual functions in this class
413 /** Substitute symbols in expression and return the result as a new expression.
414 * There are two valid types of replacement arguments: 1) a relational like
415 * symbol==ex and 2) a list of relationals lst(symbol1==ex1,symbol2==ex2,...),
416 * which is converted to subs(lst(symbol1,symbol2,...),lst(ex1,ex2,...)).
417 * In addition, an object of class idx can be used instead of a symbol. */
418 ex basic::subs(const ex & e) const
420 if (e.info(info_flags::relation_equal)) {
423 if (!e.info(info_flags::list)) {
424 throw(std::invalid_argument("basic::subs(ex): argument must be a list"));
428 for (unsigned i=0; i<e.nops(); i++) {
429 if (!e.op(i).info(info_flags::relation_equal)) {
430 throw(std::invalid_argument("basic::subs(ex): argument must be a list or equations"));
432 if (!e.op(i).op(0).info(info_flags::symbol)) {
433 if (!e.op(i).op(0).info(info_flags::idx)) {
434 throw(std::invalid_argument("basic::subs(ex): lhs must be a symbol or an idx"));
437 ls.append(e.op(i).op(0));
438 lr.append(e.op(i).op(1));
443 /** Compare objects to establish canonical ordering.
444 * All compare functions return: -1 for *this less than other, 0 equal,
446 int basic::compare(const basic & other) const
448 unsigned hash_this = gethash();
449 unsigned hash_other = other.gethash();
451 if (hash_this<hash_other) return -1;
452 if (hash_this>hash_other) return 1;
454 unsigned typeid_this = tinfo();
455 unsigned typeid_other = other.tinfo();
457 if (typeid_this<typeid_other) {
458 // std::cout << "hash collision, different types: "
459 // << *this << " and " << other << std::endl;
460 // this->printraw(std::cout);
461 // std::cout << " and ";
462 // other.printraw(std::cout);
463 // std::cout << std::endl;
466 if (typeid_this>typeid_other) {
467 // std::cout << "hash collision, different types: "
468 // << *this << " and " << other << std::endl;
469 // this->printraw(std::cout);
470 // std::cout << " and ";
471 // other.printraw(std::cout);
472 // std::cout << std::endl;
476 GINAC_ASSERT(typeid(*this)==typeid(other));
478 int cmpval = compare_same_type(other);
479 if ((cmpval!=0) && (hash_this<0x80000000U)) {
480 // std::cout << "hash collision, same type: "
481 // << *this << " and " << other << std::endl;
482 // this->printraw(std::cout);
483 // std::cout << " and ";
484 // other.printraw(std::cout);
485 // std::cout << std::endl;
490 /** Test for equality.
491 * This is only a quick test, meaning objects should be in the same domain.
492 * You might have to .expand(), .normal() objects first, depending on the
493 * domain of your computation, to get a more reliable answer.
495 * @see is_equal_same_type */
496 bool basic::is_equal(const basic & other) const
498 if (this->gethash()!=other.gethash())
500 if (this->tinfo()!=other.tinfo())
503 GINAC_ASSERT(typeid(*this)==typeid(other));
505 return this->is_equal_same_type(other);
510 /** Stop further evaluation.
512 * @see basic::eval */
513 const basic & basic::hold(void) const
515 return this->setflag(status_flags::evaluated);
518 /** Ensure the object may be modified without hurting others, throws if this
519 * is not the case. */
520 void basic::ensure_if_modifiable(void) const
522 if (this->refcount>1)
523 throw(std::runtime_error("cannot modify multiply referenced object"));
527 // static member variables
532 unsigned basic::precedence = 70;
533 unsigned basic::delta_indent = 4;
539 int max_recursion_level = 1024;