]> www.ginac.de Git - ginac.git/blob - ginac/archive.cpp
[nitpick] power::expand_add(): don't use int instead of std::size_t.
[ginac.git] / ginac / archive.cpp
1 /** @file archive.cpp
2  *
3  *  Archiving of GiNaC expressions. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2008 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 #include <iostream>
24 #include <stdexcept>
25
26 #include "archive.h"
27 #include "registrar.h"
28 #include "ex.h"
29 #include "lst.h"
30 #include "config.h"
31 #include "tostring.h"
32
33 namespace GiNaC {
34
35
36 void archive::archive_ex(const ex &e, const char *name)
37 {
38         // Create root node (which recursively archives the whole expression tree)
39         // and add it to the archive
40         archive_node_id id = add_node(archive_node(*this, e));
41
42         // Add root node ID to list of archived expressions
43         archived_ex ae = archived_ex(atomize(name), id);
44         exprs.push_back(ae);
45 }
46
47
48 /** Add archive_node to archive if the corresponding expression is
49  *  not already archived.
50  *  @return ID of archived node */
51 archive_node_id archive::add_node(const archive_node &n)
52 {
53         // Look if expression is known to be in some node already.
54         if (n.has_ex()) {
55                 mapit i = exprtable.find(n.get_ex());
56                 if (i != exprtable.end())
57                         return i->second;
58                 nodes.push_back(n);
59                 exprtable[n.get_ex()] = nodes.size() - 1;
60                 return nodes.size() - 1;
61         }
62
63         // Not found, add archive_node to nodes vector
64         nodes.push_back(n);
65         return nodes.size()-1;
66 }
67
68
69 /** Retrieve archive_node by ID. */
70 archive_node &archive::get_node(archive_node_id id)
71 {
72         if (id >= nodes.size())
73                 throw (std::range_error("archive::get_node(): archive node ID out of range"));
74
75         return nodes[id];
76 }
77
78
79 ex archive::unarchive_ex(const lst &sym_lst, const char *name) const
80 {
81         // Find root node
82         std::string name_string = name;
83         archive_atom id = atomize(name_string);
84         std::vector<archived_ex>::const_iterator i = exprs.begin(), iend = exprs.end();
85         while (i != iend) {
86                 if (i->name == id)
87                         goto found;
88                 i++;
89         }
90         throw (std::runtime_error("expression with name '" + name_string + "' not found in archive"));
91
92 found:
93         // Recursively unarchive all nodes, starting at the root node
94         lst sym_lst_copy = sym_lst;
95         return nodes[i->root].unarchive(sym_lst_copy);
96 }
97
98 ex archive::unarchive_ex(const lst &sym_lst, unsigned index) const
99 {
100         if (index >= exprs.size())
101                 throw (std::range_error("index of archived expression out of range"));
102
103         // Recursively unarchive all nodes, starting at the root node
104         lst sym_lst_copy = sym_lst;
105         return nodes[exprs[index].root].unarchive(sym_lst_copy);
106 }
107
108 ex archive::unarchive_ex(const lst &sym_lst, std::string &name, unsigned index) const
109 {
110         if (index >= exprs.size())
111                 throw (std::range_error("index of archived expression out of range"));
112
113         // Return expression name
114         name = unatomize(exprs[index].name);
115
116         // Recursively unarchive all nodes, starting at the root node
117         lst sym_lst_copy = sym_lst;
118         return nodes[exprs[index].root].unarchive(sym_lst_copy);
119 }
120
121 unsigned archive::num_expressions() const
122 {
123         return exprs.size();
124 }
125
126 const archive_node &archive::get_top_node(unsigned index) const
127 {
128         if (index >= exprs.size())
129                 throw (std::range_error("index of archived expression out of range"));
130
131         return nodes[exprs[index].root];
132 }
133
134
135 /*
136  *  Archive file format
137  *
138  *   - 4 bytes signature 'GARC'
139  *   - unsigned version number
140  *   - unsigned number of atoms
141  *      - atom strings (each zero-terminated)
142  *   - unsigned number of expressions
143  *      - unsigned name atom
144  *      - unsigned root node ID
145  *   - unsigned number of nodes
146  *      - unsigned number of properties
147  *        - unsigned containing type (PTYPE_*) in its lower 3 bits and
148  *          name atom in the upper bits
149  *        - unsigned property value
150  *
151  *  Unsigned quantities are stored in a compressed format:
152  *   - numbers in the range 0x00..0x7f are stored verbatim (1 byte)
153  *   - numbers larger than 0x7f are stored in 7-bit packets (1 byte per
154  *     packet), starting with the LSBs; all bytes except the last one have
155  *     their upper bit set
156  *
157  *  Examples:
158  *   0x00           =   0x00
159  *    ..                 ..
160  *   0x7f           =   0x7f
161  *   0x80 0x01      =   0x80
162  *    ..   ..            ..
163  *   0xff 0x01      =   0xff
164  *   0x80 0x02      =  0x100
165  *    ..   ..            ..
166  *   0xff 0x02      =  0x17f
167  *   0x80 0x03      =  0x180
168  *    ..   ..            ..
169  *   0xff 0x7f      = 0x3fff
170  *   0x80 0x80 0x01 = 0x4000
171  *    ..   ..   ..       ..
172  */
173
174 /** Write unsigned integer quantity to stream. */
175 static void write_unsigned(std::ostream &os, unsigned val)
176 {
177         while (val >= 0x80) {
178                 os.put((val & 0x7f) | 0x80);
179                 val >>= 7;
180         }
181         os.put(val);
182 }
183
184 /** Read unsigned integer quantity from stream. */
185 static unsigned read_unsigned(std::istream &is)
186 {
187         unsigned char b;
188         unsigned ret = 0;
189         unsigned shift = 0;
190         do {
191                 char b2;
192                 is.get(b2);
193                 b = b2;
194                 ret |= (b & 0x7f) << shift;
195                 shift += 7;
196         } while (b & 0x80);
197         return ret;
198 }
199
200 /** Write archive_node to binary data stream. */
201 std::ostream &operator<<(std::ostream &os, const archive_node &n)
202 {
203         // Write properties
204         unsigned num_props = n.props.size();
205         write_unsigned(os, num_props);
206         for (unsigned i=0; i<num_props; i++) {
207                 write_unsigned(os, n.props[i].type | (n.props[i].name << 3));
208                 write_unsigned(os, n.props[i].value);
209         }
210         return os;
211 }
212
213 /** Write archive to binary data stream. */
214 std::ostream &operator<<(std::ostream &os, const archive &ar)
215 {
216         // Write header
217         os.put('G');    // Signature
218         os.put('A');
219         os.put('R');
220         os.put('C');
221         write_unsigned(os, ARCHIVE_VERSION);
222
223         // Write atoms
224         unsigned num_atoms = ar.atoms.size();
225         write_unsigned(os, num_atoms);
226         for (unsigned i=0; i<num_atoms; i++)
227                 os << ar.atoms[i] << std::ends;
228
229         // Write expressions
230         unsigned num_exprs = ar.exprs.size();
231         write_unsigned(os, num_exprs);
232         for (unsigned i=0; i<num_exprs; i++) {
233                 write_unsigned(os, ar.exprs[i].name);
234                 write_unsigned(os, ar.exprs[i].root);
235         }
236
237         // Write nodes
238         unsigned num_nodes = ar.nodes.size();
239         write_unsigned(os, num_nodes);
240         for (unsigned i=0; i<num_nodes; i++)
241                 os << ar.nodes[i];
242         return os;
243 }
244
245 /** Read archive_node from binary data stream. */
246 std::istream &operator>>(std::istream &is, archive_node &n)
247 {
248         // Read properties
249         unsigned num_props = read_unsigned(is);
250         n.props.resize(num_props);
251         for (unsigned i=0; i<num_props; i++) {
252                 unsigned name_type = read_unsigned(is);
253                 n.props[i].type = (archive_node::property_type)(name_type & 7);
254                 n.props[i].name = name_type >> 3;
255                 n.props[i].value = read_unsigned(is);
256         }
257         return is;
258 }
259
260 /** Read archive from binary data stream. */
261 std::istream &operator>>(std::istream &is, archive &ar)
262 {
263         // Read header
264         char c1, c2, c3, c4;
265         is.get(c1); is.get(c2); is.get(c3); is.get(c4);
266         if (c1 != 'G' || c2 != 'A' || c3 != 'R' || c4 != 'C')
267                 throw (std::runtime_error("not a GiNaC archive (signature not found)"));
268         unsigned version = read_unsigned(is);
269         if (version > ARCHIVE_VERSION || version < ARCHIVE_VERSION - ARCHIVE_AGE)
270                 throw (std::runtime_error("archive version " + ToString(version) + " cannot be read by this GiNaC library (which supports versions " + ToString(ARCHIVE_VERSION-ARCHIVE_AGE) + " thru " + ToString(ARCHIVE_VERSION)));
271
272         // Read atoms
273         unsigned num_atoms = read_unsigned(is);
274         ar.atoms.resize(num_atoms);
275         for (unsigned i=0; i<num_atoms; i++) {
276                 getline(is, ar.atoms[i], '\0');
277                 ar.inverse_atoms[ar.atoms[i]] = i;
278         }
279
280         // Read expressions
281         unsigned num_exprs = read_unsigned(is);
282         ar.exprs.resize(num_exprs);
283         for (unsigned i=0; i<num_exprs; i++) {
284                 archive_atom name = read_unsigned(is);
285                 archive_node_id root = read_unsigned(is);
286                 ar.exprs[i] = archive::archived_ex(name, root);
287         }
288
289         // Read nodes
290         unsigned num_nodes = read_unsigned(is);
291         ar.nodes.resize(num_nodes, ar);
292         for (unsigned i=0; i<num_nodes; i++)
293                 is >> ar.nodes[i];
294         return is;
295 }
296
297
298 /** Atomize a string (i.e. convert it into an ID number that uniquely
299  *  represents the string). */
300 archive_atom archive::atomize(const std::string &s) const
301 {
302         // Search for string in inverse_atoms map.
303         inv_at_cit i = inverse_atoms.find(s);
304         if (i!=inverse_atoms.end())
305                 return i->second;
306
307         // Not found, add to atoms vector
308         archive_atom id = atoms.size();
309         atoms.push_back(s);
310         inverse_atoms[s] = id;
311         return id;
312 }
313
314 /** Unatomize a string (i.e. convert the ID number back to the string). */
315 const std::string &archive::unatomize(archive_atom id) const
316 {
317         if (id >= atoms.size())
318                 throw (std::range_error("archive::unatomizee(): atom ID out of range"));
319
320         return atoms[id];
321 }
322
323
324 /** Assignment operator of archive_node. */
325 const archive_node &archive_node::operator=(const archive_node &other)
326 {
327         if (this != &other) {
328                 // archive &a member doesn't get copied
329                 props = other.props;
330                 has_expression = other.has_expression;
331                 e = other.e;
332         }
333         return *this;
334 }
335
336
337 /** Recursively construct archive node from expression. */
338 archive_node::archive_node(archive &ar, const ex &expr)
339   : a(ar), has_expression(true), e(expr)
340 {
341         expr.bp->archive(*this);
342 }
343
344
345 /** Check if the archive_node stores the same expression as another
346  *  archive_node.
347  *  @return "true" if expressions are the same */
348 bool archive_node::has_same_ex_as(const archive_node &other) const
349 {
350         if (!has_expression || !other.has_expression)
351                 return false;
352         return e.bp == other.e.bp;
353 }
354
355 archive_node::archive_node_cit
356                 archive_node::find_first(const std::string &name) const
357 {       
358         archive_atom name_atom = a.atomize(name);
359         for (archive_node_cit i=props.begin(); i!=props.end(); ++i)
360                 if (i->name == name_atom)
361                         return i;
362         return props.end();;
363 }
364
365 archive_node::archive_node_cit
366                 archive_node::find_last(const std::string &name) const
367 {
368         archive_atom name_atom = a.atomize(name);
369         for (archive_node_cit i=props.end(); i!=props.begin();) {
370                 --i;
371                 if (i->name == name_atom)
372                         return i;
373         }
374         return props.end();
375 }
376
377 void archive_node::add_bool(const std::string &name, bool value)
378 {
379         props.push_back(property(a.atomize(name), PTYPE_BOOL, value));
380 }
381
382 void archive_node::add_unsigned(const std::string &name, unsigned value)
383 {
384         props.push_back(property(a.atomize(name), PTYPE_UNSIGNED, value));
385 }
386
387 void archive_node::add_string(const std::string &name, const std::string &value)
388 {
389         props.push_back(property(a.atomize(name), PTYPE_STRING, a.atomize(value)));
390 }
391
392 void archive_node::add_ex(const std::string &name, const ex &value)
393 {
394         // Recursively create an archive_node and add its ID to the properties of this node
395         archive_node_id id = a.add_node(archive_node(a, value));
396         props.push_back(property(a.atomize(name), PTYPE_NODE, id));
397 }
398
399
400 bool archive_node::find_bool(const std::string &name, bool &ret, unsigned index) const
401 {
402         archive_atom name_atom = a.atomize(name);
403         archive_node_cit i = props.begin(), iend = props.end();
404         unsigned found_index = 0;
405         while (i != iend) {
406                 if (i->type == PTYPE_BOOL && i->name == name_atom) {
407                         if (found_index == index) {
408                                 ret = i->value;
409                                 return true;
410                         }
411                         found_index++;
412                 }
413                 i++;
414         }
415         return false;
416 }
417
418 bool archive_node::find_unsigned(const std::string &name, unsigned &ret, unsigned index) const
419 {
420         archive_atom name_atom = a.atomize(name);
421         archive_node_cit i = props.begin(), iend = props.end();
422         unsigned found_index = 0;
423         while (i != iend) {
424                 if (i->type == PTYPE_UNSIGNED && i->name == name_atom) {
425                         if (found_index == index) {
426                                 ret = i->value;
427                                 return true;
428                         }
429                         found_index++;
430                 }
431                 i++;
432         }
433         return false;
434 }
435
436 bool archive_node::find_string(const std::string &name, std::string &ret, unsigned index) const
437 {
438         archive_atom name_atom = a.atomize(name);
439         archive_node_cit i = props.begin(), iend = props.end();
440         unsigned found_index = 0;
441         while (i != iend) {
442                 if (i->type == PTYPE_STRING && i->name == name_atom) {
443                         if (found_index == index) {
444                                 ret = a.unatomize(i->value);
445                                 return true;
446                         }
447                         found_index++;
448                 }
449                 i++;
450         }
451         return false;
452 }
453
454 void archive_node::find_ex_by_loc(archive_node_cit loc, ex &ret, lst &sym_lst)
455                 const
456 {
457         ret = a.get_node(loc->value).unarchive(sym_lst);
458 }
459
460 bool archive_node::find_ex(const std::string &name, ex &ret, lst &sym_lst, unsigned index) const
461 {
462         archive_atom name_atom = a.atomize(name);
463         archive_node_cit i = props.begin(), iend = props.end();
464         unsigned found_index = 0;
465         while (i != iend) {
466                 if (i->type == PTYPE_NODE && i->name == name_atom) {
467                         if (found_index == index) {
468                                 ret = a.get_node(i->value).unarchive(sym_lst);
469                                 return true;
470                         }
471                         found_index++;
472                 }
473                 i++;
474         }
475         return false;
476 }
477
478 const archive_node &archive_node::find_ex_node(const std::string &name, unsigned index) const
479 {
480         archive_atom name_atom = a.atomize(name);
481         archive_node_cit i = props.begin(), iend = props.end();
482         unsigned found_index = 0;
483         while (i != iend) {
484                 if (i->type == PTYPE_NODE && i->name == name_atom) {
485                         if (found_index == index)
486                                 return a.get_node(i->value);
487                         found_index++;
488                 }
489                 i++;
490         }
491         throw (std::runtime_error("property with name '" + name + "' not found in archive node"));
492 }
493
494
495 void archive_node::get_properties(propinfovector &v) const
496 {
497         v.clear();
498         archive_node_cit i = props.begin(), iend = props.end();
499         while (i != iend) {
500                 property_type type = i->type;
501                 std::string name = a.unatomize(i->name);
502
503                 propinfovector::iterator a = v.begin(), aend = v.end();
504                 bool found = false;
505                 while (a != aend) {
506                         if (a->type == type && a->name == name) {
507                                 a->count++;
508                                 found = true;
509                                 break;
510                         }
511                         ++a;
512                 }
513                 if (!found)
514                         v.push_back(property_info(type, name));
515                 i++;
516         }       
517 }
518
519
520 /** Convert archive node to GiNaC expression. */
521 ex archive_node::unarchive(lst &sym_lst) const
522 {
523         // Already unarchived? Then return cached unarchived expression.
524         if (has_expression)
525                 return e;
526
527         // Find instantiation function for class specified in node
528         std::string class_name;
529         if (!find_string("class", class_name))
530                 throw (std::runtime_error("archive node contains no class name"));
531         unarch_func f = find_unarch_func(class_name);
532
533         // Call instantiation function
534         e = f(*this, sym_lst);
535         has_expression = true;
536         return e;
537 }
538
539
540 void archive::clear()
541 {
542         atoms.clear();
543         inverse_atoms.clear();
544         exprs.clear();
545         nodes.clear();
546         exprtable.clear();
547 }
548
549
550 /** Delete cached unarchived expressions in all archive_nodes (mainly for debugging). */
551 void archive::forget()
552 {
553         for_each(nodes.begin(), nodes.end(), std::mem_fun_ref(&archive_node::forget));
554 }
555
556 /** Delete cached unarchived expressions from node (for debugging). */
557 void archive_node::forget()
558 {
559         has_expression = false;
560         e = 0;
561 }
562
563
564 /** Print archive to stream in ugly raw format (for debugging). */
565 void archive::printraw(std::ostream &os) const
566 {
567         // Dump atoms
568         os << "Atoms:\n";
569         {
570                 std::vector<std::string>::const_iterator i = atoms.begin(), iend = atoms.end();
571                 archive_atom id = 0;
572                 while (i != iend) {
573                         os << " " << id << " " << *i << std::endl;
574                         i++; id++;
575                 }
576         }
577         os << std::endl;
578
579         // Dump expressions
580         os << "Expressions:\n";
581         {
582                 std::vector<archived_ex>::const_iterator i = exprs.begin(), iend = exprs.end();
583                 unsigned index = 0;
584                 while (i != iend) {
585                         os << " " << index << " \"" << unatomize(i->name) << "\" root node " << i->root << std::endl;
586                         i++; index++;
587                 }
588         }
589         os << std::endl;
590
591         // Dump nodes
592         os << "Nodes:\n";
593         {
594                 std::vector<archive_node>::const_iterator i = nodes.begin(), iend = nodes.end();
595                 archive_node_id id = 0;
596                 while (i != iend) {
597                         os << " " << id << " ";
598                         i->printraw(os);
599                         i++; id++;
600                 }
601         }
602 }
603
604 /** Output archive_node to stream in ugly raw format (for debugging). */
605 void archive_node::printraw(std::ostream &os) const
606 {
607         // Dump cached unarchived expression
608         if (has_expression)
609                 os << "(basic * " << e.bp << " = " << e << ")\n";
610         else
611                 os << "\n";
612
613         // Dump properties
614         archive_node_cit i = props.begin(), iend = props.end();
615         while (i != iend) {
616                 os << "  ";
617                 switch (i->type) {
618                         case PTYPE_BOOL: os << "bool"; break;
619                         case PTYPE_UNSIGNED: os << "unsigned"; break;
620                         case PTYPE_STRING: os << "string"; break;
621                         case PTYPE_NODE: os << "node"; break;
622                         default: os << "<unknown>"; break;
623                 }
624                 os << " \"" << a.unatomize(i->name) << "\" " << i->value << std::endl;
625                 i++;
626         }
627 }
628
629 /** Create a dummy archive.  The intention is to fill archive_node's default
630  *  ctor, which is currently a Cint-requirement. */
631 archive* archive_node::dummy_ar_creator()
632 {
633         static archive* some_ar = new archive;
634         return some_ar;
635 }
636
637
638 } // namespace GiNaC