[antlr-interest] First grammar a simple string template language

Daniel Lidström daniel.lidstrom at gpsgate.com
Thu Sep 23 06:50:27 PDT 2010


Hello,

I am trying out Antlr for the very first time. My task is to define a string 
template language, similar to
StringTemplate but with some formatting requirements. So I thought Antlr 
would be suitable for this
task. I have managed to define the first part, well almost. I'd like to get 
some feedback on my approach
as I feel I might be heading down the wrong path. Given a format string 
"[yyyy]-[M]-[d] [H]:[m]"
the desired result is "2010-9-23 15:28". Right now I am getting 
"20109231528".

How do I "capture" the dash and colon? Here's my grammar:

grammar TemplateCommand;

options {
    language=CSharp2;
}

tokens {
    TIMEFILTER = 'TimeFilter';
    YEAR       = 'yyyy';
    MONTH      = 'M';
    DAY        = 'd';
    HOUR       = 'H';
    MINUTE     = 'm';
}

@header {
using System.Text;
using System.Collections.Generic;
}

@members {
// Build template command using a StringBuilder
private StringBuilder builder = new StringBuilder();

// Used to resolve variables
private readonly IDictionary<string, string> resolver;

public TemplateCommandParser(ITokenStream input, IDictionary<string, string> 
resolver)
    : this(input)
{
    this.resolver = resolver;
}

public string Result
{ get { return builder.ToString(); } }
}

// parser rules:

prog returns [string result]
	: expression=templateExpression
	  { result = $expression.text; }
	;

templateExpression
	: var=(WS | Text | Number | variable)+
	  { builder.Append($var.text); }
	;

variable
	: '[' var=(TIMEFILTER | YEAR | MONTH | DAY | HOUR | MINUTE) ']'
	  { builder.Append(resolver[$var.text]); }
	;

// lexer rules:

Text : ('a'..'z' | 'A'..'Z' | ':' | ';' | '-')+ ;

Number : '1'..'9' ('0'..'9')* ;

WS : ' '+ 	;

I pass a dictionary to the parser during construction. This dictionary 
contains the variable
substitutions. Why isn't the templateExpression action able to capture the 
dash and colon?
Is there an approach better suited to my task than using actions in this 
way?

Thanks in advance!

(I have read up on StringTemplate and it doesn't quite fit with our 
requirements.)

Daniel 



More information about the antlr-interest mailing list