|
1 | 1 | package org.biscuitsec.biscuit.token.builder.parser;
|
2 | 2 |
|
3 | 3 | import biscuit.format.schema.Schema;
|
| 4 | +import io.vavr.collection.Stream; |
4 | 5 | import org.biscuitsec.biscuit.crypto.PublicKey;
|
| 6 | +import org.biscuitsec.biscuit.datalog.SymbolTable; |
5 | 7 | import org.biscuitsec.biscuit.token.Policy;
|
6 | 8 | import io.vavr.Tuple2;
|
7 | 9 | import io.vavr.Tuple4;
|
|
10 | 12 |
|
11 | 13 | import java.time.OffsetDateTime;
|
12 | 14 | import java.time.format.DateTimeParseException;
|
13 |
| -import java.util.ArrayList; |
14 |
| -import java.util.List; |
15 |
| -import java.util.HashSet; |
| 15 | +import java.util.*; |
16 | 16 | import java.util.function.Function;
|
17 | 17 |
|
18 | 18 | public class Parser {
|
| 19 | + /** |
| 20 | + * Takes a datalog string with <code>\n</code> as datalog line separator. It tries to parse |
| 21 | + * each line using fact, rule, check and scope sequentially. |
| 22 | + * |
| 23 | + * If one succeeds it returns Right(Block) |
| 24 | + * else it returns a Map[lineNumber, List[Error]] |
| 25 | + * |
| 26 | + * @param index block index |
| 27 | + * @param baseSymbols symbols table |
| 28 | + * @param s datalog string to parse |
| 29 | + * @return Either<Map<Integer, List<Error>>, Block> |
| 30 | + */ |
| 31 | + public static Either<Map<Integer, List<Error>>, Block> datalog(long index, SymbolTable baseSymbols, String s) { |
| 32 | + Block blockBuilder = new Block(index, baseSymbols); |
| 33 | + Map<Integer, List<Error>> errors = new HashMap<>(); |
| 34 | + |
| 35 | + Stream.of(s.split("\n")).zipWithIndex().forEach(indexedLine -> { |
| 36 | + Integer lineNumber = indexedLine._2; |
| 37 | + String codeLine = indexedLine._1; |
| 38 | + List<Error> lineErrors = new ArrayList<>(); |
| 39 | + |
| 40 | + fact(codeLine).bimap(lineErrors::add, r -> r._2).map(blockBuilder::add_fact); |
| 41 | + rule(codeLine).bimap(lineErrors::add, r -> r._2).map(blockBuilder::add_rule); |
| 42 | + check(codeLine).bimap(lineErrors::add, r -> r._2).map(blockBuilder::add_check); |
| 43 | + scope(codeLine).bimap(lineErrors::add, r -> r._2).map(blockBuilder::add_scope); |
| 44 | + |
| 45 | + if (lineErrors.size() > 3) { |
| 46 | + errors.put(lineNumber, lineErrors); |
| 47 | + } |
| 48 | + }); |
| 49 | + |
| 50 | + if (!errors.isEmpty()) { |
| 51 | + return Either.left(errors); |
| 52 | + } |
| 53 | + |
| 54 | + return Either.right(blockBuilder); |
| 55 | + } |
| 56 | + |
19 | 57 | public static Either<Error, Tuple2<String, Fact>> fact(String s) {
|
20 | 58 | Either<Error, Tuple2<String, Predicate>> res = fact_predicate(s);
|
21 | 59 | if (res.isLeft()) {
|
|
0 commit comments