rego

    Pure MoonBit Open Policy Agent (OPA) Rego v1 syntax, AST and policy engine

    rego
    opa
    policy
    parser
    cst
    ast
    Download zip
    Author
    Version
    0.5.0
    License
    Apache-2.0
    Last updated
    2 hours ago
    Downloads
    16

    #moonrockz/rego

    Pure MoonBit Open Policy Agent (OPA) Rego v1 policy engine: lexer, lossless error-recovering CST, immutable SyntaxCursor, # METADATA annotation parser, smart-constructed AST, exact arbitrary-precision Value model, extensible BuiltinRegistry with Tier-1 and Tier-2 pure standard library built-ins (regex.*, glob.*, semver.*, units.*, time.*, base64.*, base64url.*, hex.*, urlquery.*, uri.*, uuid.*, rand.intn, strings.render_template, rego.parse_module), HIR compiler with dependency scheduler and cycle/safety checks, explicit-stack Plan VM with deterministic StepBudget, Clock and RandomSeed injection, and a pure run_tests unit test runner. Zero I/O; builds and tests on wasm, wasm-gc, js and native.

    #Compile and evaluate a Rego v1 policy

    ///|
    test "compile and evaluate a Rego v1 policy with template strings" {
    let src =
    #|package okf.decisions
    #|
    #|# METADATA
    #|# title: Decision needs owner
    #|deny contains msg if {
    #| some doc in input.documents
    #| doc.type == "Decision"
    #| not doc.fields.owner
    #| msg := $"decision {doc.path} has no owner"
    #|}
    #|
    let policy = @rego.compile_sources([src])
    let input = @value.Value::from_json_string(
    "{\"documents\": [{\"path\": \"docs/adr-1.md\", \"type\": \"Decision\", \"fields\": {}}]}",
    )
    let res = @rego.eval_query_source(
    policy,
    "data.okf.decisions.deny",
    input=Some(input),
    )
    assert_eq(
    res.first_value(),
    Some(
    @value.Value::set([
    @value.Value::String("decision docs/adr-1.md has no owner"),
    ]),
    ),
    )
    }

    #Register a custom pure built-in and enforce a StepBudget

    ///|
    test "register a custom built-in and evaluate with StepBudget" {
    let custom_reg = @rego.tier1_builtins().with_builtin(
    @builtins.BuiltinName("custom.double"),
    @builtins.BuiltinArity::fixed(1),
    (args, _) => {
    match args[0] {
    Number(d) => Ok(Some(Number(d.mul(@value.Decimal::from_int(2)))))
    _ => Ok(None)
    }
    },
    )
    let policy = @rego.compile_sources(
    ["package demo\nans := custom.double(21)\n"],
    builtins=custom_reg,
    )
    let opts = @rego.default_options()
    .with_builtins(custom_reg)
    .with_step_budget(@rego.step_budget(1_000))
    let ans = @rego.eval_rule(policy, ["demo", "ans"], options=opts)
    assert_eq(ans, Some(@value.Value::int(42)))
    }

    #Run pure Rego test_* suites with Tier-2 built-ins and injected Clock

    ///|
    test "run pure Rego policy tests with Tier-2 built-ins and deterministic Clock" {
    let src =
    #|package okf.checks_test
    #|
    #|test_tier2_helpers if {
    #| semver.compare("1.10.0", "1.2.0") > 0
    #| regex.match(`^ADR-[0-9]{4}$`, "ADR-0042")
    #| glob.match("docs/**/*.{md,yaml}", ["/"], "docs/adr/0042.md")
    #| units.parse_bytes("2KiB") == 2048
    #| time.now_ns() == 1700000000000000000
    #|}
    #|
    #|todo_test_future_rule if {
    #| false
    #|}
    #|
    let policy = @rego.compile_sources([src])
    let opts = @rego.default_options().with_clock(
    @builtins.Clock::from_unix_nanos(1700000000000000000L),
    )
    let report = @rego.run_tests(policy, options=opts)
    assert_true(report.all_passed())
    assert_eq(report.passed_count(), 1)
    assert_eq(report.skipped_count(), 1)
    }

    #Parse a Rego v1 module and inspect # METADATA

    ///|
    test "parse a Rego v1 module with METADATA and lossless CST" {
    let src =
    #|package okf.decisions
    #|
    #|# METADATA
    #|# title: Decision needs owner
    #|deny contains msg if {
    #| some doc in input.documents
    #| not doc.fields.owner
    #| msg := $"decision {doc.path} has no owner"
    #|}
    #|
    let cst = @rego.parse_module_cst(src)
    assert_false(cst.has_errors())
    assert_eq(cst.to_source(), src)

    let mod = @rego.parse_module(src)
    assert_eq(mod.package_path().to_string(), "okf.decisions")
    assert_eq(mod.rules().length(), 1)
    assert_eq(
    mod.rules()[0].annotations()[0].title(),
    Some("Decision needs owner"),
    )
    }

    ///|
    test "walk a parsed CST with SyntaxCursor" {
    let cst = @rego.parse_module_cst("package demo\nallow := true\n")
    let root = @syntax.SyntaxCursor::root(cst.root())
    guard root.first_child() is Some(pkg) else { fail("missing package") }
    assert_eq(pkg.node().kind(), @syntax.PackageDecl)
    guard pkg.next_sibling() is Some(rule) else { fail("missing rule") }
    assert_eq(rule.node().kind(), @syntax.Rule)
    }

    BindingSet

    Re-exported single query solution row.

    BuiltinArity

    Re-exported validated built-in arity.

    BuiltinContext

    Re-exported pure built-in execution context.

    BuiltinError

    Re-exported built-in error type.

    BuiltinName

    Re-exported validated built-in name.

    BuiltinRegistry

    Re-exported immutable built-in registry and signature types.

    BuiltinSignature

    Re-exported validated built-in signature.

    Clock

    Re-exported immutable injected deterministic clock type.

    CompileError

    Re-exported compiler error type.

    CompiledPolicy

    Re-exported compiled Rego v1 policy.

    CompiledQuery

    Re-exported compiled Rego v1 query.

    Decimal

    Re-exported exact arbitrary-precision decimal number type.

    EngineError

    Re-exported engine configuration error type.

    EngineOptions

    Re-exported VM evaluation options.

    EvalError

    Re-exported VM evaluation error type.

    EvalResult

    Re-exported query evaluation result set.

    RandomSeed

    Re-exported immutable injected deterministic random seed type.

    RegoObject

    Re-exported immutable Rego object type.

    RegoSet

    Re-exported immutable Rego set type.

    StepBudget

    Re-exported validated positive VM step budget.

    TestCaseResult

    Re-exported immutable single Rego test case result.

    TestFilter

    Re-exported pure Rego test discovery filter.

    TestReport

    Re-exported immutable Rego test suite report.

    TestStatus

    Re-exported outcome status of one Rego test rule.

    UnixNanos

    Re-exported immutable Unix nanosecond timestamp type.

    Value

    Re-exported immutable Rego runtime value types.

    PolicyError

    Combined error raised by convenience end-to-end source compilation and evaluation helpers.
    impl Show for PolicyError

    compile_query

    Compiles a standalone Rego v1 AST query against a CompiledPolicy.

    compile_sources

    Parses, lowers, and compiles one or more Rego v1 source strings into an immutable CompiledPolicy.

    default_options

    Returns default EngineOptions (StepBudget::default(), standard pure built-ins, epoch Clock, and default deterministic RandomSeed).

    eval_query_source

    Parses, compiles, and evaluates a Rego v1 query string against policy.

    eval_rule

    Directly evaluates a data.<path...> rule or package document in policy. path holds arbitrary data object keys (ArrayView[String]), which have no character-set restrictions in Rego or JSON.

    parse_module

    Parses and lowers a strict Rego v1 module into an immutable AST.

    parse_module_cst

    fn parse_module_cst(source : String) ->
    ParseResult

    Parses a strict Rego v1 module into a lossless, error-recovering CST and any syntax diagnostics.

    parse_query

    Parses and lowers a standalone Rego v1 query into an immutable AST.

    parse_query_cst

    fn parse_query_cst(source : String) ->
    ParseResult

    Parses a standalone Rego v1 query into a lossless, error-recovering CST and any syntax diagnostics.

    run_tests

    Discovers and runs test_* and todo_test_* rules in policy with zero I/O, giving each test its own isolated StepBudget.

    standard_builtins

    Returns the full pure standard library built-in registry (Tier-1 + Tier-2) matching OPA v1.23.0.

    step_budget

    Constructs a validated positive StepBudget.

    tier1_builtins

    Returns the minimal Tier-1 pure built-in registry matching OPA v1.23.0.

    Source Files