[antlr-interest] Re: How to parse java source code ?
paul taney
paultaney at yahoo.com
Mon Jul 14 16:53:20 PDT 2003
> > > I am looking for a parser which can parse an
> > input java source
> > code.I
> > > mean the parser
> > > should read
> > > the source code and identify the variable names
> > and types.
Matt,
I would humbly suggest that if that's all you want to
do and this is not a toy to help you learn antlr
then you are using a sledge to hammer the
proverbial mosquito... You not need to "parse",
as that's complex, you may only need to "grep"...
Right tool for the job may be python, perl or
% egrep "int|String|bool|etc" file | cut -f2
or something like that. Describe the general
problem.
paul
---- python example follows. Only does 3 types...
#!/usr/bin/python
# grep the vars out of some.java like this:
# python grepVars.py <some.java
import re, sys
debug = 0
pat0 = re.compile("(String) (\w*)")
pat1 = re.compile("(Boolean) (\w*)")
pat2 = re.compile("(int) (\w*)")
pat3 = re.compile("(float) (\w*)")
# etc.
for line in sys.stdin.xreadlines():
line = line[:-1] # chomp
mo0 = re.search(pat0, line)
mo1 = re.search(pat1, line)
mo2 = re.search(pat2, line)
mo3 = re.search(pat3, line)
# etc.
if mo0:
if debug: print "// pat0. groups=%s" %
repr(mo0.groups())
print "I see %s %s: %s" % (duh(mo0.group(1)),
mo0.group(1), mo0.group(2))
elif mo1:
if debug: print "// pat1. groups=%s" %
repr(mo1.groups())
print "I see %s %s: %s" % (duh(mo1.group(1)),
mo1.group(1), mo1.group(2))
elif mo2:
if debug: print "// pat2. groups=%s" %
repr(mo2.groups())
print "I see %s %s: %s" % (duh(mo2.group(1)),
mo2.group(1), mo2.group(2))
elif mo3:
if debug: print "// pat3. groups=%s" %
repr(mo3.groups())
print "I see %s %s: %s" % (duh(mo3.group(1)),
mo3.group(1), mo3.group(2))
else:
pass
#print line
def duh(st):
if st[0] in "aeiou":
return "an"
else:
return "a"
# EOF
$ python grepVars.py <matts.java
I see a String: args
I see a String: message
I see an int: count
----
Input file: grepVars.java, something like:
> > > Eg: Input is :
> > > import java.util.*;
> > >
> > > public class HelloWorld{
> > >
> > > public static void main(String args[]) {
> > >
> > > String message = "Hello World";
> > > int count =0;
> > >
> > > while(count <10) {
> > > System.out.println(message);
> > > count++;
> > > }
> > >
> > > }
> > >
> > > Output should be :
> > >
> > > Variables: type name
> > > int count
> > > String message
> > >
> > > Can ANTLR do this and if so how ??
> > >
> > > PLEASE HELP ME!!
> > >
> > > thanks in advance,
> > > suma
__________________________________
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
http://sbc.yahoo.com
Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
More information about the antlr-interest
mailing list