Search in sources :

Example 41 with ST

use of edu.princeton.cs.algs4.ST in project uPortal by Jasig.

the class EmailPasswordResetNotificationImpl method formatBody.

/**
 * Get the body content of the email.
 *
 * @param resetUrl the password reset URL
 * @param account the user account that has had its password reset
 * @param locale the locale of the user who reset the password
 * @return The message body as a string.
 */
private String formatBody(URL resetUrl, ILocalAccountPerson account, Locale locale) {
    final STGroup group = new STGroupDir(templateDir, '$', '$');
    final ST template = group.getInstanceOf(templateName);
    String name = findDisplayNameFromLocalAccountPerson(account);
    template.add("displayName", name);
    template.add("url", resetUrl.toString());
    return template.render();
}
Also used : ST(org.stringtemplate.v4.ST) STGroupDir(org.stringtemplate.v4.STGroupDir) STGroup(org.stringtemplate.v4.STGroup)

Example 42 with ST

use of edu.princeton.cs.algs4.ST in project bndtools by bndtools.

the class STTests method test.

@Test
public void test() {
    STGroupDir group = new STGroupDir("testdata/stuff", '$', '$');
    ST st = group.getInstanceOf("foo");
    st.add("name", "Neil");
    System.out.println(st.render());
}
Also used : ST(org.stringtemplate.v4.ST) STGroupDir(org.stringtemplate.v4.STGroupDir) Test(org.junit.Test)

Example 43 with ST

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

the class BoaCompiler method main.

public static void main(final String[] args) throws IOException {
    CommandLine cl = processCommandLineOptions(args);
    if (cl == null)
        return;
    final ArrayList<File> inputFiles = BoaCompiler.inputFiles;
    // get the name of the generated class
    final String className = getGeneratedClass(cl);
    // get the filename of the jar we will be writing
    final String jarName;
    if (cl.hasOption('o'))
        jarName = cl.getOptionValue('o');
    else
        jarName = className + ".jar";
    // make the output directory
    File outputRoot = null;
    if (cl.hasOption("cd")) {
        outputRoot = new File(cl.getOptionValue("cd"));
    } else {
        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);
    // find custom libs to load
    final List<URL> libs = new ArrayList<URL>();
    if (cl.hasOption('l'))
        for (final String lib : cl.getOptionValues('l')) libs.add(new File(lib).toURI().toURL());
    final File outputFile = new File(outputSrcDir, className + ".java");
    final BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(outputFile));
    try {
        final List<String> jobnames = new ArrayList<String>();
        final List<String> jobs = new ArrayList<String>();
        final List<Integer> seeds = new ArrayList<Integer>();
        boolean isSimple = true;
        final List<Program> visitorPrograms = new ArrayList<Program>();
        SymbolTable.initialize(libs);
        final int maxVisitors;
        if (cl.hasOption('v'))
            maxVisitors = Integer.parseInt(cl.getOptionValue('v'));
        else
            maxVisitors = Integer.MAX_VALUE;
        for (int i = 0; i < inputFiles.size(); i++) {
            final File f = inputFiles.get(i);
            try {
                final BoaLexer lexer = new BoaLexer(new ANTLRFileStream(f.getAbsolutePath()));
                // use the whole input string to seed the RNG
                seeds.add(lexer._input.getText(new Interval(0, lexer._input.size())).hashCode());
                lexer.removeErrorListeners();
                lexer.addErrorListener(new LexerErrorListener());
                final CommonTokenStream tokens = new CommonTokenStream(lexer);
                final BoaParser parser = new BoaParser(tokens);
                parser.removeErrorListeners();
                parser.addErrorListener(new BaseErrorListener() {

                    @Override
                    public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) throws ParseCancellationException {
                        throw new ParseCancellationException(e);
                    }
                });
                final BoaErrorListener parserErrorListener = new ParserErrorListener();
                final Start p = parse(tokens, parser, parserErrorListener);
                if (cl.hasOption("ast"))
                    new ASTPrintingVisitor().start(p);
                final String jobName = "" + i;
                try {
                    if (!parserErrorListener.hasError) {
                        new TypeCheckingVisitor().start(p, new SymbolTable());
                        final TaskClassifyingVisitor simpleVisitor = new TaskClassifyingVisitor();
                        simpleVisitor.start(p);
                        LOG.info(f.getName() + ": task complexity: " + (!simpleVisitor.isComplex() ? "simple" : "complex"));
                        isSimple &= !simpleVisitor.isComplex();
                        new InheritedAttributeTransformer().start(p);
                        new LocalAggregationTransformer().start(p);
                        // also let jobs have own methods if visitor merging is disabled
                        if (!simpleVisitor.isComplex() || maxVisitors < 2 || inputFiles.size() == 1) {
                            new VisitorOptimizingTransformer().start(p);
                            if (cl.hasOption("pp"))
                                new PrettyPrintVisitor().start(p);
                            if (cl.hasOption("ast2"))
                                new ASTPrintingVisitor().start(p);
                            final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(jobName);
                            cg.start(p);
                            jobs.add(cg.getCode());
                            jobnames.add(jobName);
                        } else // if a job has visitors, fuse them all together into a single program
                        {
                            p.getProgram().jobName = jobName;
                            visitorPrograms.add(p.getProgram());
                        }
                    }
                } catch (final TypeCheckException e) {
                    parserErrorListener.error("typecheck", lexer, null, e.n.beginLine, e.n.beginColumn, e.n2.endColumn - e.n.beginColumn + 1, e.getMessage(), e);
                }
            } catch (final Exception e) {
                System.err.print(f.getName() + ": compilation failed: ");
                e.printStackTrace();
            }
        }
        if (!visitorPrograms.isEmpty())
            try {
                for (final Program p : new VisitorMergingTransformer().mergePrograms(visitorPrograms, maxVisitors)) {
                    new VisitorOptimizingTransformer().start(p);
                    if (cl.hasOption("pp"))
                        new PrettyPrintVisitor().start(p);
                    if (cl.hasOption("ast2"))
                        new ASTPrintingVisitor().start(p);
                    final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(p.jobName);
                    cg.start(p);
                    jobs.add(cg.getCode());
                    jobnames.add(p.jobName);
                }
            } catch (final Exception e) {
                System.err.println("error fusing visitors - falling back: " + e);
                e.printStackTrace();
                for (final Program p : visitorPrograms) {
                    new VisitorOptimizingTransformer().start(p);
                    if (cl.hasOption("pp"))
                        new PrettyPrintVisitor().start(p);
                    if (cl.hasOption("ast2"))
                        new ASTPrintingVisitor().start(p);
                    final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(p.jobName);
                    cg.start(p);
                    jobs.add(cg.getCode());
                    jobnames.add(p.jobName);
                }
            }
        if (jobs.size() == 0)
            throw new RuntimeException("no files compiled without error");
        final ST st = AbstractCodeGeneratingVisitor.stg.getInstanceOf("Program");
        st.add("name", className);
        st.add("numreducers", inputFiles.size());
        st.add("jobs", jobs);
        st.add("jobnames", jobnames);
        st.add("combineTables", CodeGeneratingVisitor.combineAggregatorStrings);
        st.add("reduceTables", CodeGeneratingVisitor.reduceAggregatorStrings);
        st.add("splitsize", isSimple ? 64 * 1024 * 1024 : 10 * 1024 * 1024);
        st.add("seeds", seeds);
        if (DefaultProperties.localDataPath != null) {
            st.add("isLocal", true);
        }
        o.write(st.render().getBytes());
    } finally {
        o.close();
    }
    compileGeneratedSrc(cl, jarName, outputRoot, outputFile);
}
Also used : BoaParser(boa.parser.BoaParser) Start(boa.compiler.ast.Start) ArrayList(java.util.ArrayList) URL(java.net.URL) VisitorOptimizingTransformer(boa.compiler.transforms.VisitorOptimizingTransformer) BoaErrorListener(boa.compiler.listeners.BoaErrorListener) TypeCheckingVisitor(boa.compiler.visitors.TypeCheckingVisitor) BufferedOutputStream(java.io.BufferedOutputStream) BoaLexer(boa.parser.BoaLexer) PrettyPrintVisitor(boa.compiler.visitors.PrettyPrintVisitor) CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) ST(org.stringtemplate.v4.ST) Program(boa.compiler.ast.Program) LexerErrorListener(boa.compiler.listeners.LexerErrorListener) BaseErrorListener(org.antlr.v4.runtime.BaseErrorListener) InheritedAttributeTransformer(boa.compiler.transforms.InheritedAttributeTransformer) VisitorMergingTransformer(boa.compiler.transforms.VisitorMergingTransformer) LocalAggregationTransformer(boa.compiler.transforms.LocalAggregationTransformer) IOException(java.io.IOException) TaskClassifyingVisitor(boa.compiler.visitors.TaskClassifyingVisitor) FileNotFoundException(java.io.FileNotFoundException) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) IOException(java.io.IOException) RecognitionException(org.antlr.v4.runtime.RecognitionException) ParserErrorListener(boa.compiler.listeners.ParserErrorListener) CommandLine(org.apache.commons.cli.CommandLine) ANTLRFileStream(org.antlr.v4.runtime.ANTLRFileStream) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) FileOutputStream(java.io.FileOutputStream) AbstractCodeGeneratingVisitor(boa.compiler.visitors.AbstractCodeGeneratingVisitor) CodeGeneratingVisitor(boa.compiler.visitors.CodeGeneratingVisitor) ASTPrintingVisitor(boa.compiler.visitors.ASTPrintingVisitor) File(java.io.File) RecognitionException(org.antlr.v4.runtime.RecognitionException) Interval(org.antlr.v4.runtime.misc.Interval)

Example 44 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 EnumType n) {
    final ST st = stg.getInstanceOf("EnumType");
    if (!(n.type instanceof BoaEnum))
        throw new TypeCheckException(n, "type " + n.type + " is not a enum type");
    final BoaEnum enumType = ((BoaEnum) n.type);
    final BoaType fieldType = enumType.getType();
    final List<String> fields = new ArrayList<String>();
    final List<String> values = new ArrayList<String>();
    for (final EnumBodyDeclaration c : n.getMembers()) {
        Factor f = c.getExp().getLhs().getLhs().getLhs().getLhs().getLhs();
        if (f.getOperand() instanceof ILiteral) {
            code.add(((ILiteral) (f.getOperand())).getLiteral());
            fields.add(c.getIdentifier().getToken());
            values.add(code.removeLast());
        }
    }
    st.add("ename", enumType.toJavaType());
    st.add("fields", fields);
    st.add("values", values);
    st.add("fname", fieldType.toJavaType());
    code.add(st.render());
}
Also used : ST(org.stringtemplate.v4.ST) TypeCheckException(boa.compiler.TypeCheckException)

Example 45 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 Call n) {
    final ST st = stg.getInstanceOf("Call");
    this.idFinder.start(n.env.getOperand());
    final String funcName = this.idFinder.getNames().toArray()[0].toString();
    final BoaFunction f = n.env.getFunction(funcName, check(n));
    n.env.setOperandType(n.type);
    if (f.hasMacro()) {
        final List<String> parts = new ArrayList<String>();
        for (final Expression e : n.getArgs()) {
            e.accept(this);
            parts.add(code.removeLast());
        }
        final String s = expand(f.getMacro(), n.getArgs(), parts.toArray(new String[] {}));
        // FIXME rdyer a hack, so that "def(pbuf.attr)" generates "pbuf.hasAttr()"
        if (funcName.equals("def") && n.getArgsSize() == 1) {
            final Matcher m = Pattern.compile("\\((\\w+).get(\\w+)\\(\\) != null\\)").matcher(s);
            if (m.matches() && !m.group(2).endsWith("List"))
                st.add("call", m.group(1) + ".has" + m.group(2) + "()");
            else // so instead, since they are always defined, replace with 'true'
            if (n.getArg(0).type instanceof BoaScalar && !(n.getArg(0).type instanceof BoaString) && !(n.getArg(0).type instanceof BoaTuple))
                st.add("call", "true");
            else
                st.add("call", s);
        } else {
            st.add("call", s);
        }
    } else {
        if (f.hasName()) {
            st.add("operand", f.getName());
        } else {
            n.env.getOperand().accept(this);
            st.add("operand", code.removeLast() + ".invoke");
        }
        if (n.getArgsSize() > 0) {
            visit(n.getArgs());
            st.add("parameters", code.removeLast());
        }
    }
    code.add(st.render());
}
Also used : ST(org.stringtemplate.v4.ST) Matcher(java.util.regex.Matcher)

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