File: testparser.C

package info (click to toggle)
paraview 3.14.1-6
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 234,468 kB
  • sloc: cpp: 2,166,013; ansic: 801,575; xml: 58,068; tcl: 49,247; python: 43,091; java: 16,625; fortran: 12,224; sh: 11,722; yacc: 5,688; perl: 3,128; makefile: 2,228; lex: 1,311; lisp: 486; asm: 471; pascal: 228
file content (349 lines) | stat: -rw-r--r-- 10,833 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/*****************************************************************************
*
* Copyright (c) 2000 - 2010, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* LLNL-CODE-400124
* All rights reserved.
*
* This file is  part of VisIt. For  details, see https://visit.llnl.gov/.  The
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution  and  use  in  source  and  binary  forms,  with  or  without
* modification, are permitted provided that the following conditions are met:
*
*  - Redistributions of  source code must  retain the above  copyright notice,
*    this list of conditions and the disclaimer below.
*  - Redistributions in binary form must reproduce the above copyright notice,
*    this  list of  conditions  and  the  disclaimer (as noted below)  in  the
*    documentation and/or other materials provided with the distribution.
*  - Neither the name of  the LLNS/LLNL nor the names of  its contributors may
*    be used to endorse or promote products derived from this software without
*    specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT  HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR  IMPLIED WARRANTIES, INCLUDING,  BUT NOT  LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND  FITNESS FOR A PARTICULAR  PURPOSE
* ARE  DISCLAIMED. IN  NO EVENT  SHALL LAWRENCE  LIVERMORE NATIONAL  SECURITY,
* LLC, THE  U.S.  DEPARTMENT OF  ENERGY  OR  CONTRIBUTORS BE  LIABLE  FOR  ANY
* DIRECT,  INDIRECT,   INCIDENTAL,   SPECIAL,   EXEMPLARY,  OR   CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT  LIMITED TO, PROCUREMENT OF  SUBSTITUTE GOODS OR
* SERVICES; LOSS OF  USE, DATA, OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER
* CAUSED  AND  ON  ANY  THEORY  OF  LIABILITY,  WHETHER  IN  CONTRACT,  STRICT
* LIABILITY, OR TORT  (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY  WAY
* OUT OF THE  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*****************************************************************************/

#include "Token.h"
#include "Scanner.h"
#include "Grammar.h"
#include "VisItParser.h"
#include "ParseException.h"
#include "Symbol.h"
#include "Dictionary.h"

using std::string;
using std::vector;

// ----------------------------------------------------------------------------
// dictionary
// ----------------------------------------------------------------------------
Dictionary D;

// ----------------------------------------------------------------------------
// terminals
// ----------------------------------------------------------------------------
enum TokenType {
    TT_NoToken    = 0,
    // All single-character tokens go in this range
    TT_EOF        = EOF_TOKEN_ID,
    TT_Var
};
Symbol T_Plus(D, '+');
Symbol T_Mult(D, '*');
Symbol T_And(D,  '&');
Symbol T_Var(D, TT_Var, "Var");

// ----------------------------------------------------------------------------
// nonterminals
// ----------------------------------------------------------------------------
Symbol Expr(D, "Expr");

// ----------------------------------------------------------------------------
// Tokens
// ----------------------------------------------------------------------------
class Operator : public Token
{
  public:
    Operator(const Pos &p, char c) : Token(p,c), op(c) { }
    void PrintNode(ostream &o) { o << "Operator: "<<op<<endl; }
  public:
    char op;
};

class Var : public Token
{
  public:
    Var(const Pos &p, const std::string &v) : Token(p,TT_Var), name(v) { }
    void PrintNode(ostream &o) { o << "Var: "<<name<<endl; }
  public:
    string name;
};

// ----------------------------------------------------------------------------
// Scanner
// ----------------------------------------------------------------------------
class TestScanner : public Scanner
{
  public:
    TestScanner() { }
    virtual ~TestScanner() { }
    virtual void   SetInput(const std::string &s)
    {
        input = s;
        pos = 0;
    }
    virtual Token *ScanOneToken()
    {
        if (pos >= input.length())
            return new EndOfInput(pos);

        if (input[pos] == '+' || input[pos] == '-' ||
            input[pos] == '*' || input[pos] == '/' ||
            input[pos] == '^' || input[pos] == '%' ||
            input[pos] == '&')
        {
            Token *t = new Operator(pos, input[pos]);
            pos++;
            return t;
        }

        if (input[pos] < 'a' || input[pos] > 'z')
            EXCEPTION1(LexicalException, pos);

        string var;
        while (input[pos] >= 'a' && input[pos] <= 'z')
        {
            var += input[pos];
            pos++;
        }
        return new Var(Pos(pos - var.length(), pos-1), var);
    }
  private:
    string input;
    int pos;
};

// ----------------------------------------------------------------------------
// ParseTreeNodes
// ----------------------------------------------------------------------------
class BinaryExpression : public ParseTreeNode 
{
  public:
    BinaryExpression(const Pos &p, char op, ParseTreeNode *l, ParseTreeNode *r)
        : ParseTreeNode(p), oper(op), left(l), right(r) { }
    virtual ~BinaryExpression()
    {
        delete left;
        delete right;        
    }
    virtual const std::string GetTypeName() { return "BinaryExpression"; }
    virtual void PrintNode(ostream &o)
    {
        o << "BinaryExpression: '"<<oper<<"'" << endl;
        left->Print(o,"Left:  ");
        right->Print(o,"Right: ");
    }
  public:
    char oper;
    ParseTreeNode *left;
    ParseTreeNode *right;
};

class VarExpression : public ParseTreeNode
{
  public:
    VarExpression(const Pos &p, string &v) : ParseTreeNode(p), name(v) { }
    virtual ~VarExpression() { }
    virtual const std::string GetTypeName() {return "VarExpression";}
    virtual void PrintNode(ostream &o) { o << "Var: "<<name<<"\n"; }
  private:
    string name;
};

// ----------------------------------------------------------------------------
// Grammar Definition
// ----------------------------------------------------------------------------
class TestGrammar : public Grammar
{
  public:
    TestGrammar() : Grammar(D)
    {
        SetStartSymbol(Expr);

        AddRule(Rule(0, Expr) >> Expr + T_Plus + Expr );
        AddRule(Rule(1, Expr) >> Expr + T_Mult + Expr );
        AddRule(Rule(2, Expr) >> T_Var );
        AddRule(Rule(3, Expr) >> Expr + T_And + Expr );

        SetAssoc(T_Plus,  Grammar::Left);
        SetAssoc(T_Mult,  Grammar::Left);
        SetAssoc(T_And,   Grammar::NonAssoc);
        SetPrec(T_Plus,   1);
        SetPrec(T_Mult,   2);
        SetPrec(T_And,    2);
    }
    bool Initialize() { return false; } // only for pre-configuration 
    
};

// ----------------------------------------------------------------------------
// Parser
//
// Modifications:
//
//   Hank Childs, Fri Jan 28 15:43:04 PST 2005
//   Use expression macros.
//
//   Mark C. Miller, Wed Jun 17 14:27:08 PDT 2009
//   Replaced CATCHALL(...) with CATCHALL.
// ----------------------------------------------------------------------------
class TestParser : public Parser
{
  private:
    ParseTreeNode *ApplyRule(const Symbol &sym, const Rule *rule,
                           vector<ParseTreeNode*> &E,
                           vector<Token*> &T, Pos p)
    {
        ParseTreeNode *node = NULL;
        if (sym == Expr)
        {
            switch (rule->GetID())
            {
              case 0:
              case 1:
              case 3:
                node = new BinaryExpression(p,((Operator*)T[1])->op,E[0],E[2]);
                break;
              case 2:
                node = new VarExpression(p, ((Var*)T[0])->name);
                break;
            }
        }
        else if (sym == *G->GetStartSymbol())
        {
            node = E[0];
        }
        return node;
    }

  public:
    TestParser() : Parser()
    {
        Grammar *G = new TestGrammar;
#ifdef PRE_CONFIGURED
        if (!G->Initialize())
#else
        G->SetPrinter(&cout);
        if (!G->Configure())
#endif
        {
            cerr << "Error in initializion of Expression Grammar!\n";
        }
        else
        {
            /*
            cout<<"-------------------------------------------------------\n";
            cout<<"---------------- Grammar Configuration ----------------\n";
            cout<<"-------------------------------------------------------\n";
            G->WriteStateInitialization("TestGrammar", cout);
            cout<<"-------------------------------------------------------\n";
            cout<<"-------------- End Grammar Configuration --------------\n";
            cout<<"-------------------------------------------------------\n";
            */
            SetGrammar(G);
        }
    }

    TestParser::~TestParser()
    {
        delete G;
    }

    ParseTreeNode *Parse(const string &input)
    {
        TRY
        {
            Init();
            TestScanner scanner;
            scanner.SetInput(input);

            Token *token = NULL;
            while (!Accept())
            {
                token = scanner.ScanOneToken();
                ParseOneToken(token);
            }
            delete token;
        }
        CATCH2(UnhandledReductionException, e)
        {
            // This should only occur during debugging; print to cerr anyway
            cerr << e.Message() << endl;
            cerr << "Rule = " << *(e.GetRule()) << endl;
            cerr << e.GetPos().GetErrorText(input) << endl;
            CATCH_RETURN2(1, NULL);
        }
        CATCH2(ParseException, e)
        {
            cerr << e.Message() << endl;
            cerr << e.GetPos().GetErrorText(input) << endl;
            CATCH_RETURN2(1, NULL);
        }
        CATCHALL
        {
            cerr << "Unknown exception!\n";
            CATCH_RETURN2(1, NULL);
        }
        ENDTRY
        return GetParseTree();
    }

};

// ****************************************************************************
//  Function:  main
//
//  Programmer:  Jeremy Meredith
//  Creation:    November 24, 2004
//
//  Modifications:
//
// ****************************************************************************
int
main(int argc, char *argv[])
{
    if (argc<2) {cerr<<"needs an argument\n"; exit(-1);}

    Parser *parser = new TestParser();

    for (int i=1; i<argc; i++)
    {
        cout << "----- Parsing "<<argv[i]<<" -----\n";
        ParseTreeNode *node = parser->Parse(argv[i]);
        if (node)
        {
            cout << "----- PARSE TREE -----\n";
            node->Print(cout);
            delete node;
        }
        else
            cout << "ERROR\n";
    }

    delete parser;

    return 0;
}