/* * demo.cpp * * Script interpreter examples: demo program. * * Copyright (c) 1996-2000 Parsifal Software. * All Rights Reserved. * * For further information about this program or the AnaGram * parser generator, please contact: * * Parsifal Software * http://www.parsifalsoft.com * info@parsifalsoft.com * +1-800-879-2577, Voice/Fax +1-508-358-2564 * P.O. Box 219 * Wayland, MA 01778 * USA */ #include "comdefs.h" // Code common to all four script interpreters #include "agsort.h" #include "agset.h" #ifdef USE_STD #include #include using namespace std; #else #include #include #endif struct Pair : public AgKVPair { Pair() : AgKVPair() {} Pair(const AgKVPair &p) : AgKVPair(p) {} Pair(const Pair &p) : AgKVPair(p) {} const int &alternateKey() const {return value();} }; AgMap makeMap(const AgDictionary &d) { AgMap map; int n = d.size(); while (n--) { const char *s = d[n]; int k, sum = 0; for (k = strlen(s); k--;) sum += s[k]; map.value(s) = sum; } return map; } void dumpMap(const AgMap &m, const char *name) { for (int i = 0; i < m.size(); i++) { const AgKVPair &p = m[i]; cout << name << "[" << (const char *) p.key() << "] = " << p.value() << "\n"; } } int main(int argc, char *argv[]) { // Check usage if (argc != 2) { cerr << "Usage: " << argv[0] << " \n"; return 1; } // Read the file. ifstream inputFile(argv[1]); if (!inputFile) { AgString fileName(argv[1]); fileName.append(".scf"); inputFile.clear(); inputFile.open((const char *) fileName); if (!inputFile) { cerr << argv[0] << ": Cannot open " << argv[1] << " or " << (const char *) fileName << "\n"; return 1; } } // Find length of file inputFile.seekg(0, ios::end); long length = inputFile.tellg(); // Rewind inputFile.seekg(0, ios::beg); // Make space to read the file char *script = new char[length+1]; // Read the file inputFile.read(script, length); length = inputFile.gcount(); // Under windows & dos, the number of bytes read may be less than // allocation because of discarded carriage returns. script[length] = 0; // Create symbol table AgDictionary symbolDictionary; // ensure dictionary entry for the variables "xyz" and "uvw" int xyzId = symbolDictionary.intern("xyz"); symbolDictionary.intern("uvw"); // Create data object Dataset dataset(symbolDictionary); // Initialize values of xyz and uvw // (demonstrating two different ways to do it, by index and by name) dataset[xyzId] = 73; dataset.value("uvw") = 47; // Execute interpreter: apply the script to dataset. try { interpret(script, dataset); } catch(ErrorDiagnostic e) { const char *msg = (const char *) e.message(); cout << msg; cout << "\n"; } // Now display values of all variables cout << "\n\nComputed Values:\n\n"; AgArray sortPermutation = agSort(symbolDictionary); int i; for (i=0; i