[antlr-interest] Type discovery for operator overloading?

C. Mundi cmundi at gmail.com
Fri Jun 13 19:40:36 PDT 2008


Hi.  Thanks again to tparr and all the great people who make antlr fun =and=
useful!

I'm getting a bit -- ok, a lot -- out of my depth here.  Literature
citations and examples are equally welcome.

I would like to create a DSL with a funny idea of 'multiplication' and the
field(s) on which it operates.

p = 3             // an "integer" assignment in my language
y = 'yeah! '   // a "string" assignment

q = 2 * p
print q          // gives 6

r = p * y
print "She loves me -- " + r   // gives "She loves me -- yeah! yeah! yeah!"

s = y * p
print s       // gives "yeah! yeah! yeah!"

There are two ideas in play here.  First, the multiplication operator has
been overloaded in my "string" class to understand

     ^( MULTIPLY INTEGER STRING )

as well as the familiar

     ^( MULTIPLY  INTEGER  INTEGER )

That does not seem too mysterious to me.

Now in my calculus, multiplication over pairs of one integer and one string
is commutative.  So my tree-walker has to recognize the equivalence of

     ^( MULTIPLY STRING INTEGER )

and

     ^( MULTIPLY INTEGER STRING )

But it seems to me that simply overloading the "left-multiply" method for
both strings and integers is wholly inadequate, because the multiplication
must take into account not only the type of the left-argument, but also the
type of the right-argument, to determine what to do and what type to
return.  This is evident from the fact that 2*3 and 2*'foo' return entirely
different types, but 2*'foo' and 'foo'*2 return the same type (and value in
this case).

How does one approach this?  It seems to me that the answer lies in the
translation output, not in ANTLR itself.  Nonetheless, I am hoping that
perhaps ANTLR provides some tools to support such situations.  I was
thinking LL(2) with a semantic predicate peeking ahead to determine the type
of the second operand.  Am I on the right track here?  Or should I go back
to monkey finishing school?

Three possibilities, none excluding another, occur to me:

1. There is an obvious way to do this, if only I had taken the right classes
at university.
2. There is a non-obvious way to factor this "dynamically typed" grammar
into simpler concepts, which has eluded me.
3. I'm going to groan when someone points out the answer in a FAQ or the
ANTLR book.

Thanks,
c. mundi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20080613/e56c4b7c/attachment.html 


More information about the antlr-interest mailing list