[stringtemplate-interest] Conditionals

Udo Borkowski ub at abego-software.de
Fri Sep 2 04:24:00 PDT 2011


Hi Jiwon,

> So far, I could somehow use the map (such as, EqMap ::= ["int": "==" ,
> default: ".equals"] ) but this is something that cannot be done using
> the map. 

Actually maps provide a way to do exactly what you are looking for.

For every value you want to check ("int", "String") just create a map like this:

	someName ::= ["TheValue":true]

Then you can check if a variable holds this value using 

	<if (someName.(variable))> … <endif>

(Make sure to put (…) around the variable)


E.g. in your case you would define

	isInt ::= ["int":true]
and
	isString ::= ["String":true]


Your example would then look like this:

Foo(type, a, b) ::= <<
class Foo {
    <type> foo;

<if (isInt.(type))>
    foo = <a>+<b>; // int operation
<elseif (isString.(type))>
    foo = "<a>"+ " " +"<b>"; // string operation
<endif>
}
>>

When called by a template like this:

main() ::= <<
<Foo("int","x","2")>

<Foo("String","foo","bar")>
>>

the output is:

class Foo {
    int foo;

    foo = x+2; // int operation
}

class Foo {
    String foo;

    foo = "foo"+ " " +"bar"; // string operation
}


Udo


On 02.09.2011, at 00:35, Jiwon Seo wrote:

> Hi,
> 
> I'm using stringtemplate for code generation.
> One thing I need to do is to generate different code based on the type
> of a variable, like following:
> 
> Foo(type, a, b) ::= <<
> class Foo {
>    <type> foo;
> 
>    <if (type=="int")>
>       do some int thing
>    <elseif (type=="String">
>      do some string thing
>    <endif>
> }
>>> 
> 
> So far, I could somehow use the map (such as, EqMap ::= ["int": "==" ,
> default: ".equals"] ) but this is something that cannot be done using
> the map. So I ended up using a lot of variables like following:
> 
> Foo(type, intType, stringType, ... a, b) ::= <<
> class Foo {
>    <type> foo;
> 
>    <if (intType)>
>       do some int thing
>    <elseif (stringType)>
>      do some string thing
>    <endif>
> }
>>> 
> 
> Is there any other ways of doing this?
> 
> -Jiwon
> _______________________________________________
> stringtemplate-interest mailing list
> stringtemplate-interest at antlr.org
> http://www.antlr.org/mailman/listinfo/stringtemplate-interest

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/stringtemplate-interest/attachments/20110902/922b79b5/attachment.html 


More information about the stringtemplate-interest mailing list