Search in sources :

Example 46 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 Program n) {
    final ST st = stg.getInstanceOf("Job");
    st.add("name", this.name);
    this.varDecl.start(n);
    this.functionDeclarator.start(n);
    this.tupleDeclarator.start(n);
    this.enumDeclarator.start(n);
    if (this.functionDeclarator.hasCode())
        st.add("staticDeclarations", this.varDecl.getCode() + "\n" + this.functionDeclarator.getCode());
    else
        st.add("staticDeclarations", this.varDecl.getCode());
    if (this.tupleDeclarator.hasCode())
        st.add("staticDeclarations", "\n" + this.tupleDeclarator.getCode());
    if (this.enumDeclarator.hasCode())
        st.add("staticDeclarations", "\n" + this.enumDeclarator.getCode());
    this.staticInitialization.start(n);
    if (this.staticInitialization.hasCode())
        st.add("staticStatements", this.staticInitialization.getCode());
    final List<String> statements = new ArrayList<String>();
    for (final Statement s : n.getStatements()) {
        s.accept(this);
        final String statement = code.removeLast();
        if (!statement.isEmpty())
            statements.add(statement);
    }
    st.add("statements", statements);
    if (this.aggregators.size() == 0)
        throw new TypeCheckException(n, "No output variables were declared - must declare at least one output variable");
    for (final Entry<String, AggregatorDescription> entry : this.aggregators.entrySet()) {
        String id = entry.getKey();
        String prefix = name;
        if (id.matches("\\d+_.*")) {
            prefix = id.substring(0, id.indexOf('_'));
            id = id.substring(id.indexOf('_') + 1);
        }
        final AggregatorDescription description = entry.getValue();
        final String parameters = description.getParameters() == null ? "" : description.getParameters().get(0);
        final BoaType type = description.getType();
        final StringBuilder src = new StringBuilder();
        boolean combines = false;
        for (final Class<?> c : n.env.getAggregators(description.getAggregator(), type)) {
            src.append(", new " + c.getCanonicalName() + "(" + parameters + ")");
            try {
                final AggregatorSpec annotation = c.getAnnotation(AggregatorSpec.class);
                if (annotation.canCombine())
                    combines = true;
            } catch (final RuntimeException e) {
                throw new TypeCheckException(n, e.getMessage(), e);
            }
        }
        if (combines)
            combineAggregatorStrings.add("this.aggregators.put(\"" + prefix + "::" + id + "\", " + src.toString().substring(2) + ");");
        reduceAggregatorStrings.add("this.aggregators.put(\"" + prefix + "::" + id + "\", " + src.toString().substring(2) + ");");
    }
    code.add(st.render());
}
Also used : ST(org.stringtemplate.v4.ST) TypeCheckException(boa.compiler.TypeCheckException) AggregatorSpec(boa.aggregators.AggregatorSpec)

Example 47 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 ReturnStatement n) {
    final ST st = stg.getInstanceOf("Return");
    if (n.hasExpr()) {
        n.getExpr().accept(this);
        st.add("expr", code.removeLast());
    }
    code.add(st.render());
}
Also used : ST(org.stringtemplate.v4.ST)

Example 48 with ST

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

the class BaseTest method codegen.

protected StartContext codegen(final String input, final String error) throws IOException {
    final File outputRoot = new File(new File(System.getProperty("java.io.tmpdir")), UUID.randomUUID().toString());
    final File outputSrcDir = new File(outputRoot, "boa");
    if (!outputSrcDir.mkdirs())
        throw new IOException("unable to mkdir " + outputSrcDir);
    final File outputFile = new File(outputSrcDir, "Test.java");
    CodeGeneratingVisitor.combineAggregatorStrings.clear();
    CodeGeneratingVisitor.reduceAggregatorStrings.clear();
    final List<String> jobnames = new ArrayList<String>();
    final List<String> jobs = new ArrayList<String>();
    final List<Integer> seeds = new ArrayList<Integer>();
    final StartContext ctx = typecheck(input);
    // use the whole input string to seed the RNG
    seeds.add(input.hashCode());
    final Start p = ctx.ast;
    try {
        new InheritedAttributeTransformer().start(p);
        new LocalAggregationTransformer().start(p);
        new VisitorOptimizingTransformer().start(p);
        final CodeGeneratingVisitor cg = new CodeGeneratingVisitor("1");
        cg.start(p);
        jobs.add(cg.getCode());
        jobnames.add("1");
        final ST st = AbstractCodeGeneratingVisitor.stg.getInstanceOf("Program");
        st.add("name", "Test");
        st.add("numreducers", 1);
        st.add("jobs", jobs);
        st.add("jobnames", jobnames);
        st.add("combineTables", CodeGeneratingVisitor.combineAggregatorStrings);
        st.add("reduceTables", CodeGeneratingVisitor.reduceAggregatorStrings);
        st.add("splitsize", 64 * 1024 * 1024);
        st.add("seeds", seeds);
        final BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(outputFile));
        try {
            o.write(st.render().getBytes());
        } finally {
            o.close();
        }
        final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(new File[] { outputFile }));
        if (!compiler.getTask(null, fileManager, diagnostics, Arrays.asList(new String[] { "-cp", System.getProperty("java.class.path") }), null, compilationUnits).call())
            for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) throw new RuntimeException("Error on line " + diagnostic.getLineNumber() + ": " + diagnostic.getMessage(null));
        if (error != null)
            fail("expected to see exception: " + error);
    } catch (final Exception e) {
        if (error == null) {
            if (e.getMessage() == null) {
                e.printStackTrace();
                fail("unexpected exception");
            } else
                fail("found unexpected exception: " + e.getMessage());
        } else
            assertEquals(error, e.getMessage());
    }
    delete(outputSrcDir);
    return ctx;
}
Also used : Start(boa.compiler.ast.Start) ArrayList(java.util.ArrayList) Diagnostic(javax.tools.Diagnostic) JavaFileObject(javax.tools.JavaFileObject) VisitorOptimizingTransformer(boa.compiler.transforms.VisitorOptimizingTransformer) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) BufferedOutputStream(java.io.BufferedOutputStream) ST(org.stringtemplate.v4.ST) InheritedAttributeTransformer(boa.compiler.transforms.InheritedAttributeTransformer) JavaCompiler(javax.tools.JavaCompiler) LocalAggregationTransformer(boa.compiler.transforms.LocalAggregationTransformer) IOException(java.io.IOException) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) IOException(java.io.IOException) RecognitionException(org.antlr.v4.runtime.RecognitionException) StartContext(boa.parser.BoaParser.StartContext) FileOutputStream(java.io.FileOutputStream) AbstractCodeGeneratingVisitor(boa.compiler.visitors.AbstractCodeGeneratingVisitor) CodeGeneratingVisitor(boa.compiler.visitors.CodeGeneratingVisitor) File(java.io.File)

Example 49 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 ExprStatement n) {
    final ST st = stg.getInstanceOf("ExprStatement");
    n.getExpr().accept(this);
    st.add("expression", code.removeLast());
    code.add(st.render());
}
Also used : ST(org.stringtemplate.v4.ST)

Example 50 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 IfAllStatement n) {
    final ST st = stg.getInstanceOf("WhenStatement");
    st.add("all", "true");
    generateQuantifier(n, n.getVar(), n.getCondition(), n.getBody(), "ifall", st);
}
Also used : ST(org.stringtemplate.v4.ST)

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