/** * Get the source of the string to parse. This method is undefined if it is called before calling * {@link #stringToParse()}. * @return A textual description of the source of the string to parse. */ public Source source() { if (expression != null) { return Source.apply("<command line: -e>"); } else { return Source.apply(files.get().resolveWorkingDirectory(parameters.get(0)).getAbsolutePath()); } }
/** * Tries to parse a term from the given file, as either binary or textual kore. * * We don't seem to have good error returns, nor access to the KExceptionGroup * chosen for a KEMException, so it's hard to give a good message when neither * parser worked, or figure out which might have been closer to parsing the file. */ private static K loadFile(File file) throws IOException { try { try { return KoreParser.parse(FileUtils.readFileToString(file), new Source(file.getName())); } catch (KEMException e) { FileChannel input = FileChannel.open(file.toPath(), StandardOpenOption.READ); return BinaryParser.parse(input.map(FileChannel.MapMode.READ_ONLY, 0, input.size())); } } catch (KEMException e) { throw new IOException("Parse Error", e); } }
@Override protected int run() { List<org.kframework.kil.Module> modules = new ArrayList<>(); Source source = Source.apply(options.mainDefinitionFile(files).getAbsolutePath()); File currentDirectory = options.mainDefinitionFile(files).getParentFile(); List<File> lookupDirectories = ListUtils.union(options.includes.stream() lookupDirectories, requiredFiles));; Set<File> allFiles = modules.stream().map(m -> new File(m.getSource().source())).collect(Collectors.toSet()); System.out.println(files.resolveWorkingDirectory(".").toURI().relativize(files.resolveKompiled("timestamp").toURI()).getPath() + " : \\"); for (File file : allFiles) {
private void printSummaryBox(Rule rule, List<ConstrainedTerm> proofResults, int successPaths, int step) { if (proofResults.isEmpty()) { System.err.format("\nSPEC PROVED: %s %s\n==================================\nExecution paths: %d\n", new File(rule.getSource().source()), rule.getLocation(), successPaths); } else { System.err.format("\nSPEC FAILED: %s %s\n==================================\n" + "Success execution paths: %d\nFailed execution paths: %d\n", new File(rule.getSource().source()), rule.getLocation(), successPaths, proofResults.size()); } System.err.format("Longest path: %d steps\n", step); global.profiler.printResult(); }
private static String getSourceLocation(Rule rule) { String s; // Return null, if location information is not available. Source source = rule.getSource(); s = source.toString() + ":" + rule.getLocation().toString(); return s; } }
private Stream<? extends K> performParse(Map<String, ParsedSentence> cache, ParseInModule parser, Scanner scanner, Bubble b) { int startLine = b.att().get("contentStartLine", Integer.class); int startColumn = b.att().get("contentStartColumn", Integer.class); Source source = b.att().get(Source.class); Tuple2<Either<java.util.Set<ParseFailedException>, K>, java.util.Set<ParseFailedException>> result; if (cache.containsKey(b.contents())) { ParsedSentence parse = cache.get(b.contents()); Optional<Source> cacheSource = parse.getParse().source(); //Cache might contain content from an identical file but another source path. //The content will have wrong Source attribute and must be invalidated. if (cacheSource.isPresent() && cacheSource.get().equals(source)) { cachedBubbles.getAndIncrement(); kem.addAllKException(parse.getWarnings().stream().map(e -> e.getKException()).collect(Collectors.toList())); return Stream.of(parse.getParse()); } } result = parser.parseString(b.contents(), START_SYMBOL, scanner, source, startLine, startColumn, !b.att().contains("macro") && !b.att().contains("alias")); parsedBubbles.getAndIncrement(); kem.addAllKException(result._2().stream().map(e -> e.getKException()).collect(Collectors.toList())); if (result._1().isRight()) { KApply k = (KApply) new TreeNodesToKORE(Outer::parseSort, isStrict).down(result._1().right().get()); k = KApply(k.klabel(), k.klist(), k.att().addAll(b.att().remove("contentStartLine").remove("contentStartColumn").remove(Source.class).remove(Location.class))); cache.put(b.contents(), new ParsedSentence(k, new HashSet<>(result._2()))); return Stream.of(k); } else { errors.addAll(result._1().left().get()); return Stream.empty(); } } }
public static void appendRuleAndSource(Rule rule, Appendable out) { File source = rule.source().isPresent() ? new File(rule.getSource().source()) : null; Formatter formatter = new Formatter(out); if (sourceShortEnough(rule)) { formatter.format("%s\n", loadSource(rule)); } else if (rule.source().isPresent()) { formatter.format("rule too long...\n"); } else { formatter.format("Rule with no source. toString() format:\n%s\n", rule.toString()); } formatter.format("\tSource: %s %s\n\n", source, rule.getLocation()); } }
continue; if (rule.getSource().toString().contains(options.auditingFile) && rule.getLocation().startLine() == options.auditingLine) { matchedRules.add(rule);
/** * Parses the text to create a {@link Definition} object. */ public static org.kframework.definition.Definition from(String definitionText, String mainModuleName) { return from(definitionText, mainModuleName, Source.apply("generated")); }
private static String loadSource(Rule rule) { if (!cache.containsKey(rule)) { if (rule.getSource() != null && rule.getLocation() != null) { cache.putIfAbsent(rule, FileUtil.loadFragment(new File(rule.getSource().source()), rule.getLocation())); } } return cache.get(rule); }
@Test(expected = ParseFailedException.class) public void testNoKLabel() throws Exception { throwFirstLeftException(TermCons.apply(ConsPStack.from(Arrays.asList(bar, foo)), noKLabelProduction, new Location(0, 0, 0, 0), new Source(""))); }
private static String getSourceLocation(Term term) { String s = null; // Return null, if location information is not available. Term t = term.getCellContentsByName("<k>").get(0); if (t instanceof KSequence && ((KSequence) t).concreteSize() > 0) { t = ((KSequence) t).get(0); } if (t instanceof KItem) { Source source = t.getSource(); s = source.toString() + ":" + t.getLocation().toString(); } return s; }
public static K parseWithFile(String theTextToParse, String mainModule, Sort startSymbol, File definitionFile) { String definitionText; try { definitionText = FileUtils.readFileToString(definitionFile); } catch (IOException e) { throw new RuntimeException(e); } return parseWithString(theTextToParse, mainModule, startSymbol, Source.apply(definitionFile.getAbsolutePath()), definitionText); }
public K gen(Rule r, K body) { if (!cover || !r.att().getOptional(Source.class).isPresent()) { return body; } K left = RewriteToTop.toLeft(body); K right = RewriteToTop.toRight(body); String file = r.att().get(Source.class).source(); if (file.startsWith(JarInfo.getKBase())) { return body; } int line = r.att().get(Location.class).startLine(); int col = r.att().get(Location.class).startColumn(); String loc = file + ":" + line + ":" + col; String id = r.att().get("UNIQUE_ID"); allRulesFile.print(id); allRulesFile.print(" "); allRulesFile.println(loc); if (r.att().contains("macro") || r.att().contains("alias")) { //handled by macro expander return body; } return KRewrite(left, KSequence(KApply(KLabel("#logToFile"), KToken(StringUtil.enquoteKString(files.resolveKompiled("coverage.txt").getAbsolutePath()), Sorts.String()), KToken(StringUtil.enquoteKString(id + '\n'), Sorts.String())), right)); }
private K unparseThenParse(K origTerm, OutputModes outputMode) { byte[] unparsed = new KPrint().serialize(origTerm, outputMode); switch (outputMode) { case JSON: return JsonParser.parse(unparsed); case BINARY: return BinaryParser.parse(unparsed); case KAST: return KoreParser.parse(bytes2String(unparsed), new Source("KPrintTest")); default: return new KToken("###", Sort("UnsupportedOutputMode")); } }
/** * Parses a string with a particular start symbol/sort. * * @param startSymbol the start symbol/sort * @param toParse the String to parse * @return a pair: the left projection is a parsed string as a K, if successful; * the right projection is the set of issues encountered while parsing */ public Tuple2<Option<K>, Set<Warning>> apply(Sort startSymbol, String toParse) { return apply(startSymbol, toParse, Source.apply("generated")); }
private void parseTerm(String term, String sort, K expected, int expectWarnings) { String source = "AddEmpytListsTest." + testName.getMethodName(); final Tuple2<Either<Set<ParseFailedException>, K>, Set<ParseFailedException>> parseResult = parser.parseString(term, Sort(sort), new Source(source)); if (parseResult._1().isLeft()) { Assert.assertTrue("Unexpected parse errors" + parseResult._1().left().get(), false); } K actual = new TreeNodesToKORE(Outer::parseSort, false).down(parseResult._1().right().get()); Assert.assertEquals(expected, actual); if (parseResult._2().size() != expectWarnings) { Assert.assertTrue("Unexpected parse warnings" + parseResult._2(), false); } }
/** * Parses the text to create a {@link Definition} object. * The main module of the definition will be last module defined in the text file. */ public static org.kframework.definition.Definition from(String definitionText) { Pattern pattern = Pattern.compile("(?:^|\\s)module ([A-Z][A-Z\\-]*)"); Matcher m = pattern.matcher(definitionText); if(!m.find()) { throw new RuntimeException("Could not find any module in the definition"); } String nameOfLastModule = m.group(m.groupCount()); return from(definitionText, nameOfLastModule, Source.apply("generated")); }
public Parser(String input, Scanner scanner) { s = new ParseState(input, scanner, Source.apply("<unknown>"), 1, 1); }
private void addOpaqueKLabels(Set<KLabel> klabels) { if (options.klabels == null) return; File definitionFile = files.resolveWorkingDirectory(options.klabels).getAbsoluteFile(); List<File> lookupDirectories = kompileOptions.outerParsing.includes.stream().map(files::resolveWorkingDirectory).collect(Collectors.toList()); lookupDirectories.add(Kompile.BUILTIN_DIRECTORY); java.util.Set<Module> mods = new ParserUtils(files::resolveWorkingDirectory, kem, globalOptions).loadModules( new HashSet<>(), "require " + StringUtil.enquoteCString(definitionFile.getPath()), Source.apply(definitionFile.getAbsolutePath()), definitionFile.getParentFile(), lookupDirectories, new HashSet<>(), false); mods.stream().forEach(m -> klabels.addAll(mutable(m.definedKLabels()))); }