[stringtemplate-interest] sequences and unique numbers
Terence Parr
parrt at cs.usfca.edu
Mon Aug 3 12:19:03 PDT 2009
ST is lacking something I need. For the ANTLR->LLVM example, I need to
generate unique labels for the assembly code like LLVM IR. Right now,
I pass in a unique number. Since it's really part of the view, I think
it's bad to have the model track a unique number and pass it in. On
the other hand, sequences are difficult to use without side effects.
Every time you referenced a sequence name, it would increment it. I'm
uncomfortable with that side effect. still, we need to be able to deal
with unique label generation.
So, instead of sequence, how about we introduce the notion of unique
value but with unspecified order or values or whatever. In fact, it
wouldn't necessarily need to be a number. We could have unique label
generation directly.
Let's assume for the moment that every reference to <uniq> gives you a
unique label. How can we define and reference it? For example, here
is how we would generate labels and assembly code for an IF statement:
<cond>
brf end<uniq>
<block>
end<uniq>:
The problem is that we get something like end1 and end2 instead of the
same label. The solution is to compute a value and hold it for the
duration of the template, which we can do as a default argument:
if(cond, block, label={end<(uniq)>}) ::= <<
<cond>
brf <label>
<block>
<label>:
>>
Remember that (uniq) forces the immediate evaluation and conversion
to string of the enclosing element. Otherwise, it would use lazy
evaluation and evaluate uniq twice. So, the solution works.
Now, what is uniq? It turns out we don't need a special syntax or
mechanism. ST can handle already if we pass in an object with side
effects:
public class Counter {
int n = 1;
public String toString() { return String.valueOf(n++); }
}
Remember, ST assumes no side effects, but it can't stop the programmer
from passing in something with a side effect. ST would assume only
that the counter returns a value. It's up to us to decide what that
value is. This seems like a hack, but we could return the time value
back. That is not a side effect-- it just happens to get a different
value every time we call. You could also look at string tables the
same way. pass in a different string map and it gives you strings in a
different language. ST is assuming only that he gets a value. it's up
to the model to get the right value.
I'm running this up the flagpole to see what people think. Is this
good, bad, or indifferent?
Ter
More information about the stringtemplate-interest
mailing list