<commit_before>package com.poco.PoCoCompiler;


import com.poco.PoCoParser.PoCoParser;
import com.poco.PoCoParser.PoCoParserBaseVisitor;
import com.poco.Extractor.Closure;
import org.antlr.v4.runtime.misc.NotNull;

import java.io.PrintWriter;
import java.sql.SQLSyntaxErrorException;
import java.util.Stack;

import com.poco.Extractor.VarTypeVal;
import sun.jvm.hotspot.debugger.posix.elf.ELFSectionHeader;

/**
 * Generates the Java code to create a PoCoPolicy object representing
 * the parsed PoCo policy.
 */
public class PolicyVisitor extends PoCoParserBaseVisitor<Void> {
    private final int indentLevel;
    private final PrintWriter out;

    private int executionNum;
    private Stack<String> executionNames;

    private int exchangeNum;
    private String currentExchange;
    private boolean isReturnValue;

    private int matchsNum;
    private Stack<String> matchsNames;

    private int matchNum;
    private String currentMatch;

    private Closure closure;

    private String currentAction;
    private int sreNum;

    private int actionNum;

    private boolean matchRHS    = false;
    private boolean hasAsterisk = false;
    private boolean hasPlus     = false;

    /**
     * Constructor
     *
     * @param out         output stream to write to (a PrintWriter-wrapped Java or AspectJ file)
     * @param indentLevel base indent level for all code generated by PolicyVisitor
     */
    public PolicyVisitor(PrintWriter out, int indentLevel, Closure closure1) {
        this.out = out;
        this.indentLevel = indentLevel;

        // Initialize execution data structures
        this.executionNum = 0;
        this.executionNames = new Stack<>();

        // Initialize exchange data structures
        this.exchangeNum = 0;
        this.currentExchange = null;
        this.isReturnValue = false;

        // Initialize Matchs data structures
        this.matchsNum = 0;
        this.matchsNames = new Stack<>();

        // Initialize Match data structures
        this.matchNum = 0;
        this.currentMatch = null;

        // Initialize SRE data structures
        this.currentAction = null;
        this.sreNum = 0;

        this.actionNum = 0;

        this.closure = closure1;
    }

    /**
     * Outputs one line of Java/AspectJ code to the out object (always ends in newline).
     *
     * @param indent indent level of current line (relative to the existing indent level)
     * @param text   code to write out (printf style formatting used)
     * @param args   printf-style arguments
     */
    private void outLine(int indent, String text, Object... args) {
        outPartial(indent, text, args);
        outPartial(-1, "\n");
    }

    /**
     * Outputs Java/AspectJ code without appending newline. Use a negative indent value to
     * disable indents.
     *
     * @param indent indent level (relative to existing indent level), or negative to disable indents
     * @param text   code to write out (printf style formatting used)
     * @param args   printf-style arguments
     */
    private void outPartial(int indent, String text, Object... args) {
        if (indent >= 0) {
            int trueIndent = (indent + indentLevel) * 4;

            for (int i = 0; i < trueIndent; i++) {
                out.format(" ");
            }
        }
        out.format(text, args);
    }

    /**
     * Generates code for class representing a PoCo policy. This is the first visit method called.
     *
     * @param ctx
     * @return
     */
    @Override
    public Void visitPocopol(@NotNull PoCoParser.PocopolContext ctx) {
        String policyName = ctx.id().getText();

        outLine(0, "class %s extends Policy {", policyName);
        outLine(1, "public %s() {", policyName);
        outLine(2, "try {");
        executionNames.push("ROOT");
        visitChildren(ctx);
        executionNames.pop();
        outLine(2, "} catch (PoCoException pex) {");
        outLine(3, "System.out.println(pex.getMessage());");
        outLine(3, "pex.printStackTrace();");
        outLine(3, "System.exit(-1);");
        outLine(2, "}");
        outLine(1, "}");
        outLine(0, "}");

        return null;
    }

    @Override
    public Void visitParamlist(@NotNull PoCoParser.ParamlistContext ctx) {
        // TODO: Support actual policy parameters (as references to policy objects)

        visitChildren(ctx);

        return null;
    }

    @Override
    public Void visitExecution(@NotNull PoCoParser.ExecutionContext ctx) {
        // TODO: Support non-sequential executions
        if(ctx.exch() == null) {
            // Get modifier of execution (i.e. + or *), if any
            if (ctx.ASTERISK() != null)
                hasAsterisk = true;
            else if (ctx.PLUS() != null)
                hasPlus = true;
            else {
                hasAsterisk = false;
                hasPlus     = false;
            }
            visitChildren(ctx);
        }
        else if (ctx.exch() != null) {
            String executionName = "exec" + executionNum++;
            String parentExecutionName = executionNames.peek();
            String modifier = "none";

            // Get modifier of execution (i.e. + or *), if any
            if (hasAsterisk)
                modifier = "*";
            else if (hasPlus)
                modifier = "+";


            // This execution becomes the parent of all children
            executionNames.push(executionName);

            // CODE GENERATION:
            // Declare new execution variable and initialize it
            outLine(3, "SequentialExecution %s = new SequentialExecution(\"%s\");", executionName, modifier);

            // Visit children, who will add themselves as children to this execution.
            visitChildren(ctx);

            // Add this execution as a child to the parent
            /*if (parentExecutionName == "ROOT") {
                outLine(3, "rootExecution = %s;", executionName);
            } else {
                outLine(3, "%s.addChild(%s);", parentExecutionName, executionName);
            }*/
            outLine(3, "root.addChild(%s);", executionName);<commit_msg>add policy to root policy<commit_after>package com.poco.PoCoCompiler;


import com.poco.PoCoParser.PoCoParser;
import com.poco.PoCoParser.PoCoParserBaseVisitor;
import com.poco.Extractor.Closure;
import org.antlr.v4.runtime.misc.NotNull;

import java.io.PrintWriter;
import java.sql.SQLSyntaxErrorException;
import java.util.Stack;

import com.poco.Extractor.VarTypeVal;
import sun.jvm.hotspot.debugger.posix.elf.ELFSectionHeader;

/**
 * Generates the Java code to create a PoCoPolicy object representing
 * the parsed PoCo policy.
 */
public class PolicyVisitor extends PoCoParserBaseVisitor<Void> {
    private final int indentLevel;
    private final PrintWriter out;

    private int executionNum;
    private Stack<String> executionNames;

    private int exchangeNum;
    private String currentExchange;
    private boolean isReturnValue;

    private int matchsNum;
    private Stack<String> matchsNames;

    private int matchNum;
    private String currentMatch;

    private Closure closure;

    private String currentAction;
    private int sreNum;

    private int actionNum;

    private boolean matchRHS    = false;
    private boolean hasAsterisk = false;
    private boolean hasPlus     = false;

    /**
     * Constructor
     *
     * @param out         output stream to write to (a PrintWriter-wrapped Java or AspectJ file)
     * @param indentLevel base indent level for all code generated by PolicyVisitor
     */
    public PolicyVisitor(PrintWriter out, int indentLevel, Closure closure1) {
        this.out = out;
        this.indentLevel = indentLevel;

        // Initialize execution data structures
        this.executionNum = 0;
        this.executionNames = new Stack<>();

        // Initialize exchange data structures
        this.exchangeNum = 0;
        this.currentExchange = null;
        this.isReturnValue = false;

        // Initialize Matchs data structures
        this.matchsNum = 0;
        this.matchsNames = new Stack<>();

        // Initialize Match data structures
        this.matchNum = 0;
        this.currentMatch = null;

        // Initialize SRE data structures
        this.currentAction = null;
        this.sreNum = 0;

        this.actionNum = 0;

        this.closure = closure1;
    }

    /**
     * Outputs one line of Java/AspectJ code to the out object (always ends in newline).
     *
     * @param indent indent level of current line (relative to the existing indent level)
     * @param text   code to write out (printf style formatting used)
     * @param args   printf-style arguments
     */
    private void outLine(int indent, String text, Object... args) {
        outPartial(indent, text, args);
        outPartial(-1, "\n");
    }

    /**
     * Outputs Java/AspectJ code without appending newline. Use a negative indent value to
     * disable indents.
     *
     * @param indent indent level (relative to existing indent level), or negative to disable indents
     * @param text   code to write out (printf style formatting used)
     * @param args   printf-style arguments
     */
    private void outPartial(int indent, String text, Object... args) {
        if (indent >= 0) {
            int trueIndent = (indent + indentLevel) * 4;

            for (int i = 0; i < trueIndent; i++) {
                out.format(" ");
            }
        }
        out.format(text, args);
    }

    /**
     * Generates code for class representing a PoCo policy. This is the first visit method called.
     *
     * @param ctx
     * @return
     */
    @Override
    public Void visitPocopol(@NotNull PoCoParser.PocopolContext ctx) {
        String policyName = ctx.id().getText();

        outLine(0, "class %s extends Policy {", policyName);
        outLine(1, "public %s() {", policyName);
        outLine(2, "try {");
        executionNames.push("ROOT");
        visitChildren(ctx);
        executionNames.pop();
        outLine(2, "} catch (PoCoException pex) {");
        outLine(3, "System.out.println(pex.getMessage());");
        outLine(3, "pex.printStackTrace();");
        outLine(3, "System.exit(-1);");
        outLine(2, "}");
        outLine(1, "}");
        outLine(0, "}");

        outLine(0, "%s policy1 = new %s();",policyName,policyName);
        outLine(0, "root.setChild(policy1);");

        return null;
    }

    @Override
    public Void visitParamlist(@NotNull PoCoParser.ParamlistContext ctx) {
        // TODO: Support actual policy parameters (as references to policy objects)

        visitChildren(ctx);

        return null;
    }

    @Override
    public Void visitExecution(@NotNull PoCoParser.ExecutionContext ctx) {
        // TODO: Support non-sequential executions
        if(ctx.exch() == null) {
            // Get modifier of execution (i.e. + or *), if any
            if (ctx.ASTERISK() != null)
                hasAsterisk = true;
            else if (ctx.PLUS() != null)
                hasPlus = true;
            else {
                hasAsterisk = false;
                hasPlus     = false;
            }
            visitChildren(ctx);
        }
        else if (ctx.exch() != null) {
            String executionName = "exec" + executionNum++;
            String parentExecutionName = executionNames.peek();
            String modifier = "none";

            // Get modifier of execution (i.e. + or *), if any
            if (hasAsterisk)
                modifier = "*";
            else if (hasPlus)
                modifier = "+";


            // This execution becomes the parent of all children
            executionNames.push(executionName);

            // CODE GENERATION:
            // Declare new execution variable and initialize it
            outLine(3, "SequentialExecution %s = new SequentialExecution(\"%s\");", executionName, modifier);

            // Visit children, who will add themselves as children to this execution.
            visitChildren(ctx);

            // Add this execution as a child to the parent
            /*if (parentExecutionName == "ROOT") {
                outLine(3, "rootExecution = %s;", executionName);
            } else {
                outLine(3, "%s.addChild(%s);", parentExecutionName, executionName);
            }*/
            outLine(3, "rootExecution.addChild(%s);", executionName);
{'fraction_non_alphanumeric': 0.10071710579324793, 'fraction_numerical': 0.0048344210780759, 'mean_word_length': 2.1752366334100794, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5516851', 'n_tokens_mistral': 3441, 'n_tokens_neox': 3299, 'n_words': 1024}