Java Code Examples for org.antlr.stringtemplate.StringTemplate#setAttribute()

The following examples show how to use org.antlr.stringtemplate.StringTemplate#setAttribute() . 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 File: TestAttributes.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testEscapedLessThanInAction() throws Exception {
	Grammar g = new Grammar();
	Tool antlr = newTool();
	CodeGenerator generator = new CodeGenerator(antlr, g, "Java");
	String action = "i<3; '<xmltag>'";
	ActionTranslator translator = new ActionTranslator(generator,"a",
																 new antlr.CommonToken(ANTLRParser.ACTION,action),0);
	String expecting = action;
	String rawTranslation =
		translator.translate();
	StringTemplateGroup templates =
		new StringTemplateGroup(".", AngleBracketTemplateLexer.class);
	StringTemplate actionST = new StringTemplate(templates, "<action>");
	actionST.setAttribute("action", rawTranslation);
	String found = actionST.toString();
	assertEquals(expecting, found);
}
 
Example 2
Source File: Expression.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String visit(Store store, FilterContext context,
		Expression exp) {
	String fType = null;

	Expression e = ((BuiltinFunctionExpression) exp).getArguments()
			.iterator().next();
	for (Variable v : e.gatherVariables()) {
		fType = context.getVarMap().get(v.getName()).snd;
	}
	if (fType == null)
		fType = TypeMap.IRI_ID + "";
	StringTemplate t = store.getInstanceOf("RDF_ISIRI");
	t.setAttribute("type", fType);
	t.setAttribute("iri_type", TypeMap.IRI_ID);
	return t.toString();
}
 
Example 3
Source File: GrammarDanglingStateMessage.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 6 votes vote down vote up
public String toString() {
	GrammarAST decisionASTNode = probe.dfa.getDecisionASTNode();
	line = decisionASTNode.getLine();
	column = decisionASTNode.getColumn();
	String fileName = probe.dfa.nfa.grammar.getFileName();
	if ( fileName!=null ) {
		file = fileName;
	}
	List labels = probe.getSampleNonDeterministicInputSequence(problemState);
	String input = probe.getInputSequenceDisplay(labels);
	StringTemplate st = getMessageTemplate();
	List alts = new ArrayList();
	alts.addAll(problemState.getAltSet());
	Collections.sort(alts);
	st.setAttribute("danglingAlts", alts);
	st.setAttribute("input", input);

	return super.toString(st);
}
 
Example 4
Source File: RelationalExpression.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
private String getSimpleLiteralMatch(FilterContext context,
		String lVarString, String rVarString, Store store) {
	StringTemplate t;
	t = store.getInstanceOf("STRING_SIMPLE_LIT_MATCH");
	t.setAttribute("simple_lit_type", TypeMap.SIMPLE_LITERAL_ID);
	t.setAttribute("string_type", TypeMap.STRING_ID);

	t.setAttribute("ltype",
			(context.getVarMap().get(lVarString).snd != null) ? context
					.getVarMap().get(lVarString).snd : TypeMap.IRI_ID);
	t.setAttribute("rtype",
			(context.getVarMap().get(rVarString).snd != null) ? context
					.getVarMap().get(rVarString).snd : TypeMap.IRI_ID);

	String simpleLitMatch = t.toString();
	return simpleLitMatch;
}
 
Example 5
Source File: BaseTest.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected void writeLexerTestFile(String lexerName, boolean debug) {
	StringTemplate outputFileST = new StringTemplate(
		"import org.antlr.runtime.*;\n" +
		"import org.antlr.runtime.tree.*;\n" +
		"import org.antlr.runtime.debug.*;\n" +
		"\n" +
		"class Profiler2 extends Profiler {\n" +
		"    public void terminate() { ; }\n" +
		"}\n"+
		"public class Test {\n" +
		"    public static void main(String[] args) throws Exception {\n" +
		"        CharStream input = new ANTLRFileStream(args[0]);\n" +
		"        $lexerName$ lex = new $lexerName$(input);\n" +
		"        CommonTokenStream tokens = new CommonTokenStream(lex);\n" +
		"        System.out.println(tokens);\n" +
		"    }\n" +
		"}"
		);
	outputFileST.setAttribute("lexerName", lexerName);
	writeFile(tmpdir, "Test.java", outputFileST.toString());
}
 
Example 6
Source File: RelationalExpression.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
private void setRelationalAttributes(ERelationalOp relationalOperator,
		String left, String right, StringTemplate t) {
	t.setAttribute("left", left);
	t.setAttribute("right", right);
	t.setAttribute("operator",
			RelationalExpression.getOperatorSymbol(relationalOperator));
}
 
Example 7
Source File: IAppProfile.java    From swift-k with Apache License 2.0 5 votes vote down vote up
@Override
protected void setTemplateAttributes(OutputContext oc, StringTemplate st) {
    super.setTemplateAttributes(oc, st);
    for (Pair<IExpression> e : entries) {
        StringTemplate entry = oc.template("map_entry");
        entry.setAttribute("key", e.get(0));
        entry.setAttribute("value", e.get(1));
        st.setAttribute("entries", entry);
    }
}
 
Example 8
Source File: IFieldConstant.java    From swift-k with Apache License 2.0 5 votes vote down vote up
@Override
protected void setTemplateAttributes(OutputContext oc, StringTemplate st) {
    super.setTemplateAttributes(oc, st);
    st.setAttribute("name", name);
    st.setAttribute("id", id);
    st.setAttribute("type", type);
}
 
Example 9
Source File: BuildDependencyGenerator.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 5 votes vote down vote up
public StringTemplate getDependencies() {
	loadDependencyTemplates();
	StringTemplate dependenciesST = templates.getInstanceOf("dependencies");
	dependenciesST.setAttribute("in", getDependenciesFileList());
	dependenciesST.setAttribute("out", getGeneratedFileList());
	dependenciesST.setAttribute("grammarFileName", grammar.fileName);
	return dependenciesST;
}
 
Example 10
Source File: NumericExpression.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String visit(FilterContext context, Store store) {
	String left = null;
	if (getLHS() instanceof ConstantExpression) {
		left = ((ConstantExpression) getLHS()).getSQLConstantExpressionAsType(
				context, store);
	} else {
		left = getLHS().visit(context, store);
	}
	String right = null;
	if (getRHS() instanceof ConstantExpression) {
		right = ((ConstantExpression) getRHS()).getSQLConstantExpressionAsType(
				context, store);
	} else {
		right = getRHS().visit(context, store);
	}
	if ((left.equals("")) || (right.equals("")))
		return "";

	String operator = getOperatorString();
	if (operator.equals(""))
		return "";

	StringTemplate t = store.getInstanceOf("numeric_expression");
	t.setAttribute("left", left);
	t.setAttribute("right", right);
	t.setAttribute("operator", operator);

	return t.toString();
}
 
Example 11
Source File: ICallExpression.java    From swift-k with Apache License 2.0 5 votes vote down vote up
@Override
protected void setTemplateAttributes(OutputContext oc, StringTemplate st) {
    super.setTemplateAttributes(oc, st);
    if (mapping) {
        st.setAttribute("mapping", true);
    }
    st.setAttribute("field", fieldName);
    st.setAttribute("call", call.getTemplate(oc));
    if (prefix != null) {
        st.setAttribute("prefix", prefix);
    }
}
 
Example 12
Source File: SPARQLToSQLExpression.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
private List<String> getNumericTypeCheckSQL(Expression expression,
		Map<String, Pair<String, String>> varMap) {
	List<String> types = new LinkedList<String>();
	for (Variable v : expression.gatherVariables()) {
		StringTemplate t = getInstanceOf(Expression.BETWEEN_TYPE_TEST);
		t.setAttribute("typeCol", varMap.get(v.getName()).snd);
		t.setAttribute("start", TypeMap.DATATYPE_NUMERICS_IDS_START);
		t.setAttribute("end", TypeMap.DATATYPE_NUMERICS_IDS_END);
		types.add(t.toString());
	}
	return types;
}
 
Example 13
Source File: PluginProtoCompiler.java    From protostuff with Apache License 2.0 5 votes vote down vote up
public static void compileServiceBlockTo(Writer writer,
        ProtoModule module, Service service,
        StringTemplate serviceBlockTemplate) throws IOException
{
    AutoIndentWriter out = new AutoIndentWriter(writer);

    StringTemplate messageBlock = serviceBlockTemplate.getInstanceOf();
    messageBlock.setAttribute("service", service);
    messageBlock.setAttribute("module", module);
    messageBlock.setAttribute("options", module.getOptions());

    messageBlock.write(out);
}
 
Example 14
Source File: Pst.java    From swellrt with 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 15
Source File: AggregateExpression.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public String visit(FilterContext context, Store store) {
	Set<Variable> vars = null;
	if (getArgs() != null) {
		vars = gatherVariables();
	}

	StringBuffer sql = new StringBuffer();
	StringTemplate t = null;

	if (AggregateExpression.EType.COUNT == getAggregationType()) {
		if (vars != null) {
			Iterator<Variable> varIterator = vars.iterator();
			boolean isFirstVar = true;
			while (varIterator.hasNext()) {
				if (!isFirstVar) {
					sql.append("||");
				} else {
					isFirstVar = false;
				}
				sql.append(varIterator.next().getName());
			}
		} else {
			sql.append("*");
		}

		if (isDistinct()) {
			t = store.getInstanceOf(AGGREGATE_DISTINCT_COUNT);
		} else {
			t = store.getInstanceOf(AGGREGATE_COUNT);
		}
		t.setAttribute("var", sql.toString());

		return t.toString();
	} else if (getAggregationType() == EType.GROUP_CONCAT) {
		t = store.getInstanceOf(GROUP_CONCAT);
		t.setAttribute("var", vars.iterator().next().getName());
		t.setAttribute("s", getSeparator().substring(1, 2));
		
		return t.toString();
	} else {
		if (context.doesConstantNeedTypeCheck(this)) {
			t = store.getInstanceOf(AGGREGATE_FUNCTION_WITH_TYP_CHECK);
			t.setAttribute("typecheck",
					getNumericTypeCheckSQL(context, store));

		} else {
			t = store.getInstanceOf(AGGREGATE_FUNCTION);
		}

		EType func = getAggregationType();
		if (AggregateExpression.EType.SAMPLE == getAggregationType()) {
			func = EType.MIN; // Kavitha: If this is a sample type, we need
								// to basically return 1 item from the set
		}
		t.setAttribute("function", func.toString().toLowerCase()); // XPath/XQuery
																	// functions
																	// are
																	// all
																	// lower
																	// case!
		if (getArgs() instanceof VariableExpression) {
			t.setAttribute("var", vars.iterator().next().getName());
		} else {
			t.setAttribute("var", getArgs().visit(context, store));
		}

		return t.toString();
	}
}
 
Example 16
Source File: ActionTranslator.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 4 votes vote down vote up
public final void mENCLOSING_RULE_SCOPE_ATTR() throws RecognitionException {
    try {
        int _type = ENCLOSING_RULE_SCOPE_ATTR;
        Token x=null;
        Token y=null;

        // ActionTranslator.g:222:2: ( '$' x= ID '.' y= ID {...}?)
        // ActionTranslator.g:222:4: '$' x= ID '.' y= ID {...}?
        {
        match('$'); if (state.failed) return ;
        int xStart97 = getCharIndex();
        mID(); if (state.failed) return ;
        x = new CommonToken(input, Token.INVALID_TOKEN_TYPE, Token.DEFAULT_CHANNEL, xStart97, getCharIndex()-1);
        match('.'); if (state.failed) return ;
        int yStart103 = getCharIndex();
        mID(); if (state.failed) return ;
        y = new CommonToken(input, Token.INVALID_TOKEN_TYPE, Token.DEFAULT_CHANNEL, yStart103, getCharIndex()-1);
        if ( !(enclosingRule!=null &&
        	                         (x!=null?x.getText():null).equals(enclosingRule.name) &&
        	                         enclosingRule.getLocalAttributeScope((y!=null?y.getText():null))!=null) ) {
            if (state.backtracking>0) {state.failed=true; return ;}
            throw new FailedPredicateException(input, "ENCLOSING_RULE_SCOPE_ATTR", "enclosingRule!=null &&\n\t                         $x.text.equals(enclosingRule.name) &&\n\t                         enclosingRule.getLocalAttributeScope($y.text)!=null");
        }
        if ( state.backtracking==1 ) {

          		if ( isRuleRefInAlt((x!=null?x.getText():null))  ) {
          			ErrorManager.grammarError(ErrorManager.MSG_RULE_REF_AMBIG_WITH_RULE_IN_ALT,
          									  grammar,
          									  actionToken,
          									  (x!=null?x.getText():null));
          		}
          		StringTemplate st = null;
          		AttributeScope scope = enclosingRule.getLocalAttributeScope((y!=null?y.getText():null));
          		if ( scope.isPredefinedRuleScope ) {
          			st = template("rulePropertyRef_"+(y!=null?y.getText():null));
          			grammar.referenceRuleLabelPredefinedAttribute((x!=null?x.getText():null));
          			st.setAttribute("scope", (x!=null?x.getText():null));
          			st.setAttribute("attr", (y!=null?y.getText():null));
          		}
          	    else if ( scope.isPredefinedLexerRuleScope ) {
          	    	// perhaps not the most precise error message to use, but...
          			ErrorManager.grammarError(ErrorManager.MSG_RULE_HAS_NO_ARGS,
          									  grammar,
          									  actionToken,
          									  (x!=null?x.getText():null));
          	    }
          		else if ( scope.isParameterScope ) {
          			st = template("parameterAttributeRef");
          			st.setAttribute("attr", scope.getAttribute((y!=null?y.getText():null)));
          		}
          		else { // must be return value
          			st = template("returnAttributeRef");
          			st.setAttribute("ruleDescriptor", enclosingRule);
          			st.setAttribute("attr", scope.getAttribute((y!=null?y.getText():null)));
          		}
          		
        }


        }

        state.type = _type;
    }
    finally {
    }
}
 
Example 17
Source File: IUnaryOperator.java    From swift-k with Apache License 2.0 4 votes vote down vote up
@Override
protected void setTemplateAttributes(OutputContext oc, StringTemplate st) {
    super.setTemplateAttributes(oc, st);
    st.setAttribute("exp", operand.getTemplate(oc));
}
 
Example 18
Source File: ISliceArray.java    From swift-k with Apache License 2.0 4 votes vote down vote up
@Override
protected void setTemplateAttributes(OutputContext oc, StringTemplate st) {
    super.setTemplateAttributes(oc, st);
    st.setAttribute("type", getType().toString());
}
 
Example 19
Source File: ActionTranslator.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 4 votes vote down vote up
public final void mISOLATED_LEXER_RULE_REF() throws RecognitionException {
    try {
        int _type = ISOLATED_LEXER_RULE_REF;
        Token ID3=null;

        // ActionTranslator.g:447:2: ( '$' ID {...}?)
        // ActionTranslator.g:447:4: '$' ID {...}?
        {
        match('$'); if (state.failed) return ;
        int ID3Start366 = getCharIndex();
        mID(); if (state.failed) return ;
        ID3 = new CommonToken(input, Token.INVALID_TOKEN_TYPE, Token.DEFAULT_CHANNEL, ID3Start366, getCharIndex()-1);
        if ( !(grammar.type==Grammar.LEXER &&
        	             enclosingRule!=null &&
        	             isRuleRefInAlt((ID3!=null?ID3.getText():null))) ) {
            if (state.backtracking>0) {state.failed=true; return ;}
            throw new FailedPredicateException(input, "ISOLATED_LEXER_RULE_REF", "grammar.type==Grammar.LEXER &&\n\t             enclosingRule!=null &&\n\t             isRuleRefInAlt($ID.text)");
        }
        if ( state.backtracking==1 ) {

          		String label = enclosingRule.getElementLabel((ID3!=null?ID3.getText():null), outerAltNum, generator);
          		checkElementRefUniqueness((ID3!=null?ID3.getText():null), false);
          		if ( label==null ) {
          			ErrorManager.grammarError(ErrorManager.MSG_FORWARD_ELEMENT_REF,
          									  grammar,
          									  actionToken,
          									  (ID3!=null?ID3.getText():null));
          		}
          		else {
          			StringTemplate st = template("lexerRuleLabel");
          			st.setAttribute("label", label);
          		}
          		
        }


        }

        state.type = _type;
    }
    finally {
    }
}
 
Example 20
Source File: ActionTranslator.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 4 votes vote down vote up
public final void mDYNAMIC_NEGATIVE_INDEXED_SCOPE_ATTR() throws RecognitionException {
    try {
        int _type = DYNAMIC_NEGATIVE_INDEXED_SCOPE_ATTR;
        Token x=null;
        Token expr=null;
        Token y=null;

        // ActionTranslator.g:612:2: ( '$' x= ID '[' '-' expr= SCOPE_INDEX_EXPR ']' '::' y= ID )
        // ActionTranslator.g:612:4: '$' x= ID '[' '-' expr= SCOPE_INDEX_EXPR ']' '::' y= ID
        {
        match('$'); if (state.failed) return ;
        int xStart566 = getCharIndex();
        mID(); if (state.failed) return ;
        x = new CommonToken(input, Token.INVALID_TOKEN_TYPE, Token.DEFAULT_CHANNEL, xStart566, getCharIndex()-1);
        match('['); if (state.failed) return ;
        match('-'); if (state.failed) return ;
        int exprStart574 = getCharIndex();
        mSCOPE_INDEX_EXPR(); if (state.failed) return ;
        expr = new CommonToken(input, Token.INVALID_TOKEN_TYPE, Token.DEFAULT_CHANNEL, exprStart574, getCharIndex()-1);
        match(']'); if (state.failed) return ;
        match("::"); if (state.failed) return ;

        int yStart582 = getCharIndex();
        mID(); if (state.failed) return ;
        y = new CommonToken(input, Token.INVALID_TOKEN_TYPE, Token.DEFAULT_CHANNEL, yStart582, getCharIndex()-1);
        if ( state.backtracking==1 ) {

          		StringTemplate st = template("scopeAttributeRef");
          		st.setAttribute("scope",    (x!=null?x.getText():null));
          		st.setAttribute("attr",     resolveDynamicScope((x!=null?x.getText():null)).getAttribute((y!=null?y.getText():null)));
          		st.setAttribute("negIndex", (expr!=null?expr.getText():null));
          		
        }


        }

        state.type = _type;
    }
    finally {
    }
}