Table of Contents

Class Interpreter

Namespace
Rego
Assembly
Rego.dll

Rego interpreter instance. This class provides methods to load modules, data, and input, execute queries, and manage bundles.

public class Interpreter
Inheritance
Interpreter
Inherited Members

Examples

You can use a query alone, without input or data:

using Rego;
Interpreter rego = new();
Console.WriteLine(rego.Query("x=5;y=x + (2 - 4 * 0.25) * -3 + 7.4;2 * 5"));
// {"expressions":[true, true, 10], "bindings":{"x":5, "y":9.4}}

More typically, a policy will involve base documents (static data) and virtual documents (Rego modules):

using System.Collections;
using Rego;
Interpreter rego = new();
var data0 = new Dictionary<string, object>{
   {"one", new Dictionary<string, object>{
       {"bar", "Foo"},
       {"baz", 5},
       {"be", true},
       {"bop", 23.4}}},
   {"two", new Dictionary<string, object>{
       {"bar", "Bar"},
       {"baz", 12.3},
       {"be", false},
       {"bop", 42}}}};
rego.AddData(data0);

rego.AddDataJson("""
   {
       "three": {
           "bar": "Baz",
           "baz": 15,
           "be": true,
           "bop": 4.23
       }
   }
   """);

var objectsSource = """
   package objects

   rect := {"width": 2, "height": 4}
   cube := {"width": 3, "height": 4, "depth": 5}
   a := 42
   b := false
   c := null
   d := {"a": a, "x": [b, c]}
   index := 1
   shapes := [rect, cube]
   names := ["prod", "smoke1", "dev"]
   sites := [{"name": "prod"}, {"name": names[index]}, {"name": "dev"}]
   e := {
       a: "foo",
       "three": c,
       names[2]: b,
       "four": d,
   }
   f := e["dev"]
   """;
rego.AddModule("objects.rego", objectsSource);

rego.SetInputTerm("""
   {
       "a": 10,
       "b": "20",
       "c": 30.0,
       "d": true
   }
   """);

Console.WriteLine(rego.Query("[data.one, input.b, data.objects.sites[1]] = x"));
// {"bindings":{"x":[{"bar":"Foo", "baz":5, "be":true, "bop":23.4}, "20", {"name":"smoke1"}]}}

When the same policy is going to be queried multiple times with different inputs, it can be more efficient to build a bundle.

using System.Collections;
using Rego;
Interpreter rego_build = new();
rego_build.AddDataJson("""
{"a": 7,
"b": 13}
""");

rego_build.AddModule("example.rego", """
    package example

   foo := data.a * input.x + data.b * input.y
   bar := data.b * input.x + data.a * input.y
""");

var bundle = rego_build.Build("x=data.example.foo + data.example.bar", ["example/foo", "example/bar"]);

rego_build.SaveBundle("bundle", bundle);
Interpreter rego_run = new();
rego_run.LoadBundle("bundle");

var input = Input.Create(new Dictionary<string, int>
{
    {"x", 104 },
    {"y", 119 }
});

rego_run.SetInput(input);

Console.WriteLine(rego_run.QueryBundle(bundle));
// {"expressions":[true], "bindings":{"x":4460}}
Console.WriteLine(rego_run.QueryBundle(bundle, "example/foo"));
// {"expressions":[2275]}

Constructors

Interpreter()

Creates a new Rego interpreter instance

public Interpreter()

Properties

BuildInfo

Returns build information about the underlying Rego library

public static string BuildInfo { get; }

Property Value

string

DebugEnabled

Gets or sets whether debug logging of intermediate ASTs is enabled.

public bool DebugEnabled { get; set; }

Property Value

bool

Handle

Returns the handle to the underlying Rego interpreter instance

public RegoHandle Handle { get; }

Property Value

RegoHandle

LogLevel

Gets or sets the log level for the interpreter.

public LogLevel LogLevel { get; set; }

Property Value

LogLevel

StrictBuiltInErrors

Gets or sets whether built-in functions will raise an error on invalid input.

public bool StrictBuiltInErrors { get; set; }

Property Value

bool

Version

Returns the version of the underlying Rego library

public static string Version { get; }

Property Value

string

WellFormedChecksEnabled

Gets or sets whether well-formedness checks are enabled.

public bool WellFormedChecksEnabled { get; set; }

Property Value

bool

Methods

AddDataJson(string)

Adds a base document in JSON format.

public void AddDataJson(string json)

Parameters

json string

JSON representation of the document

Examples

Interpreter rego = new();
var data = """
  {
    "one": {
      "bar": "Foo",
      "baz": 5,
      "be": true,
      "bop": 23.4
    },
    "two": {
      "bar": "Bar",
      "baz": 12.3,
      "be": false,
      "bop": 42
    }
  }
""";
rego.AddDataJson(data);
Console.WriteLine(rego.Query("data.one.bar"));
// {"expressions":["Foo"]}

Exceptions

RegoException

AddData<T>(T)

Adds a base document by serializing the provided object to JSON.

public void AddData<T>(T data)

Parameters

data T

The data to serialize

Type Parameters

T

Exceptions

RegoException

AddModule(string, string)

Adds a new Rego module to the interpreter

public void AddModule(string name, string source)

Parameters

name string

The name of the module

source string

The source code of the module

Examples

using Rego;
Interpreter rego = new();
var source = """
   package scalars

   greeting := "Hello"
   max_height := 42
   pi := 3.14159
   allowed := true
   location := null
""";
rego.AddModule("scalars.rego", source);
Console.WriteLine(rego.Query("data.scalars.greeting"));
// {"expressions":["Hello"]}

Exceptions

RegoException

Build(string)

Builds a bundle from the loaded modules and data, setting the specified query as the bundle's entrypoint.

public Bundle Build(string query)

Parameters

query string

The Rego query string

Returns

Bundle

The created bundle

Exceptions

RegoException

Build(string, string[])

Builds a bundle from the loaded modules and data, setting the specified query and entrypoints as the bundle's entrypoints. Entrypoints are of the format [path/to/rule].

public Bundle Build(string query, string[] entrypoints)

Parameters

query string
entrypoints string[]

The Rego entrypoints

Returns

Bundle

The created bundle

Examples

var input = new Dictionary<string, int>{
    {"x", 104 },
    {"y", 119 }};
var data = new Dictionary<string, int>{
    {"a", 7},
    {"b", 13}};
var module = """
    package example
    foo := data.a * input.x + data.b * input.y
    bar := data.b * input.x + data.a * input.y
""";

Interpreter rego_build = new();
rego_build.AddData(data);
rego_build.AddModule("example.rego", module);
var bundle = rego_build.Build("x=data.example.foo + data.example.bar", ["example/foo", "example/bar"]);

Interpreter rego_run = new();
rego_run.SetInput(input);
Console.WriteLine(rego_run.QueryBundle(bundle));
// {"expressions":[true], "bindings":{"x":4460}}

Console.WriteLine(rego_run.QueryBundle(bundle, "example/foo"));
// {"expressions":[2275]}

Exceptions

RegoException

Build(string[])

Builds a bundle from the loaded modules and data, setting the specified entrypoints. Entrypoints are of the format [path/to/rule].

public Bundle Build(string[] entrypoints)

Parameters

entrypoints string[]

The Rego entrypoints

Returns

Bundle

The created bundle

Exceptions

RegoException

IsAvailableBuiltIn(string)

Returns whether the specified string corresponds to a known built-in function.

public bool IsAvailableBuiltIn(string name)

Parameters

name string

The name of the built-in function

Returns

bool

True if the function is built-in, false otherwise

LoadBundle(string, BundleFormat)

Loads a bundle from the specified path. The path should point to a directory containing a bundle in JSON format, or to a file containing a bundle in binary format

public Bundle LoadBundle(string path, BundleFormat format = BundleFormat.JSON)

Parameters

path string

The path to the bundle

format BundleFormat

The format of the bundle

Returns

Bundle

The loaded bundle

Exceptions

ArgumentException
RegoException

Query(string)

Executes a query against the loaded modules, data, and input.

public Output Query(string query)

Parameters

query string

Rego query string

Returns

Output

The query output

Examples

Interpreter rego = new();
var input0 = new Dictionary<string, int> { { "a", 10 } };
var input1 = new Dictionary<string, int> { { "a", 4 } };
var input2 = new Dictionary<string, int> { { "a", 7 } };
var multi = """
    package multi

    default a := 0

    a := val {
        input.a > 0
        input.a < 10
        input.a % 2 == 1
        val := input.a * 10
    } {
        input.a > 0
        input.a < 10
        input.a % 2 == 0
        val := input.a * 10 + 1
    }

    a := input.a / 10 {
        input.a >= 10
    }
    """;
rego.AddModule("multi.rego", multi);

rego.SetInput(input0);
Console.WriteLine(rego.Query("data.multi.a"));
// {"expressions":[1]}

rego.SetInput(input1);
Console.WriteLine(rego.Query("data.multi.a"));
// {"expressions":[41]}

rego.SetInput(input2);
Console.WriteLine(rego.Query("data.multi.a"));
// {"expressions":[70]}

Exceptions

RegoException

QueryBundle(Bundle)

Executes a query against the specified bundle. This requires that Build(string) was provided with a query when this bundle was built.

public Output QueryBundle(Bundle bundle)

Parameters

bundle Bundle

The bundle to query

Returns

Output

The query output

Exceptions

RegoException

QueryBundle(Bundle, string)

Executes a query against the specified bundle, using the specified entrypoint. This requires that Build(string) was provided with the specified entrypoint when this bundle was built.

public Output QueryBundle(Bundle bundle, string entrypoint)

Parameters

bundle Bundle

The bundle to query

entrypoint string

The entrypoint to use for the query

Returns

Output

The query output

Exceptions

RegoException

SaveBundle(string, Bundle, BundleFormat)

Saves the specified bundle to the specified path. The path should point to a directory where the bundle will be saved in JSON format, or to a file where the bundle will be saved in binary format.

public void SaveBundle(string path, Bundle bundle, BundleFormat format = BundleFormat.JSON)

Parameters

path string

The path to the bundle

bundle Bundle

The bundle to save

format BundleFormat

The format of the bundle

Examples

Interpreter rego_build = new();
var bundle = rego_build.Build("a=1");
rego_build.SaveBundle("bundle_doctest1", bundle);
rego_build.SaveBundle("bundle_bin_doctest1.rbb", bundle, BundleFormat.Binary);

Interpreter rego_run = new();
bundle = rego_run.LoadBundle("bundle_doctest1");
Console.WriteLine(rego_run.QueryBundle(bundle));
// {"expressions":[true], "bindings":{"a":1}}

bundle = rego_run.LoadBundle("bundle_bin_doctest1.rbb", BundleFormat.Binary);
Console.WriteLine(rego_run.QueryBundle(bundle));
// {"expressions":[true], "bindings":{"a":1}}

Exceptions

ArgumentException
RegoException

SetDebugPath(string)

Sets the root of the directory tree where debug ASTs will be written. It will be created if it does not exist.

public void SetDebugPath(string path)

Parameters

path string

Path to a directory

Exceptions

RegoException

SetInput(Input)

Sets the input document from an Input object.

public void SetInput(Input input)

Parameters

input Input

The input object

Examples

Interpreter rego = new();
var input = Input.Create(new Dictionary<string, int>
{
    {"x", 104 },
    {"y", 119 }
});
rego.SetInput(input);
Console.WriteLine(rego.Query("x=input.x"));
// {"expressions":[true], "bindings":{"x":104}}

Exceptions

RegoException

SetInputTerm(string)

Sets the input document from a Rego term.

public void SetInputTerm(string term)

Parameters

term string

The Rego term

Examples

Interpreter rego = new();
var input = """
    {
        "a": 10,
        "b": "20",
        "c": 30.0,
        "d": true
    }
    """;
rego.SetInputTerm(input);
Console.WriteLine(rego.Query("input.a"));
// {"expressions":[10]}

Exceptions

RegoException

SetInput<T>(T)

Sets the input document by serializing the provided object to JSON.

public void SetInput<T>(T data)

Parameters

data T

The data to serialize

Type Parameters

T

Exceptions

RegoException