source: trunk/yao/share/antlr-2.7.7/examples/java/pascal/symtab.g @ 1

Last change on this file since 1 was 1, checked in by lnalod, 15 years ago

Initial import of YAO sources

File size: 7.8 KB
Line 
1//
2// Pascal Tree Grammar that walks tree, building symtab
3//
4// Adapted from,
5// Pascal User Manual And Report (Second Edition-1978)
6// Kathleen Jensen - Niklaus Wirth
7//
8// By
9//
10// Hakki Dogusan dogusanh@tr-net.net.tr
11//
12// Then significantly enhanced by Piet Schoutteten
13// with some guidance by Terence Parr.  Piet added tree
14// construction, and some tree walkers.
15//
16
17{
18import java.util.*;
19import java.io.*;
20}
21
22class SymtabPhase extends PascalTreeParserSuper;
23
24options {
25        importVocab = Pascal;
26        ASTLabelType = "PascalAST";
27}
28
29{
30Stack scopes = new Stack();
31Stack usesScopes = new Stack();
32//public static File thisUnit;
33public File thisUnit;
34}
35
36program
37    : programHeading
38      block
39      {System.out.println(scopes.peek());}
40    ;
41
42programHeading
43    : #(PROGRAM IDENT identifierList)
44      {Scope root = new Scope(null);
45       scopes.push(root);}
46    | #(UNIT IDENT)
47      {
48      Scope root = new Scope(null); // create new scope
49      scopes.push(root);            // enter new scope :)
50      root.addSymbol(new Unit(#IDENT.getText())); // create unit symbol entry
51
52      String tUnit = new String (#IDENT.getText());
53      tUnit = tUnit.concat(".sym");
54      thisUnit = new File (PascalParser.translateFilePath, tUnit);
55      }
56    ;
57
58block
59    : ( labelDeclarationPart
60      | constantDefinitionPart
61      | typeDefinitionPart
62      | variableDeclarationPart
63      | procedureAndFunctionDeclarationPart
64      | usesUnitsPart
65      | IMPLEMENTATION
66        { System.out.println(scopes.peek());
67            //write symbol table and exit when currentFileName != translateFileName
68            if  (PascalParser.currentFileName.compareTo(PascalParser.translateFileName) != 0) {
69                try{
70                    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(thisUnit));
71                    oos.writeObject(scopes);
72                    oos.close();
73                }
74                catch (IOException e) {
75                    System.err.println("IOexception: "+e); }
76                _t = null;
77                throw new RecognitionException();
78            }
79        }
80      )*
81      compoundStatement
82    ;
83
84usesUnitsPart
85{
86String usesFile, usesSymtab;
87String oldUsesFile;
88File f, symFile;
89Object readSymtab = new Stack();
90}
91    : #(USES usesList:identifierList)
92    // walk identifierList and make symbol table
93    {
94        usesList = (PascalAST) usesList.getFirstChild();
95        oldUsesFile = PascalParser.currentFileName;
96        while (usesList !=null) {
97            // make symboltable for usesFile
98            usesFile = usesList.getText();
99            usesFile = usesFile.concat(".pas");
100            usesSymtab = usesList.getText();
101            usesSymtab = usesSymtab.concat(".sym");
102
103            f = new File(PascalParser.translateFilePath,usesFile);
104            symFile = new File(PascalParser.translateFilePath,usesSymtab);
105
106                        // we have to build the symbol table when ...
107                        if (( !(symFile.exists() ) )
108                        // this .sym file (usesSymtyb) does not exist or ...
109                           || ((f.lastModified()) > (symFile.lastModified()) ) ){
110                        // the date of this .sym file (usesSymtyb) is older than the .pas file (usesFile)
111
112                try {
113                PascalParser.parseFile(f.getName(),new FileInputStream(f));
114                }
115                catch (Exception e) {
116                    System.err.println("parser exception: "+e);
117                    e.printStackTrace();   // so we can get stack trace
118                }
119            }
120
121            // read serialized symbol table and add to symbol table "usesScopes"
122            File symTab = new File (PascalParser.translateFilePath , usesSymtab);
123            try {
124                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(symTab));
125                readSymtab = ois.readObject();
126                ois.close();
127            }
128            catch (ClassNotFoundException cnfe) {
129                System.err.println("parser exception: "+cnfe);
130                cnfe.printStackTrace();   // so we can get stack trace
131            }
132            catch (FileNotFoundException e) {
133                System.err.println("parser exception: "+e);
134                e.printStackTrace();   // so we can get stack trace
135                        }
136            catch (IOException e) {
137                System.err.println("parser exception: "+e);
138                e.printStackTrace();   // so we can get stack trace
139            }
140
141            Stack symTabToPop = (Stack) readSymtab;
142
143            // add uses symbol table "readSymtab" to symboltable "usesScopes"
144            while (!(symTabToPop.empty())) {
145                usesScopes.push(symTabToPop.pop());
146            }
147
148            usesList = (PascalAST) usesList.getNextSibling();
149        }
150        PascalParser.currentFileName = oldUsesFile;
151    }
152    ;
153
154constantDefinition
155{
156Constant c = null;
157}
158    : #(r:EQUAL IDENT c=constant)
159      {
160      if ( c!=null ) {
161        Scope sc = (Scope)scopes.peek();
162        c.setName(#IDENT.getText());
163        sc.addSymbol(c);
164        r.symbol = c; // AST def root points to symbol table entry now
165      }
166      }
167    ;
168
169constant returns [Constant c=null]
170    : NUM_INT
171      {c = new IntegerConstant(#NUM_INT.getText());}
172    | NUM_REAL
173      {c = new RealConstant(#NUM_REAL.getText());}
174    | #( PLUS
175         ( NUM_INT
176           {c = new IntegerConstant(#NUM_INT.getText());}
177         | NUM_REAL
178           {c = new RealConstant(#NUM_REAL.getText());}
179         | IDENT
180         )
181       )
182    | #( MINUS
183         ( NUM_INT
184           {c = new IntegerConstant(#NUM_INT.getText());}
185         | NUM_REAL
186           {c = new RealConstant(#NUM_REAL.getText());}
187         | IDENT
188         )
189       )
190    | IDENT
191    | STRING_LITERAL
192    | #(CHR (NUM_INT|NUM_REAL))
193    ;
194
195typeDefinition
196{
197TypeSpecifier t=null;
198}
199    : #(TYPEDECL IDENT
200      ( type
201      | #(r:FUNCTION (formalParameterList)? t=resultType)
202      {
203      if ( t!=null ) {r.symbol = t;}
204      }
205
206      | #(PROCEDURE (formalParameterList)?)
207      )
208      )
209    ;
210
211type returns [TypeSpecifier ts=null]
212    : #(SCALARTYPE identifierList)
213    | #(DOTDOT constant constant)
214    | ts=typeIdentifier
215    | structuredType
216    | #(POINTER typeIdentifier)
217    ;
218
219typeIdentifier returns [TypeSpecifier ts=null]
220    : IDENT // lookup and return type spec
221    | CHAR
222    | BOOLEAN
223    | INTEGER {ts=PascalParser.symbolTable.getPredefinedType("integer");}
224    | REAL {ts=PascalParser.symbolTable.getPredefinedType("real");}
225    | #( STRING
226         ( IDENT
227         | NUM_INT
228         | NUM_REAL
229         |
230         )
231       )
232    ;
233
234variableDeclaration
235{
236Vector ids=null;
237TypeSpecifier t=null;
238}
239    : #(r:VARDECL ids=identifierList t=type)
240      {
241      // walk list of identifiers, creating variable syms and setting types
242      if ( t!=null ) {
243        Scope sc = (Scope)scopes.peek();
244        for (int i=0; ids!=null && i<ids.size(); i++) {
245          String id = (String)ids.elementAt(i);
246          Variable v = new Variable(id,t);
247          sc.addSymbol(v);
248          r.symbol = t; // AST def root points to symbol table entry now
249       }
250      }
251      }
252    ;
253
254parameterGroup
255{
256Vector ids=null;
257TypeSpecifier t=null;
258}
259    : #(r:ARGDECL ids=identifierList t=typeIdentifier)
260      {
261      // walk list of identifiers, creating variable syms and setting types
262      if ( t!=null ) {
263        Scope sc = (Scope)scopes.peek();
264        for (int i=0; ids!=null && i<ids.size(); i++) {
265          String id = (String)ids.elementAt(i);
266          Variable v = new Variable(id,t);
267          sc.addSymbol(v);
268          r.symbol = t; // AST def root points to symbol table entry now
269       }
270      }
271      }
272
273    ;
274
275identifierList returns [Vector ids=new Vector()]
276    : #( IDLIST ( IDENT {ids.addElement(#IDENT.getText());} )+ )
277    ;
278
279functionDeclaration
280{
281TypeSpecifier t=null;
282}
283    : #(r:FUNCTION IDENT (formalParameterList)? t=resultType block)
284      {
285      if ( t!=null ) {r.symbol = t;}
286      }
287    ;
288
289resultType returns [TypeSpecifier ts=null]
290    : ts=typeIdentifier
291    ;
Note: See TracBrowser for help on using the repository browser.