Search in sources :

Example 61 with ST

use of edu.princeton.cs.algs4.ST in project compiler by boalang.

the class CodeGeneratingVisitor method visit.

//
// expressions
//
/** {@inheritDoc} */
@Override
public void visit(final Expression n) {
    final ST st = stg.getInstanceOf("Expression");
    n.getLhs().accept(this);
    st.add("lhs", code.removeLast());
    if (n.getRhsSize() > 0) {
        final List<String> operators = new ArrayList<String>();
        final List<String> operands = new ArrayList<String>();
        for (final Conjunction c : n.getRhs()) {
            operators.add("||");
            c.accept(this);
            operands.add(code.removeLast());
        }
        st.add("operators", operators);
        st.add("operands", operands);
    }
    code.add(st.render());
}
Also used : ST(org.stringtemplate.v4.ST)

Example 62 with ST

use of edu.princeton.cs.algs4.ST in project compiler by boalang.

the class CodeGeneratingVisitor method visit.

/** {@inheritDoc} */
@Override
public void visit(final DoStatement n) {
    final ST st = stg.getInstanceOf("DoWhile");
    n.getCondition().accept(this);
    st.add("condition", code.removeLast());
    n.getBody().accept(this);
    st.add("stmt", code.removeLast());
    code.add(st.render());
}
Also used : ST(org.stringtemplate.v4.ST)

Example 63 with ST

use of edu.princeton.cs.algs4.ST in project compiler by boalang.

the class CodeGeneratingVisitor method visit.

/** {@inheritDoc} */
@Override
public void visit(final Composite n) {
    final ST st = stg.getInstanceOf("Composite");
    if (n.getPairsSize() > 0) {
        String s = "\t{\n";
        for (final Pair p : n.getPairs()) {
            visit(p);
            s += "\t\t" + code.removeLast() + "\n";
        }
        s += "\t}";
        st.add("exprlist", s);
        st.add("type", n.type.toBoxedJavaType() + "()");
    } else if (n.getExprsSize() > 0) {
        // FIXME rdyer
        BoaType t = n.type;
        if (t instanceof BoaTuple) {
            final ST stup = stg.getInstanceOf("Tuple");
            stup.add("name", t.toJavaType());
            visit(n.getExprs());
            stup.add("exprlist", code.removeLast());
            code.add(stup.render());
            return;
        }
        visit(n.getExprs());
        if (t instanceof BoaArray) {
            if (((BoaArray) t).getType() instanceof BoaEnum) {
                st.add("exprlist", code.removeLast());
                st.add("type", "Object[] ");
                code.add(st.render());
                return;
            }
        }
        st.add("exprlist", code.removeLast());
        st.add("type", t.toJavaType());
    }
    code.add(st.render());
}
Also used : ST(org.stringtemplate.v4.ST)

Example 64 with ST

use of edu.princeton.cs.algs4.ST in project bender by Nextdoor.

the class BenderConfig method swapEnvironmentVariables.

/**
 * Parses an input String and replaces instances of {@literal <XXX>}" with the value of the XXX OS
 * Environment Variable. This is used as a pre-parser for the Config files, allowing environment
 * variables to be swapped at run-time.
 *
 * @param raw A raw string (not necessarily valid configuration data)
 * @return A parsed string with OS variables swapped in
 * @throws ConfigurationException If any discovered {@literal <WRAPPED_VALUES>} are not found in
 *         System.getenv().
 */
public static String swapEnvironmentVariables(String raw) throws ConfigurationException {
    ErrorBuffer errors = new ErrorBuffer();
    ST template = new ST(raw);
    STGroup g = template.groupThatCreatedThisInstance;
    g.setListener(errors);
    Map<String, String> env = System.getenv();
    for (String envName : env.keySet()) {
        template.add(envName, env.get(envName));
    }
    String parsed = template.render();
    if (errors.errors.size() > 0) {
        throw new ConfigurationException(errors.toString());
    }
    return parsed;
}
Also used : ST(org.stringtemplate.v4.ST) ErrorBuffer(org.stringtemplate.v4.misc.ErrorBuffer) STGroup(org.stringtemplate.v4.STGroup)

Example 65 with ST

use of edu.princeton.cs.algs4.ST in project bookish by parrt.

the class Tex2SVG method tex2svg.

public Triple<String, Float, Float> tex2svg(String latex, LatexType type, int fontsize) {
    try {
        latex = latex.trim();
        String tmpdir = new File(outputDir).getAbsolutePath();
        if (!Files.exists(Paths.get(tmpdir))) {
            Files.createDirectories(Paths.get(tmpdir));
        }
        if (!Files.exists(Paths.get(tmpdir + "/images"))) {
            Files.createSymbolicLink(Paths.get(tmpdir + "/images"), Paths.get(outputDir + "/images"));
        }
        String texfilename = tmpdir + "/temp.tex";
        ST template = null;
        switch(type) {
            case EQN:
                template = templates.getInstanceOf("eqntex");
                break;
            case BLOCKEQN:
                template = templates.getInstanceOf("blockeqntex");
                break;
            case LATEX:
                template = templates.getInstanceOf("blocktex");
                break;
        }
        template.add("text", latex);
        template.add("fontsize", fontsize);
        Files.write(Paths.get(texfilename), template.render().getBytes());
        // System.out.println("wrote "+texfilename);
        String[] results = execInDir(tmpdir, "xelatex", "-shell-escape", "-interaction=nonstopmode", "temp.tex");
        // println(results.a)
        String metricsRegex = "// bookish metrics: ([0-9]*[.][0-9]+)pt, ([0-9]*[.][0-9]+)pt";
        Pattern metricsPattern = Pattern.compile("metricsRegex");
        String log = ParrtIO.load(tmpdir + "/temp.log");
        float height = 0, depth = 0;
        for (String line : results[0].split("\n")) {
            String prefix = "// bookish metrics: ";
            if (line.startsWith(prefix)) {
                int first = prefix.length();
                int comma = line.indexOf(',');
                String heightS = line.substring(first, comma - "pt".length());
                String depthS = line.substring(comma + 1, line.indexOf('p', comma));
                height = Float.parseFloat(heightS);
                depth = Float.parseFloat(depthS);
            }
            if (line.startsWith("!") || line.startsWith("l.")) {
                System.err.println(line);
                System.err.println(latex);
            }
        }
        if (results[1].length() > 0) {
            System.err.println(results[1]);
        }
        results = execInDir(tmpdir, "pdfcrop", "temp.pdf");
        if (results[1].length() > 0) {
            System.err.println(results[1]);
        }
        results = execInDir(tmpdir, "pdf2svg", "temp-crop.pdf", "temp.svg");
        if (results[1].length() > 0) {
            System.err.println(results[1]);
        }
        String svgfilename = tmpdir + "/temp.svg";
        return new Triple<>(new String(Files.readAllBytes(Paths.get(svgfilename))), height, depth);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : Triple(org.antlr.v4.runtime.misc.Triple) ST(org.stringtemplate.v4.ST) Pattern(java.util.regex.Pattern) STGroupFile(org.stringtemplate.v4.STGroupFile) File(java.io.File)

Aggregations

ST (org.stringtemplate.v4.ST)197 GrammarAST (org.antlr.v4.tool.ast.GrammarAST)37 STGroup (org.stringtemplate.v4.STGroup)24 File (java.io.File)19 ArrayList (java.util.ArrayList)16 IOException (java.io.IOException)12 STGroupFile (org.stringtemplate.v4.STGroupFile)12 Path (java.nio.file.Path)10 Test (org.junit.Test)10 ATNFactory (org.antlr.v4.automata.ATNFactory)9 LexerATNFactory (org.antlr.v4.automata.LexerATNFactory)9 ParserATNFactory (org.antlr.v4.automata.ParserATNFactory)9 CodeGenerator (org.antlr.v4.codegen.CodeGenerator)9 SemanticPipeline (org.antlr.v4.semantics.SemanticPipeline)9 Grammar (org.antlr.v4.tool.Grammar)9 LexerGrammar (org.antlr.v4.tool.LexerGrammar)9 STGroupString (org.stringtemplate.v4.STGroupString)9 LinkedHashMap (java.util.LinkedHashMap)7 URL (java.net.URL)6 Map (java.util.Map)6