Ejemplo n.º 1
0
 public static Integer getBitwidth(ASTNode t) {
   String bitwidth = t.getAttribute(Attribute.BITWIDTH_KEY);
   if (bitwidth == null) {
     return null;
   }
   try {
     return Integer.parseInt(bitwidth);
   } catch (NumberFormatException e) {
     GlobalSettings.kem.registerCriticalError(
         "Expected variable attribute 'bitwidth' to "
             + "be an integer, found: "
             + t.getAttribute("bitwidth"),
         e);
     throw new AssertionError("unreachable");
   }
 }
Ejemplo n.º 2
0
  /**
   * Print maudified program to standard output.
   *
   * <p>Save it in kompiled cache under pgm.maude.
   */
  public static Term processPgm(
      String content,
      String filename,
      Definition def,
      String startSymbol,
      Context context,
      GlobalSettings.ParserType whatParser)
      throws TransformerException {
    Stopwatch.sw.printIntermediate("Importing Files");
    assert context.definedSorts.contains(startSymbol)
        : "The start symbol must be declared in the definition. Found: " + startSymbol;

    try {
      ASTNode out;
      if (whatParser == GlobalSettings.ParserType.GROUND) {
        org.kframework.parser.concrete.KParser.ImportTblGround(
            context.kompiled.getCanonicalPath() + "/ground/Concrete.tbl");
        out = DefinitionLoader.parseCmdString(content, filename, startSymbol, context);
        out = out.accept(new RemoveBrackets(context));
        out = out.accept(new AddEmptyLists(context));
        out = out.accept(new RemoveSyntacticCasts(context));
        out = out.accept(new FlattenSyntax(context));
      } else if (whatParser == GlobalSettings.ParserType.RULES) {
        org.kframework.parser.concrete.KParser.ImportTbl(
            context.kompiled.getCanonicalPath() + "/def/Concrete.tbl");
        out = DefinitionLoader.parsePattern(content, filename, startSymbol, context);
        out = out.accept(new RemoveBrackets(context));
        out = out.accept(new AddEmptyLists(context));
        out = out.accept(new RemoveSyntacticCasts(context));
        try {
          out = new RuleCompilerSteps(def, context).compile(new Rule((Sentence) out), null);
        } catch (CompilerStepDone e) {
          out = (ASTNode) e.getResult();
        }
        out = ((Rule) out).getBody();
      } else if (whatParser == GlobalSettings.ParserType.BINARY) {
        out = (org.kframework.kil.Cell) BinaryLoader.load(filename);
      } else {
        out = loadPgmAst(content, filename, startSymbol, context);
        out = out.accept(new ResolveVariableAttribute(context));
      }
      Stopwatch.sw.printIntermediate("Parsing Program");

      return (Term) out;
    } catch (IOException e) {
      String msg = "Cannot parse program: " + e.getLocalizedMessage();
      throw new TransformerException(
          new KException(
              ExceptionType.ERROR, KExceptionGroup.CRITICAL, msg, filename, "File system."));
    }
  }
Ejemplo n.º 3
0
  public String kilToKore(ASTNode node) {

    try {
      node.accept(builtinTrans).accept(kappTrans).accept(koreTrans);
      // node.accept(kappTrans).accept(koreTrans);
    } catch (TransformerException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return koreTrans.getResult();
  }
Ejemplo n.º 4
0
  /**
   * Load program file to ASTNode.
   *
   * <p>Write pgm.xml cache in given dotk folder.
   *
   * @param kappize If true, then apply KAppModifier to AST.
   */
  public static ASTNode loadPgmAst(
      String content, String filename, Boolean kappize, String startSymbol, Context context)
      throws IOException, TransformerException {
    File tbl = new File(context.kompiled.getCanonicalPath() + "/pgm/Program.tbl");

    // ------------------------------------- import files in Stratego
    ASTNode out;

    if (GlobalSettings.fastKast) {
      // out = Sglri.run_sglri(context.kompiled.getAbsolutePath() + "/pgm/Program.tbl", startSymbol,
      // content);
      JavaClassesFactory.startConstruction(context);
      out =
          Sglr.run_sglri(
              context.kompiled.getAbsolutePath() + "/pgm/Program.tbl",
              startSymbol,
              content,
              filename);
      out.accept(new ReportErrorsVisitor(context, "file"));
      JavaClassesFactory.endConstruction();
    } else {
      org.kframework.parser.concrete.KParser.ImportTblPgm(tbl.getAbsolutePath());
      String parsed =
          org.kframework.parser.concrete.KParser.ParseProgramString(content, startSymbol);
      Document doc = XmlLoader.getXMLDoc(parsed);

      XmlLoader.addFilename(doc.getFirstChild(), filename);
      XmlLoader.reportErrors(doc);
      FileUtil.save(context.kompiled.getAbsolutePath() + "/pgm.xml", parsed);
      JavaClassesFactory.startConstruction(context);
      out =
          JavaClassesFactory.getTerm(
              (Element) doc.getDocumentElement().getFirstChild().getNextSibling());
      JavaClassesFactory.endConstruction();
    }

    out = out.accept(new PriorityFilter(context));
    out = out.accept(new PreferAvoidFilter(context));
    out = out.accept(new AmbFilter(context));
    out = out.accept(new RemoveBrackets(context));

    if (kappize) out = out.accept(new FlattenSyntax(context));

    return out;
  }
Ejemplo n.º 5
0
 @Override
 public ASTNode complete(ASTNode node, ASTNode r) {
   r.copyAttributesFrom(node);
   return super.complete(node, r);
 }
Ejemplo n.º 6
0
  // execute krun in normal mode (i.e. not in debug mode)
  public static void normalExecution(
      Term KAST, String lang, RunProcess rp, CommandlineOptions cmd_options, Context context) {
    try {
      CommandLine cmd = cmd_options.getCommandLine();

      KRun krun = obtainKRun(context);
      KRunResult<?> result = null;
      // Set<String> varNames = null;
      Rule patternRule = null;
      RuleCompilerSteps steps;
      steps = new RuleCompilerSteps(K.definition, context);
      try {
        if (cmd.hasOption("pattern") || "search".equals(K.maude_cmd)) {
          org.kframework.parser.concrete.KParser.ImportTbl(K.compiled_def + "/def/Concrete.tbl");
          ASTNode pattern =
              DefinitionLoader.parsePattern(K.pattern, "Command line pattern", context);
          CollectVariablesVisitor vars = new CollectVariablesVisitor(context);
          pattern.accept(vars);
          // varNames = vars.getVars().keySet();

          try {
            pattern = steps.compile(new Rule((Sentence) pattern), null);
          } catch (CompilerStepDone e) {
            pattern = (ASTNode) e.getResult();
          }
          patternRule = new Rule((Sentence) pattern);
          if (GlobalSettings.verbose) sw.printIntermediate("Parsing search pattern");
        }

        if (K.do_search) {
          if ("search".equals(K.maude_cmd)) {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String buffer = "";
            // detect if the input comes from console or redirected
            // from a pipeline
            Console c = System.console();
            if (c == null && br.ready()) {
              try {
                buffer = br.readLine();
              } catch (IOException ioe) {
                ioe.printStackTrace();
              } finally {
                if (br != null) {
                  try {
                    br.close();
                  } catch (IOException e) {
                    e.printStackTrace();
                  }
                }
              }
            }
            Integer depth = null;
            Integer bound = null;
            if (cmd.hasOption("bound") && cmd.hasOption("depth")) {
              bound = Integer.parseInt(K.bound);
              depth = Integer.parseInt(K.depth);
            } else if (cmd.hasOption("bound")) {
              bound = Integer.parseInt(K.bound);
            } else if (cmd.hasOption("depth")) {
              depth = Integer.parseInt(K.depth);
            }
            if (K.do_testgen) {
              result =
                  krun.generate(
                      bound,
                      depth,
                      K.searchType,
                      patternRule,
                      makeConfiguration(KAST, buffer, rp, (K.term != null), context),
                      steps);
            } else {
              result =
                  krun.search(
                      bound,
                      depth,
                      K.searchType,
                      patternRule,
                      makeConfiguration(KAST, buffer, rp, (K.term != null), context),
                      steps);
            }

            if (GlobalSettings.verbose) sw.printTotal("Search total");
          } else {
            Error.report("For the search option you must specify that --maude-cmd=search");
          }
        } else if (K.model_checking.length() > 0) {
          // run kast for the formula to be verified
          File formulaFile = new File(K.model_checking);
          Term KAST1 = null;
          if (!formulaFile.exists()) {
            // Error.silentReport("\nThe specified argument does not exist as a file on the disc; it
            // may represent a direct formula: "
            // + K.model_checking);
            // assume that the specified argument is not a file and
            // maybe represents a formula
            KAST1 = rp.runParserOrDie("kast -e", K.model_checking, false, "LtlFormula", context);
          } else {
            // the specified argument represents a file
            KAST1 = rp.runParserOrDie("kast", K.model_checking, false, "LtlFormula", context);
          }

          result =
              krun.modelCheck(KAST1, makeConfiguration(KAST, null, rp, (K.term != null), context));

          if (GlobalSettings.verbose) sw.printTotal("Model checking total");
        } else if (K.prove.length() > 0) {
          File proofFile = new File(K.prove);
          if (!proofFile.exists()) {
            Error.report("Cannot find the file containing rules to prove");
          }
          String content = FileUtil.getFileContent(proofFile.getAbsoluteFile().toString());
          Definition parsed =
              DefinitionLoader.parseString(content, proofFile.getAbsolutePath(), context);
          Module mod = parsed.getSingletonModule();
          try {
            mod = new SpecificationCompilerSteps(context).compile(mod, null);
          } catch (CompilerStepDone e) {
            assert false : "dead code";
          }
          result = krun.prove(mod);
        } else if (cmd.hasOption("depth")) {
          int depth = Integer.parseInt(K.depth);
          result = krun.step(makeConfiguration(KAST, null, rp, (K.term != null), context), depth);

          if (GlobalSettings.verbose) sw.printTotal("Bounded execution total");
        } else {
          result = krun.run(makeConfiguration(KAST, null, rp, (K.term != null), context));

          if (GlobalSettings.verbose) sw.printTotal("Normal execution total");
        }

        if (cmd.hasOption("pattern") && !K.do_search) {
          Object krs = result.getResult();
          if (krs instanceof KRunState) {
            Term res = ((KRunState) krs).getRawResult();
            krun.setBackendOption("io", false);
            result = krun.search(null, null, K.searchType, patternRule, res, steps);
          } else {
            Error.report(
                "Pattern matching after execution is not supported by search\nand model checking");
          }
        }

      } catch (KRunExecutionException e) {
        rp.printError(e.getMessage(), lang, context);
        System.exit(1);
      } catch (TransformerException e) {
        e.report();
      } catch (UnsupportedBackendOptionException e) {
        Error.report("Backend \"" + K.backend + "\" does not support option " + e.getMessage());
      }

      if ("pretty".equals(K.output_mode)) {
        String output = result.toString();
        if (!cmd.hasOption("output")) {
          AnsiConsole.out.println(output);
        } else {
          writeStringToFile(new File(K.output), output);
        }
        // print search graph
        if ("search".equals(K.maude_cmd) && K.do_search && K.showSearchGraph) {
          System.out.println(K.lineSeparator + "The search graph is:" + K.lineSeparator);
          @SuppressWarnings("unchecked")
          KRunResult<SearchResults> searchResult = (KRunResult<SearchResults>) result;
          AnsiConsole.out.println(searchResult.getResult().getGraph());
          // offer the user the possibility to turn execution into
          // debug mode
          while (true) {
            System.out.print(K.lineSeparator + "Do you want to enter in debug mode? (y/n):");
            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
            String input = stdin.readLine();
            if (input == null) {
              K.debug = false;
              K.guidebug = false;
              System.out.println();
              break;
            }
            if (input.equals("y")) {
              K.debug = true;
              debugExecution(KAST, lang, searchResult, context);
            } else if (input.equals("n")) {
              K.debug = false;
              K.guidebug = false;
              break;
            } else {
              System.out.println("You should specify one of the possible answers:y or n");
            }
          }
        }
      } else if ("raw".equals(K.output_mode)) {
        String output = result.getRawOutput();
        ;
        if (!cmd.hasOption("output")) {
          System.out.println(output);
        } else {
          writeStringToFile(new File(K.output), output);
        }
      } else if ("none".equals(K.output_mode)) {
        System.out.print("");
      } else if ("binary".equals(K.output_mode)) {
        Object krs = result.getResult();
        if (krs instanceof KRunState) {
          Term res = ((KRunState) krs).getRawResult();

          if (!cmd.hasOption("output")) {
            Error.silentReport(
                "Did not specify an output file. Cannot print output-mode binary to\nstandard out. Saving to .k/krun/krun_output");
            BinaryLoader.save(K.krun_output, res);
          } else {
            BinaryLoader.save(K.output, res);
          }
        } else {
          Error.report("binary output mode is not supported by search and model\nchecking");
        }

      } else {
        Error.report(K.output_mode + " is not a valid value for output-mode option");
      }

      System.exit(0);
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(1);
    }
  }