Search in sources :

Example 11 with Str

use of suite.node.Str in project suite by stupidsing.

the class P0CrudeScript method parse.

public Funp parse(String in) {
    // "{ return 1 + 2 * 3; }"
    var ebnf = ex(() -> new Ebnf(new FileReader("src/main/ebnf/crude-script.ebnf")));
    var ast = ebnf.parse("crude-script", in);
    var node = new Object() {

        private Node node(Ast ast) {
            var entity = ast.entity;
            var children = ast.children;
            var atom = Atom.of(entity);
            Node node;
            if (entity.startsWith("<"))
                node = new Str(in.substring(ast.start, ast.end));
            else
                node = Read.from(children).reverse().<Node>fold(Atom.NIL, (n, c) -> Tree.ofAnd(node(c), n));
            return TreeTuple.of(atom, node);
        }
    }.node(ast);
    return new Object() {

        private Funp crudeScript(Node node) {
            return new // 
            SwitchNode<Funp>(// 
            node).match("crude-script (.0,)", a -> {
                return stmt(a);
            }).nonNullResult();
        }

        private Funp stmt(Node node) {
            return new // 
            SwitchNode<Funp>(// 
            node).match("statement (expression (.0,),)", a -> {
                return expr(a);
            }).match("statement (statement-return (.0,),)", a -> {
                return expr(a);
            }).match("statement1 (.0,)", a -> {
                return stmt(a);
            }).match("statement-block (statement-let (bind (<IDENTIFIER> .0,), .1,), .2)", (a, b, c) -> {
                return FunpDefine.of(Str.str(a), expr(b), stmt(c), Fdt.L_MONO);
            }).match("statement-block (.0,)", a -> {
                return stmt(a);
            }).match("statement-for (.0, .1, .2, .3,)", (a, b, c, d) -> {
                return expr(a);
            }).match("statement-if (.0, .1, .2,)", (a, b, c) -> {
                return FunpIf.of(expr(a), stmt(b), stmt(c));
            }).match("statement-while (.0, .1,)", (a, b) -> {
                return expr(b);
            }).nonNullResult();
        }

        private Funp expr(Node node) {
            return new // 
            SwitchNode<Funp>(// 
            node).match("<IDENTIFIER> .0", s -> {
                return FunpVariable.of(Str.str(s));
            }).match("<INTEGER_LITERAL> .0", s -> {
                return FunpNumber.ofNumber(Integer.valueOf(Str.str(s)));
            }).match("<STRING_LITERAL> .0", s -> {
                return fail();
            }).match("constant (.0,)", a -> {
                return expr(a);
            }).match("expression (.0,)", a -> {
                return expr(a);
            }).match("expression-add (.0, .1)", (a, b) -> {
                return Tree.read(b).fold(expr(a), (f, c) -> FunpTree.of(FunpOp.PLUS__, f, expr(c)));
            }).match("expression-and (.0,)", a -> {
                return expr(a);
            }).match("expression-as (.0,)", a -> {
                return expr(a);
            }).match("expression-assign (.0, .1)", (a, b) -> {
                return expr(a);
            }).matchArray("expression-array .0", m -> {
                return FunpArray.of(Read.from(m).map(this::expr).toList());
            }).match("expression-bool-and (.0, .1)", (a, b) -> {
                return Tree.read(b).fold(expr(a), (f, c) -> FunpTree.of(FunpOp.BIGAND, f, expr(c)));
            }).match("expression-bool-not (.0,)", a -> {
                return expr(a);
            }).match("expression-bool-or (.0, .1)", (a, b) -> {
                return Tree.read(b).fold(expr(a), (f, c) -> FunpTree.of(FunpOp.BIGOR_, f, expr(c)));
            }).match("expression-compare (.0,)", a -> {
                return expr(a);
            }).match("expression-dict .0", a -> {
                var list = // 
                Tree.read(// 
                a).chunk(// 
                2).map(// 
                o -> o.toFixie().map((k, v) -> Pair.of(Str.str(k), expr(v)))).toList();
                return FunpStruct.of(list);
            }).match("expression-div (.0, .1)", (a, b) -> {
                return // 
                Tree.read(// 
                b).chunk(// 
                2).fold(expr(a), (f, o) -> o.toFixie().map((op, d) -> {
                    return new // 
                    SwitchNode<Funp>(// 
                    op).matchArray("'/'", m_ -> {
                        return FunpTree.of(FunpOp.DIVIDE, f, expr(d));
                    }).matchArray("'%'", m_ -> {
                        return FunpTree.of(FunpOp.MODULO, f, expr(d));
                    }).nonNullResult();
                }));
            }).match("expression-invoke (.0, .1)", (a, b) -> {
                return Tree.read(b).fold(expr(a), (f, c) -> FunpApply.of(f, expr(c)));
            }).match("expression-mul (.0, .1)", (a, b) -> {
                return Tree.read(b).fold(expr(a), (f, c) -> FunpTree.of(FunpOp.MULT__, f, expr(c)));
            }).match("expression-not (.0,)", a -> {
                return expr(a);
            }).match("expression-lambda (bind (<IDENTIFIER> (.0,),), expression (.1,),)", (a, b) -> {
                return FunpLambda.of(Str.str(a), expr(b));
            }).match("expression-lambda (bind (<IDENTIFIER> (.0,),), statement-block (.1),)", (a, b) -> {
                return FunpLambda.of(Str.str(a), stmt(b));
            }).match("expression-obj (.0,)", a -> {
                return expr(a);
            }).match("expression-or (.0,)", a -> {
                return expr(a);
            }).match("expression-pp .0", a -> {
                var pat0 = Suite.pattern("op-inc-dec ('++' (),)");
                var pat1 = Suite.pattern("op-inc-dec ('--' (),)");
                var list = Tree.read(a).toList();
                Obj_Int<Node> f = op -> pat0.match(op) != null ? 1 : pat1.match(op) != null ? -1 : 0;
                int s = 0, e = list.size() - 1, c;
                int pre_ = 0, post = 0;
                while ((c = f.apply(list.get(s))) != 0) {
                    pre_ += c;
                    s++;
                }
                while ((c = f.apply(list.get(e))) != 0) {
                    post += c;
                    e--;
                }
                var e0 = expr(list.get(s));
                var ref0 = FunpReference.of(e0);
                var e1 = pre_ == 0 ? e0 : FunpDoAssignRef.of(ref0, FunpTree.of(FunpOp.PLUS__, e0, FunpNumber.ofNumber(pre_)), e0);
                var e2 = post == 0 ? e1 : Fail.<Funp>fail();
                return s == e ? e2 : fail();
            }).match("expression-prop (.0, .1)", (a, b) -> {
                return // 
                Tree.read(// 
                b).chunk(// 
                2).fold(expr(a), (f, o) -> o.toFixie().map((k, v) -> {
                    return new // 
                    SwitchNode<Funp>(// 
                    k).matchArray("'.'", m_ -> {
                        return FunpField.of(FunpReference.of(f), Str.str(v));
                    }).matchArray("'['", m_ -> {
                        return FunpIndex.of(FunpReference.of(f), expr(v));
                    }).matchArray("'('", m_ -> {
                        return FunpApply.of(expr(v), f);
                    }).nonNullResult();
                }));
            }).match("expression-shift (.0,)", a -> {
                return expr(a);
            }).match("expression-sub (.0,)", a -> {
                return expr(a);
            }).match("expression-tuple .0", a -> {
                var list = new ArrayList<Pair<String, Funp>>();
                var i = 0;
                for (var child : Tree.read(a)) list.add(Pair.of("t" + i++, expr(child)));
                return FunpStruct.of(list);
            }).match("expression-xor (.0,)", a -> {
                return expr(a);
            }).nonNullResult();
        }
    }.crudeScript(node);
}
Also used : FunpDoAssignRef(suite.funp.P0.FunpDoAssignRef) Fdt(suite.funp.P0.Fdt) Fail.fail(primal.statics.Fail.fail) Ast(suite.ebnf.Ebnf.Ast) FunpArray(suite.funp.P0.FunpArray) FunpDefine(suite.funp.P0.FunpDefine) FunpIndex(suite.funp.P0.FunpIndex) FunpLambda(suite.funp.P0.FunpLambda) FunpReference(suite.funp.P0.FunpReference) ArrayList(java.util.ArrayList) Funp_(suite.funp.Funp_) Node(suite.node.Node) FunpApply(suite.funp.P0.FunpApply) FunpIf(suite.funp.P0.FunpIf) Ebnf(suite.ebnf.Ebnf) Obj_Int(primal.primitive.IntPrim.Obj_Int) Fail(primal.statics.Fail) FunpOp(suite.funp.FunpOp) Pair(primal.adt.Pair) Suite(suite.Suite) FunpTree(suite.funp.P0.FunpTree) FunpField(suite.funp.P0.FunpField) Read(primal.MoreVerbs.Read) Tree(suite.node.Tree) Funp(suite.funp.Funp_.Funp) Rethrow.ex(primal.statics.Rethrow.ex) FunpNumber(suite.funp.P0.FunpNumber) Atom(suite.node.Atom) SwitchNode(suite.node.io.SwitchNode) FileReader(java.io.FileReader) FunpStruct(suite.funp.P0.FunpStruct) FunpVariable(suite.funp.P0.FunpVariable) TreeTuple(suite.node.tree.TreeTuple) Str(suite.node.Str) Ast(suite.ebnf.Ebnf.Ast) Node(suite.node.Node) SwitchNode(suite.node.io.SwitchNode) SwitchNode(suite.node.io.SwitchNode) Obj_Int(primal.primitive.IntPrim.Obj_Int) Str(suite.node.Str) Funp(suite.funp.Funp_.Funp) Ebnf(suite.ebnf.Ebnf) FileReader(java.io.FileReader) Pair(primal.adt.Pair)

Example 12 with Str

use of suite.node.Str in project suite by stupidsing.

the class ServerMain method handler.

private Handler handler() {
    BiPredicate<String, String> authenticate = (username, password) -> // 
    Defaults.secrets().prove(Suite.substitute("auth .0 .1", new Str(username), new Str(password)));
    Fun2<String, String, List<String>> authenticateRoles = (username, password) -> {
        return authenticate.test(username, password) ? List.of("role") : null;
    };
    var sseHeaders = new Header(// 
    PerMap.<String, PerList<String>>empty().put("Cache-Control", // 
    PerList.of("no-cache")).put("Content-Type", PerList.of("text/event-stream")));
    Handler handlerDump = request -> Response.of(Pull.from(// 
    "" + // 
    "<html>" + "<br/>method = " + // 
    request.method + "<br/>server = " + // 
    request.server + "<br/>paths = " + // 
    request.paths + "<br/>attrs = " + // 
    HttpHeaderUtil.getAttrs(request.query) + "<br/>headers = " + // 
    request.headers + "</html>"));
    Handler handlerSse = request -> Response.ofWriter(Http.S200, sseHeaders, write -> {
        new Object() {

            private int i = 8;

            private void dispatch() {
                sleep.sink2(1000l, () -> {
                    if (0 < i--) {
                        var event = "event: number\ndata: { \"i\": " + i + " }\n\n";
                        write.f(Bytes.of(event.getBytes(Utf8.charset)));
                        dispatch();
                    } else
                        write.f(null);
                });
            }
        }.dispatch();
    });
    Handler handlerStatus = request -> {
        var cfg = new TradeCfgImpl();
        var summarize = Summarize.of(cfg);
        var sbs = summarize.summarize(trade -> trade.strategy);
        return Response.of(Pull.from("<pre>" + sbs.log + new TreeMap<>(sbs.pnlByKey) + "</pre>"));
    };
    var hh = new HttpHandle();
    var hhsa = new HttpHandleSessionAuth();
    var hhta = new HttpHandleTokenAuth();
    return hh.routeByPath(// 
    PerMap.<String, Handler>empty().put("api", // 
    hhta.applyFilter("role", hh.serveText("in good shape"))).put("hello", // 
    hh.serveText("hello world")).put("html", // 
    hh.serveDir(Paths.get(FileUtil.suiteDir() + "/src/main/html"))).put("path", // 
    hh.serveDir(Tmp.root)).put("site", // 
    hhsa.getHandler(authenticate, handlerDump)).put("sse", // 
    handlerSse).put("status", // 
    handlerStatus).put("token", hh.routeByMethod(// 
    PerMap.<String, Handler>empty().put("PATCH", // 
    hhta.refreshToken(authenticateRoles)).put("POST", hhta.getToken(authenticateRoles)))));
}
Also used : Schedule(suite.os.Schedule) Sink2(primal.fp.Funs2.Sink2) LocalDateTime(java.time.LocalDateTime) Scheduler(suite.os.Scheduler) RunUtil(suite.util.RunUtil) ArrayList(java.util.ArrayList) Defaults(suite.cfg.Defaults) BiPredicate(java.util.function.BiPredicate) Http(suite.http.Http) Response(suite.http.Http.Response) SmtpServer(suite.smtp.SmtpServer) Utf8(primal.Nouns.Utf8) LocalTime(java.time.LocalTime) FileUtil(suite.os.FileUtil) Pull(primal.MoreVerbs.Pull) HttpServe(suite.http.HttpServe) Sleep(primal.Verbs.Sleep) Handler(suite.http.Http.Handler) TelegramBotMain(suite.sample.TelegramBotMain) PerMap(primal.persistent.PerMap) TradeCfgImpl(suite.trade.data.TradeCfgImpl) Files(java.nio.file.Files) HttpNio(suite.http.HttpNio) HttpHandleSessionAuth(suite.http.HttpHandleSessionAuth) Summarize(suite.trade.analysis.Summarize) HttpHandle(suite.http.HttpHandle) Start(primal.Verbs.Start) HttpHeaderUtil(suite.http.HttpHeaderUtil) Header(suite.http.Http.Header) Bytes(primal.primitive.adt.Bytes) List(java.util.List) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) HttpHandleTokenAuth(suite.http.HttpHandleTokenAuth) Fun2(primal.fp.Funs2.Fun2) PerList(primal.persistent.PerList) Str(suite.node.Str) Tmp(primal.Nouns.Tmp) HttpHandle(suite.http.HttpHandle) TradeCfgImpl(suite.trade.data.TradeCfgImpl) Handler(suite.http.Http.Handler) Str(suite.node.Str) HttpHandleSessionAuth(suite.http.HttpHandleSessionAuth) Header(suite.http.Http.Header) ArrayList(java.util.ArrayList) List(java.util.List) PerList(primal.persistent.PerList) HttpHandleTokenAuth(suite.http.HttpHandleTokenAuth)

Aggregations

Str (suite.node.Str)12 Node (suite.node.Node)8 ArrayList (java.util.ArrayList)5 Dict (suite.node.Dict)5 Atom (suite.node.Atom)4 Reference (suite.node.Reference)4 Tree (suite.node.Tree)4 List (java.util.List)3 HashSet (java.util.HashSet)2 Suite (suite.Suite)2 Inspect (suite.inspect.Inspect)2 Chars (suite.primitive.Chars)2 Fun (suite.util.FunUtil.Fun)2 FileReader (java.io.FileReader)1 Array (java.lang.reflect.Array)1 Field (java.lang.reflect.Field)1 ParameterizedType (java.lang.reflect.ParameterizedType)1 Type (java.lang.reflect.Type)1 Files (java.nio.file.Files)1 Paths (java.nio.file.Paths)1