Java Code Examples for org.antlr.stringtemplate.StringTemplateGroup

The following examples show how to use org.antlr.stringtemplate.StringTemplateGroup. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: pitest   Source File: MutationHtmlReportListener.java    License: Apache License 2.0 6 votes vote down vote up
private void createPackageIndexPage(final PackageSummaryData psData) {
  final StringTemplateGroup group = new StringTemplateGroup("mutation_test");
  final StringTemplate st = group
      .getInstanceOf("templates/mutation/package_index");

  final Writer writer = this.outputStrategy.createWriterForFile(psData
      .getPackageDirectory() + File.separator + "index.html");
  st.setAttribute("packageData", psData);
  try {
    writer.write(st.toString());
    writer.close();
  } catch (final IOException e) {
    e.printStackTrace();
  }

}
 
Example 2
public void compile() throws IOException{
	String junitFileName;
	if ( grammarInfo.getTreeGrammarName()!=null ) {
		junitFileName = "Test"+grammarInfo.getTreeGrammarName();
	}
	else {
		junitFileName = "Test"+grammarInfo.getGrammarName();
	}
	String lexerName = grammarInfo.getGrammarName()+"Lexer";
	String parserName = grammarInfo.getGrammarName()+"Parser";
	
	StringTemplateGroupLoader loader = new CommonGroupLoader("org/antlr/gunit", null);
	StringTemplateGroup.registerGroupLoader(loader);
	StringTemplateGroup.registerDefaultLexer(AngleBracketTemplateLexer.class);
	StringBuffer buf = compileToBuffer(junitFileName, lexerName, parserName);
	writeTestFile(".", junitFileName+".java", buf.toString());
}
 
Example 3
@Override
protected void compile(ProtoModule module, Proto proto) throws IOException
{
    String javaPackageName = proto.getJavaPackageName();
    StringTemplateGroup group = getSTG(getOutputId());

    String fileName = resolveFileName(proto);
    Writer writer = CompilerUtil.newWriter(module, javaPackageName,
            "Schema" + fileName + ".java");

    AutoIndentWriter out = new AutoIndentWriter(writer);
    StringTemplate protoOuterBlock = group.getInstanceOf("proto_block");

    protoOuterBlock.setAttribute("proto", proto);
    protoOuterBlock.setAttribute("module", module);
    protoOuterBlock.setAttribute("options", module.getOptions());

    protoOuterBlock.write(out);
    writer.close();
}
 
Example 4
public void testEscaped$InAction() throws Exception {
	String action = "int \\$n; \"\\$in string\\$\"";
	String expecting = "int $n; \"$in string$\"";
	Grammar g = new Grammar(
		"parser grammar t;\n"+
		"@members {"+action+"}\n"+
		"a[User u, int i]\n" +
		"        : {"+action+"}\n" +
		"        ;");
	Tool antlr = newTool();
	CodeGenerator generator = new CodeGenerator(antlr, g, "Java");
	g.setCodeGenerator(generator);
	generator.genRecognizer(); // forces load of templates
	ActionTranslator translator =
		new ActionTranslator(generator,
								  "a",
								  new antlr.CommonToken(ANTLRParser.ACTION,action),0);
	String rawTranslation =
		translator.translate();
	StringTemplateGroup templates =
		new StringTemplateGroup(".", AngleBracketTemplateLexer.class);
	StringTemplate actionST = new StringTemplate(templates, rawTranslation);
	String found = actionST.toString();
	assertEquals(expecting, found);
}
 
Example 5
Source Project: protostuff   Source File: ProtoToJavaBeanCompiler.java    License: Apache License 2.0 6 votes vote down vote up
protected void writeMessages(ProtoModule module, Proto proto, String javaPackageName, StringTemplateGroup group)
        throws IOException
{
    for (Message m : proto.getMessages())
    {
        Writer writer = CompilerUtil.newWriter(module,
                javaPackageName, m.getName() + ".java");
        AutoIndentWriter out = new AutoIndentWriter(writer);

        StringTemplate messageBlock = group.getInstanceOf("message_block");
        messageBlock.setAttribute("message", m);
        messageBlock.setAttribute("module", module);
        messageBlock.setAttribute("options", module.getOptions());

        messageBlock.write(out);
        writer.close();
    }
}
 
Example 6
public void testFullyQualifiedRefToCurrentRuleParameter() throws Exception {
	String action = "$a.i;";
	String expecting = "i;";

	ErrorQueue equeue = new ErrorQueue();
	ErrorManager.setErrorListener(equeue);
	Grammar g = new Grammar(
		"grammar t;\n"+
		"a[int i]: {"+action+"}\n" +
		"  ;\n");
	Tool antlr = newTool();
	CodeGenerator generator = new CodeGenerator(antlr, g, "Java");
	g.setCodeGenerator(generator);
	generator.genRecognizer(); // forces load of templates
	ActionTranslator translator = new ActionTranslator(generator,"a",
																 new antlr.CommonToken(ANTLRParser.ACTION,action),1);
	String rawTranslation =
		translator.translate();
	StringTemplateGroup templates =
		new StringTemplateGroup(".", AngleBracketTemplateLexer.class);
	StringTemplate actionST = new StringTemplate(templates, rawTranslation);
	String found = actionST.toString();
	assertEquals(expecting, found);

	assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size());
}
 
Example 7
public void testFullyQualifiedRefToCurrentRuleRetVal() throws Exception {
	String action = "$a.i;";
	String expecting = "retval.i;";

	ErrorQueue equeue = new ErrorQueue();
	ErrorManager.setErrorListener(equeue);
	Grammar g = new Grammar(
		"grammar t;\n"+
		"a returns [int i, int j]: {"+action+"}\n" +
		"  ;\n");
	Tool antlr = newTool();
	CodeGenerator generator = new CodeGenerator(antlr, g, "Java");
	g.setCodeGenerator(generator);
	generator.genRecognizer(); // forces load of templates
	ActionTranslator translator = new ActionTranslator(generator,"a",
																 new antlr.CommonToken(ANTLRParser.ACTION,action),1);
	String rawTranslation =
		translator.translate();
	StringTemplateGroup templates =
		new StringTemplateGroup(".", AngleBracketTemplateLexer.class);
	StringTemplate actionST = new StringTemplate(templates, rawTranslation);
	String found = actionST.toString();
	assertEquals(expecting, found);

	assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size());
}
 
Example 8
@Override
public void compile(ProtoModule module, Proto proto) throws IOException
{
    String javaPackageName = proto.getJavaPackageName();
    StringTemplateGroup group = getSTG("java_bean_primitives");

    // this compiler doesnt allow setters
    module.getOptions().setProperty("no_setters", "true");

    // TODO find a way to push this up to the parsing step
    if (module.getOption("ByteBuffer") != null)
    {
        for (Message m : proto.getMessages())
        {
            m.setByteBufferFieldPresent(true);

            setByteBuffer(m);
        }
    }

    writeEnums(module, proto, javaPackageName, group);
    writeMessages(module, proto, javaPackageName, group);
}
 
Example 9
Source Project: protostuff   Source File: ProtoToJavaBeanCompiler.java    License: Apache License 2.0 6 votes vote down vote up
protected void writeEnums(ProtoModule module, Proto proto, String javaPackageName, StringTemplateGroup group)
        throws IOException
{
    for (EnumGroup eg : proto.getEnumGroups())
    {
        Writer writer = CompilerUtil.newWriter(module,
                javaPackageName, eg.getName() + ".java");
        AutoIndentWriter out = new AutoIndentWriter(writer);

        StringTemplate enumBlock = group.getInstanceOf("enum_block");
        enumBlock.setAttribute("eg", eg);
        enumBlock.setAttribute("module", module);
        enumBlock.setAttribute("options", module.getOptions());

        enumBlock.write(out);
        writer.close();
    }
}
 
Example 10
Source Project: attic-aurora   Source File: StringTemplateHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new template helper.
 *
 * @param templateContextClass Classpath context for the location of the template file.
 * @param templateName Template file name (excluding .st suffix) relative to
 *     {@code templateContextClass}.
 * @param cacheTemplates Whether the template should be cached.
 */
public StringTemplateHelper(
    Class<?> templateContextClass,
    String templateName,
    boolean cacheTemplates) {

  MorePreconditions.checkNotBlank(templateName);
  String templatePath =
      templateContextClass.getPackage().getName().replace('.', '/') + "/" + templateName;
  StringTemplateGroup group = new StringTemplateGroup(templateName);
  Preconditions.checkNotNull(group.getInstanceOf(templatePath),
      "Failed to load template at: %s", templatePath);

  this.group = group;
  if (!cacheTemplates) {
    group.setRefreshInterval(0);
  }
  this.templatePath = templatePath;
}
 
Example 11
public void testTokenRefTreeProperty() throws Exception {
	String action = "$ID.tree;";
	String expecting = "ID1_tree;";

	ErrorQueue equeue = new ErrorQueue();
	ErrorManager.setErrorListener(equeue);
	Grammar g = new Grammar(
		"grammar t;\n"+
		"a : ID {"+action+"} ;" +
		"ID : 'a';\n");
	Tool antlr = newTool();
	antlr.setOutputDirectory(null); // write to /dev/null
	CodeGenerator generator = new CodeGenerator(antlr, g, "Java");
	g.setCodeGenerator(generator);
	generator.genRecognizer();

	ActionTranslator translator = new ActionTranslator(generator,"a",
																 new antlr.CommonToken(ANTLRParser.ACTION,action),1);
	String rawTranslation =
		translator.translate();
	StringTemplateGroup templates =
		new StringTemplateGroup(".", AngleBracketTemplateLexer.class);
	StringTemplate actionST = new StringTemplate(templates, rawTranslation);
	String found = actionST.toString();
	assertEquals(expecting, found);
}
 
Example 12
Source Project: swellrt   Source File: Pst.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Runs the code generation for all templates.
 */
public void run() throws PstException {
  List<PstException.TemplateException> exceptions = Lists.newArrayList();
  for (File template : templates) {
    try {
      MessageProperties properties = createProperties(template);
      String groupName = stripSuffix(".st", template.getName());
      String templateName = properties.hasTemplateName() ?
          properties.getTemplateName() : "";
      StringTemplateGroup group = new StringTemplateGroup(groupName + "Group", dir(template));
      StringTemplate st = group.getInstanceOf(groupName);
      for (Descriptor messageDescriptor : fd.getMessageTypes()) {
        Message message = new Message(messageDescriptor, templateName, properties);
        st.reset();
        st.setAttribute("m", message);
        write(st, new File(
            outputDir.getPath() + File.separator +
            message.getFullJavaType().replace('.', File.separatorChar) + "." +
            (properties.hasFileExtension() ? properties.getFileExtension() : "java")));
      }
    } catch (Exception e) {
      exceptions.add(new PstException.TemplateException(template.getPath(), e));
    }
  }
  if (!exceptions.isEmpty()) {
    throw new PstException(exceptions);
  }
}
 
Example 13
Source Project: swift-k   Source File: Karajan.java    License: Apache License 2.0 5 votes vote down vote up
public static void compile(Program prog, PrintStream out, boolean provenanceEnabled) throws CompilationException {
	StringTemplateGroup templates;
	try {
	    StringTemplateGroup main = new StringTemplateGroup(new InputStreamReader(
                   Karajan.class.getClassLoader().getResource(TEMPLATE_FILE_NAME).openStream()));
	    if (provenanceEnabled) {
	        templates = main;
	    }
	    else {
	        StringTemplateGroup override = new StringTemplateGroup(new InputStreamReader(
                   Karajan.class.getClassLoader().getResource(TEMPLATE_FILE_NAME_NO_PROVENANCE).openStream()));
	        override.setSuperGroup(main);
	        templates = override;
	    }
	} 
	catch(IOException ioe) {
		throw new CompilationException("Unable to load karajan source templates",ioe);
	}

	OutputContext oc = new OutputContext(templates);
	Karajan karajan = new Karajan();
	IProgram p = karajan.program(prog);
	try {
           p.writeTo(oc, out);
       }
       catch (IOException e) {
           throw new CompilationException("Failed to write output", e);
       }
}
 
Example 14
Source Project: protostuff   Source File: ProtoToJavaBeanCompiler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void compile(ProtoModule module, Proto proto) throws IOException
{
    String javaPackageName = proto.getJavaPackageName();
    String template = module.getOption("separate_schema") == null ?
            "java_bean" : "java_bean_separate_schema";
    StringTemplateGroup group = getSTG(template);

    writeEnums(module, proto, javaPackageName, group);

    writeMessages(module, proto, javaPackageName, group);
}
 
Example 15
public void testDoNotTranslateAttributeCompare() throws Exception {
	String action = "$a.line == $b.line";
	String expecting = "(a!=null?a.getLine():0) == (b!=null?b.getLine():0)";
	ErrorQueue equeue = new ErrorQueue();
	ErrorManager.setErrorListener(equeue);
	Grammar g = new Grammar(
			"lexer grammar a;\n" +
			"RULE:\n" +
			"     a=ID b=ID {" + action + "}" +
			"    ;\n" +
			"ID : 'id';"
	);
	Tool antlr = newTool();
	CodeGenerator generator = new CodeGenerator(antlr, g, "Java");
	g.setCodeGenerator(generator);
	generator.genRecognizer();
	ActionTranslator translator = new ActionTranslator(generator,
																 "RULE",
																 new antlr.CommonToken(ANTLRParser.ACTION,action),1);
	String rawTranslation =
		translator.translate();
	StringTemplateGroup templates =
		new StringTemplateGroup(".", AngleBracketTemplateLexer.class);
	StringTemplate actionST = new StringTemplate(templates, rawTranslation);
	String found = actionST.toString();
	assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size());
	assertEquals(expecting, found);
}
 
Example 16
Source Project: quetzal   Source File: ValuesSQLTemplate.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	 String st = "group sql;\n"
	 		+ "values(values, values_project,  store_name) ::= << \n"
			+ "( select <values_project:{ v |  struct_col.col<i> AS <v>} ; separator=\",\"> from (select storename from <store_name> limit 1) dummy lateral view explode(array(<values:{struct(<it; separator=\",\">)};separator=\",\">)) LATTEMP_<store_name> AS struct_col  ) AS TEMP"
		 	//+" (select VALUES <values:{(<it; separator=\",\">)};separator=\",\">) AS TEMP(<values_project; separator=\",\">) \n"
			+">>";
	 System.out.println("template text: "+st);
	 BufferedReader configReader = new BufferedReader(new StringReader(st));
        StringTemplateGroup group = new StringTemplateGroup(configReader);
	 StringTemplate template =  group.getInstanceOf("values");//new StringTemplate(st);
	 System.out.println("template: "+template.toString());
	 template.setAttribute("store_name", "uobm1a");
	 List<String> projects = new LinkedList<String>();
	 projects.add("column1");
	 projects.add("column2");
	 template.setAttribute("values_project",projects);
	 List< List<String>> values = new LinkedList<List<String>>();
	 List<String> value = new LinkedList<String>();
	 value.add("'test1'");
	 value.add("'test2'");
	 values.add(value);
	 value = new LinkedList<String>();
	 value.add("'test3'");
	 value.add("'test4'");
	 values.add(value);
	 
	 template.setAttribute("values", values);
	 System.out.println("string: "+template.toString());
}
 
Example 17
public StringBuffer compileToBuffer(String className, String lexerName,
		String parserName) {
	StringTemplateGroup group = StringTemplateGroup.loadGroup("junit");
	StringBuffer buf = new StringBuffer();
	buf.append(genClassHeader(group, className));
	buf.append(genTestRuleMethods(group));
	buf.append(genSupportingMethods(group, lexerName, parserName));
	buf.append(group.getInstanceOf("examineParserExecResult").toString());
	buf.append("\n\n}");
	return buf;
}
 
Example 18
protected String genClassHeader(StringTemplateGroup group, String junitFileName) {
	StringTemplate classHeaderST = group.getInstanceOf("classHeader");
	if ( grammarInfo.getHeader()!=null ) {	// Set up class package if there is
		classHeaderST.setAttribute("header", "package "+grammarInfo.getHeader()+";");
	}
	classHeaderST.setAttribute("junitFileName", junitFileName);
	return classHeaderST.toString();
}
 
Example 19
protected String genSupportingMethods(StringTemplateGroup group, String lexerName, String parserName) {
	StringTemplate supportingMethodST;
	String parserPath;
	String treeParserPath;
	/** Set up appropriate class path for parser/tree parser if using package */
	if ( grammarInfo.getHeader()!=null ) {
		parserPath = grammarInfo.getHeader()+"."+parserName;
		treeParserPath = grammarInfo.getHeader()+"."+grammarInfo.getTreeGrammarName();
	}
	else {
		parserPath = parserName;
		treeParserPath = grammarInfo.getTreeGrammarName();
	}
	/** Set up different parser executer for parser grammar and tree grammar */
	if ( grammarInfo.getTreeGrammarName()!=null ) {	// Load template for testing tree grammar
		supportingMethodST = group.getInstanceOf("execTreeParser");
		supportingMethodST.setAttribute("treeParserName", grammarInfo.getTreeGrammarName());
		supportingMethodST.setAttribute("treeParserPath", treeParserPath);
	}
	else {	// Load template for testing grammar
		supportingMethodST = group.getInstanceOf("execParser");
	}
	supportingMethodST.setAttribute("lexerName", lexerName);
	supportingMethodST.setAttribute("parserName", parserName);
	supportingMethodST.setAttribute("parserPath", parserPath);
	return supportingMethodST.toString();
}
 
Example 20
private StringTemplateGroup getTemplateGroup() {
	StringTemplateGroupLoader loader = new CommonGroupLoader("org/antlr/gunit", null);
	StringTemplateGroup.registerGroupLoader(loader);
	StringTemplateGroup.registerDefaultLexer(AngleBracketTemplateLexer.class);
	StringTemplateGroup group = StringTemplateGroup.loadGroup("gUnitTestResult");
	return group;
}
 
Example 21
Source Project: protostuff   Source File: ProtoToProtoCompiler.java    License: Apache License 2.0 5 votes vote down vote up
public static String extendBy(StringTemplateGroup group, Message extend, Message by) throws IOException
{
    StringWriter stringer = new StringWriter(16);
    NoIndentWriter out = new NoIndentWriter(stringer);

    StringTemplate messageBlock = group.getInstanceOf("extend_by");
    messageBlock.setAttribute("message", extend);
    messageBlock.setAttribute("by", by);
    messageBlock.write(out);

    return stringer.toString();
}
 
Example 22
public void testArguments() throws Exception {
	String action = "$i; $i.x; $u; $u.x";
	String expecting = "i; i.x; u; u.x";

	ErrorQueue equeue = new ErrorQueue();
	ErrorManager.setErrorListener(equeue);
	Grammar g = new Grammar(
		"parser grammar t;\n"+
		"a[User u, int i]\n" +
		"        : {"+action+"}\n" +
		"        ;");
	Tool antlr = newTool();
	CodeGenerator generator = new CodeGenerator(antlr, g, "Java");
	g.setCodeGenerator(generator);
	generator.genRecognizer(); // forces load of templates
	ActionTranslator translator = new ActionTranslator(generator,"a",
																 new antlr.CommonToken(ANTLRParser.ACTION,action),1);
	String rawTranslation =
		translator.translate();
	StringTemplateGroup templates =
		new StringTemplateGroup(".", AngleBracketTemplateLexer.class);
	StringTemplate actionST = new StringTemplate(templates, rawTranslation);
	String found = actionST.toString();
	assertEquals(expecting, found);

	assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size());
}
 
Example 23
public void testGenericsAsArgumentDefinition() throws Exception {
	String action = "$foo.get(\"ick\");";
	String expecting = "foo.get(\"ick\");";

	ErrorQueue equeue = new ErrorQueue();
	ErrorManager.setErrorListener(equeue);
	String grammar =
		"parser grammar T;\n"+
		"a[HashMap<String,String> foo]\n" +
		"        : {"+action+"}\n" +
		"        ;";
	Grammar g = new Grammar(grammar);
	Rule ra = g.getRule("a");
	List<Attribute> attrs = ra.parameterScope.getAttributes();
	assertEquals("attribute mismatch","HashMap<String,String> foo",attrs.get(0).decl.toString());
	assertEquals("parameter name mismatch","foo",attrs.get(0).name);
	assertEquals("declarator mismatch", "HashMap<String,String>", attrs.get(0).type);

	Tool antlr = newTool();
	CodeGenerator generator = new CodeGenerator(antlr, g, "Java");
	g.setCodeGenerator(generator);
	generator.genRecognizer(); // forces load of templates
	ActionTranslator translator = new ActionTranslator(generator,"a",
																 new antlr.CommonToken(ANTLRParser.ACTION,action),1);
	String rawTranslation =
		translator.translate();
	StringTemplateGroup templates =
		new StringTemplateGroup(".", AngleBracketTemplateLexer.class);
	StringTemplate actionST = new StringTemplate(templates, rawTranslation);
	String found = actionST.toString();
	assertEquals(expecting, found);

	assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size());
}
 
Example 24
Source Project: jFuzzyLogic   Source File: CPPTarget.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void genRecognizerHeaderFile(Tool tool,
									   CodeGenerator generator,
									   Grammar grammar,
									   StringTemplate headerFileST,
									   String extName)
	throws IOException
{
	StringTemplateGroup templates = generator.getTemplates();
	generator.write(headerFileST, grammar.name+extName);
}
 
Example 25
public void testComplicatedArgParsingWithTranslation() throws Exception {
	String action = "x, $A.text+\"3242\", (*$A).foo(21,33), 3.2+1, '\\n', "+
					"\"a,oo\\nick\", {bl, \"fdkj\"eck}";
	String expecting = "x, (A1!=null?A1.getText():null)+\"3242\", (*A1).foo(21,33), 3.2+1, '\\n', \"a,oo\\nick\", {bl, \"fdkj\"eck}";

	ErrorQueue equeue = new ErrorQueue();
	ErrorManager.setErrorListener(equeue);

	// now check in actual grammar.
	Grammar g = new Grammar(
		"parser grammar t;\n"+
		"a[User u, int i]\n" +
		"        : A a["+action+"] B\n" +
		"        ;");
	Tool antlr = newTool();
	CodeGenerator generator = new CodeGenerator(antlr, g, "Java");
	g.setCodeGenerator(generator);
	generator.genRecognizer(); // forces load of templates
	ActionTranslator translator = new ActionTranslator(generator,"a",
																 new antlr.CommonToken(ANTLRParser.ACTION,action),1);
	String rawTranslation =
		translator.translate();
	StringTemplateGroup templates =
		new StringTemplateGroup(".", AngleBracketTemplateLexer.class);
	StringTemplate actionST = new StringTemplate(templates, rawTranslation);
	String found = actionST.toString();
	assertEquals(expecting, found);

	assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size());
}
 
Example 26
/** $x.start refs are checked during translation not before so ANTLR misses
 the fact that rule r has refs to predefined attributes if the ref is after
 the def of the method or self-referential.  Actually would be ok if I didn't
 convert actions to strings; keep as templates.
 June 9, 2006: made action translation leave templates not strings
 */
public void testRefToReturnValueBeforeRefToPredefinedAttr() throws Exception {
	String action = "$x.foo";
	String expecting = "(x!=null?x.foo:0)";

	ErrorQueue equeue = new ErrorQueue();
	ErrorManager.setErrorListener(equeue);
	Grammar g = new Grammar(
		"parser grammar t;\n"+
		"a : x=b {"+action+"} ;\n" +
		"b returns [int foo] : B {$b.start} ;\n");
	Tool antlr = newTool();
	CodeGenerator generator = new CodeGenerator(antlr, g, "Java");
	g.setCodeGenerator(generator);
	generator.genRecognizer(); // forces load of templates
	ActionTranslator translator = new ActionTranslator(generator,"a",
																 new antlr.CommonToken(ANTLRParser.ACTION,action),1);
	String rawTranslation =
		translator.translate();
	StringTemplateGroup templates =
		new StringTemplateGroup(".", AngleBracketTemplateLexer.class);
	StringTemplate actionST = new StringTemplate(templates, rawTranslation);
	String found = actionST.toString();
	assertEquals(expecting, found);

	assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size());
}
 
Example 27
public void testRuleLabelBeforeRefToPredefinedAttr() throws Exception {
	// As of Mar 2007, I'm removing unused labels.  Unfortunately,
	// the action is not seen until code gen.  Can't see $x.text
	// before stripping unused labels.  We really need to translate
	// actions first so code gen logic can use info.
	String action = "$x.text";
	String expecting = "(x!=null?input.toString(x.start,x.stop):null)";

	ErrorQueue equeue = new ErrorQueue();
	ErrorManager.setErrorListener(equeue);
	Grammar g = new Grammar(
		"parser grammar t;\n"+
		"a : x=b {"+action+"} ;\n" +
		"b : B ;\n");
	Tool antlr = newTool();
	CodeGenerator generator = new CodeGenerator(antlr, g, "Java");
	g.setCodeGenerator(generator);
	generator.genRecognizer(); // forces load of templates
	ActionTranslator translator = new ActionTranslator(generator,"a",
																 new antlr.CommonToken(ANTLRParser.ACTION,action),1);
	String rawTranslation =
		translator.translate();
	StringTemplateGroup templates =
		new StringTemplateGroup(".", AngleBracketTemplateLexer.class);
	StringTemplate actionST = new StringTemplate(templates, rawTranslation);
	String found = actionST.toString();
	assertEquals(expecting, found);

	assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size());
}
 
Example 28
Source Project: gsn   Source File: TedsToVirtualSensor.java    License: GNU General Public License v3.0 5 votes vote down vote up
public TedsToVirtualSensor ( String templateDir , String templateFile ) {
   this.templateDir = templateDir;
   this.templatefile = templateFile;
   StringTemplateGroup grp = new StringTemplateGroup( "myGroup" , templateDir );
   vstmp = grp.getInstanceOf( templateFile );
   
}
 
Example 29
Source Project: protostuff   Source File: PluginProtoCompiler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public StringTemplateGroup resolveSTG(String stgLocation)
{
    try
    {
        File file = new File(stgLocation);
        if (file.exists())
            return new StringTemplateGroup(new BufferedReader(new FileReader(file)));

        URL url = DefaultProtoLoader.getResource(stgLocation,
                PluginProtoCompiler.class);
        if (url != null)
        {
            return new StringTemplateGroup(new BufferedReader(
                    new InputStreamReader(url.openStream(), "UTF-8")));
        }
        if (stgLocation.startsWith("http://"))
        {
            return new StringTemplateGroup(new BufferedReader(
                    new InputStreamReader(new URL(stgLocation).openStream(), "UTF-8")));
        }
    }
    catch (IOException e)
    {
        throw new RuntimeException(e);
    }
    throw new IllegalStateException("Could not find " + stgLocation);
}
 
Example 30
public void testSetAttrOfExpr() throws Exception {
	String action = "%{foo($ID.text).getST()}.y = z;";
	String expecting = "(foo((ID1!=null?ID1.getText():null)).getST()).setAttribute(\"y\", z);";

	ErrorQueue equeue = new ErrorQueue();
	ErrorManager.setErrorListener(equeue);
	Grammar g = new Grammar(
		"grammar t;\n" +
		"options {\n" +
		"    output=template;\n" +
		"}\n" +
		"\n" +
		"a : ID {"+action+"}\n" +
		"  ;\n" +
		"\n" +
		"ID : 'a';\n");
	Tool antlr = newTool();
	CodeGenerator generator = new CodeGenerator(antlr, g, "Java");
	g.setCodeGenerator(generator);
	generator.genRecognizer(); // forces load of templates
	ActionTranslator translator = new ActionTranslator(generator,
																 "a",
																 new antlr.CommonToken(ANTLRParser.ACTION,action),1);
	String rawTranslation =
		translator.translate();
	StringTemplateGroup templates =
		new StringTemplateGroup(".", AngleBracketTemplateLexer.class);
	StringTemplate actionST = new StringTemplate(templates, rawTranslation);
	String found = actionST.toString();

	assertNoErrors(equeue);

	assertEquals(expecting, found);
}