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