7#include "trieste/logging.h"
8#include "trieste/token.h"
10#include <initializer_list>
11#include <trieste/trieste.h>
19 using namespace trieste;
20 using namespace wf::ops;
23 inline const auto Module =
24 TokenDef(
"rego-module", flag::lookup | flag::symtab);
25 inline const auto Package = TokenDef(
"rego-package");
26 inline const auto Policy = TokenDef(
"rego-policy");
27 inline const auto Rule = TokenDef(
29 flag::lookup | flag::lookdown | flag::symtab | flag::defbeforeuse);
30 inline const auto RuleHead = TokenDef(
"rego-rulehead");
31 inline const auto RuleHeadComp = TokenDef(
"rego-ruleheadcomp");
32 inline const auto RuleHeadFunc = TokenDef(
"rego-ruleheadfunc");
33 inline const auto RuleHeadSet = TokenDef(
"rego-ruleheadset");
34 inline const auto RuleHeadObj = TokenDef(
"rego-ruleheadobj");
35 inline const auto RuleArgs = TokenDef(
"rego-ruleargs");
36 inline const auto Query = TokenDef(
"rego-query");
37 inline const auto Literal = TokenDef(
"rego-literal");
38 inline const auto Expr = TokenDef(
"rego-expr");
39 inline const auto ExprInfix = TokenDef(
"rego-exprinfix");
40 inline const auto ExprCall = TokenDef(
"rego-exprcall");
41 inline const auto ExprEvery = TokenDef(
"rego-exprevery", flag::symtab);
42 inline const auto ExprParens = TokenDef(
"rego-exprparens");
43 inline const auto UnaryExpr = TokenDef(
"rego-unaryexpr");
44 inline const auto NotExpr = TokenDef(
"rego-not-expr");
45 inline const auto Term = TokenDef(
"rego-term");
46 inline const auto InfixOperator = TokenDef(
"rego-infixoperator");
47 inline const auto BoolOperator = TokenDef(
"rego-booloperator");
48 inline const auto ArithOperator = TokenDef(
"rego-arithoperator");
49 inline const auto AssignOperator = TokenDef(
"rego-assignoperator");
50 inline const auto BinOperator = TokenDef(
"rego-binoperator");
51 inline const auto Ref = TokenDef(
"rego-ref");
52 inline const auto RefArgBrack = TokenDef(
"rego-refargbrack");
53 inline const auto RefArgDot = TokenDef(
"rego-refargdot");
54 inline const auto Var = TokenDef(
"rego-var", flag::print);
55 inline const auto Scalar = TokenDef(
"rego-scalar");
56 inline const auto String = TokenDef(
"rego-string");
57 inline const auto Array = TokenDef(
"rego-array");
58 inline const auto Object = TokenDef(
"rego-object");
59 inline const auto Set = TokenDef(
"rego-set");
60 inline const auto ObjectItem = TokenDef(
"rego-objectitem");
61 inline const auto RawString = TokenDef(
"rego-rawstring", flag::print);
62 inline const auto JSONString = TokenDef(
"rego-STRING", flag::print);
63 inline const auto TemplateString = TokenDef(
"rego-templatestring");
64 inline const auto TemplateLiteral =
65 TokenDef(
"rego-templateliteral", flag::print);
66 inline const auto Int = TokenDef(
"rego-INT", flag::print);
67 inline const auto Float = TokenDef(
"rego-FLOAT", flag::print);
68 inline const auto True = TokenDef(
"rego-true");
69 inline const auto False = TokenDef(
"rego-false");
70 inline const auto Null = TokenDef(
"rego-null");
71 inline const auto Equals = TokenDef(
"rego-equals");
72 inline const auto NotEquals = TokenDef(
"rego-notequals");
73 inline const auto LessThan = TokenDef(
"rego-lessthan");
74 inline const auto GreaterThan = TokenDef(
"rego-greaterthan");
75 inline const auto LessThanOrEquals = TokenDef(
"rego-lessthanorequals");
76 inline const auto GreaterThanOrEquals = TokenDef(
"rego-greaterthanorequals");
77 inline const auto Add = TokenDef(
"rego-add");
78 inline const auto Subtract = TokenDef(
"rego-subtract");
79 inline const auto Multiply = TokenDef(
"rego-multiply");
80 inline const auto Divide = TokenDef(
"rego-divide");
81 inline const auto Modulo = TokenDef(
"rego-modulo");
82 inline const auto And = TokenDef(
"rego-and");
83 inline const auto Or = TokenDef(
"rego-or");
84 inline const auto Assign = TokenDef(
"rego-assign");
85 inline const auto Unify = TokenDef(
"rego-unify");
86 inline const auto Default = TokenDef(
"rego-default");
87 inline const auto Some = TokenDef(
"rego-some");
88 inline const auto SomeDecl = TokenDef(
"rego-somedecl");
89 inline const auto If = TokenDef(
"rego-if");
90 inline const auto IsIn = TokenDef(
"rego-in");
91 inline const auto Contains = TokenDef(
"rego-contains");
92 inline const auto Else = TokenDef(
"rego-else");
93 inline const auto As = TokenDef(
"rego-as");
94 inline const auto With = TokenDef(
"rego-with");
95 inline const auto Every = TokenDef(
"rego-every");
96 inline const auto ArrayCompr = TokenDef(
"rego-arraycompr", flag::symtab);
97 inline const auto ObjectCompr = TokenDef(
"rego-objectcompr", flag::symtab);
98 inline const auto SetCompr = TokenDef(
"rego-setcompr", flag::symtab);
99 inline const auto Membership = TokenDef(
"rego-membership");
100 inline const auto Not = TokenDef(
"rego-not");
101 inline const auto Import =
102 TokenDef(
"rego-import", flag::lookdown | flag::lookup | flag::shadowing);
103 inline const auto Placeholder = TokenDef(
"rego-placeholder");
104 inline const auto Version = TokenDef(
"rego-version", flag::print);
107 inline const auto RuleBodySeq = TokenDef(
"rego-rulebodyseq");
108 inline const auto ImportSeq = TokenDef(
"rego-importseq");
109 inline const auto RuleRef = TokenDef(
"rego-ruleref");
110 inline const auto RuleHeadType = TokenDef(
"rego-ruleheadtype");
111 inline const auto WithSeq = TokenDef(
"rego-withseq");
112 inline const auto TermSeq = TokenDef(
"rego-termseq");
113 inline const auto ExprSeq = TokenDef(
"rego-exprseq");
114 inline const auto VarSeq = TokenDef(
"rego-varseq");
115 inline const auto RefHead = TokenDef(
"rego-refhead");
116 inline const auto RefArgSeq = TokenDef(
"rego-refargseq");
117 inline const auto Key = TokenDef(
"rego-key", flag::print);
118 inline const auto Val = TokenDef(
"rego-value");
119 inline const auto Undefined = TokenDef(
"rego-undefined");
120 inline const auto Name = TokenDef(
"rego-name");
121 inline const auto Return = TokenDef(
"rego-return");
122 inline const auto Target = TokenDef(
"rego-target");
123 inline const auto Lhs = TokenDef(
"rego-lhs");
124 inline const auto Rhs = TokenDef(
"rego-rhs");
125 inline const auto Src = TokenDef(
"rego-src");
126 inline const auto Args = TokenDef(
"rego-args");
127 inline const auto Idx = TokenDef(
"rego-idx");
128 inline const auto Row = TokenDef(
"rego-row");
129 inline const auto Col = TokenDef(
"rego-col");
132 inline const auto Results = TokenDef(
"rego-results", flag::symtab);
133 inline const auto Result = TokenDef(
"rego-result", flag::symtab);
134 inline const auto Bindings = TokenDef(
"rego-bindings");
135 inline const auto Terms = TokenDef(
"rego-terms");
136 inline const auto Binding = TokenDef(
"rego-binding", flag::lookdown);
137 inline const auto ErrorCode = TokenDef(
"rego-errorcode");
138 inline const auto ErrorSeq = TokenDef(
"rego-errorseq");
139 inline const auto Line = TokenDef(
"rego-line", flag::print);
141 inline const auto wf_assign_op = Assign | Unify;
142 inline const auto wf_arith_op = Add | Subtract | Multiply | Divide | Modulo;
143 inline const auto wf_bin_op = And | Or | Subtract;
144 inline const auto wf_bool_op = Equals | NotEquals | LessThan |
145 LessThanOrEquals | GreaterThan | GreaterThanOrEquals | Not;
146 inline const auto wf_exprs =
147 Term | ExprCall | ExprInfix | ExprEvery | ExprParens | UnaryExpr;
150 inline const auto wf =
151 (Top <<= Query | Module)
152 | (Module <<= Package * Version * ImportSeq * Policy)
153 | (ImportSeq <<= Import++)
154 | (Import <<= Ref * Var)
156 | (Policy <<= Rule++)
157 | (Rule <<= (Default >>= True | False) * RuleHead * RuleBodySeq)
158 | (RuleHead <<= RuleRef * (RuleHeadType >>= (RuleHeadSet | RuleHeadObj | RuleHeadFunc | RuleHeadComp)))
159 | (RuleRef <<= Var | Ref)
160 | (RuleHeadComp <<= Expr)
161 | (RuleHeadObj <<= Expr * Expr)
162 | (RuleHeadFunc <<= RuleArgs * Expr)
163 | (RuleHeadSet <<= Expr)
164 | (RuleArgs <<= Term++)
165 | (RuleBodySeq <<= (Else | Query)++)
166 | (Else <<= Expr * Query)
167 | (Query <<= Literal++)
168 | (Literal <<= (Expr >>= SomeDecl | Expr | NotExpr) * WithSeq)
169 | (WithSeq <<= With++)
170 | (With <<= Term * Expr)
171 | (SomeDecl <<= ExprSeq * (IsIn >>= Expr | Undefined))
173 | (Expr <<= (Term | ExprCall | ExprInfix | ExprEvery | ExprParens | UnaryExpr))
174 | (ExprCall <<= Ref * ExprSeq)
175 | (ExprSeq <<= Expr++)
176 | (ExprInfix <<= Expr * InfixOperator * Expr)
177 | (ExprEvery <<= VarSeq * (IsIn >>= Term | ExprCall | ExprInfix) * Query)
178 | (VarSeq <<= Var++[1])
179 | (ExprParens <<= Expr)
180 | (UnaryExpr <<= Expr)
181 | (Membership <<= ExprSeq * Expr)
182 | (Term <<= Ref | Var | Scalar | Array | Object | Set | Membership | ArrayCompr | ObjectCompr | SetCompr)
183 | (TemplateString <<= Literal++)
184 | (ArrayCompr <<= Expr * Query)
185 | (SetCompr <<= Expr * Query)
186 | (ObjectCompr <<= Expr * Expr * Query)
187 | (InfixOperator <<= AssignOperator | BoolOperator | ArithOperator | BinOperator)
188 | (BoolOperator <<= Equals | NotEquals | LessThan | GreaterThan | LessThanOrEquals | GreaterThanOrEquals)
189 | (ArithOperator <<= Add | Subtract | Multiply | Divide | Modulo)
190 | (BinOperator <<= And | Or)
191 | (AssignOperator <<= Assign | Unify)
192 | (Ref <<= RefHead * RefArgSeq)
193 | (RefHead <<= Var | Array | Object | Set | ArrayCompr | ObjectCompr | SetCompr | ExprCall)
194 | (RefArgSeq <<= (RefArgDot | RefArgBrack)++)
195 | (RefArgBrack <<= Expr | Placeholder)
196 | (RefArgDot <<= Var)
197 | (Scalar <<= String | Int | Float | True | False | Null)
198 | (String <<= JSONString | RawString | TemplateString)
200 | (Object <<= ObjectItem++)
201 | (ObjectItem <<= (Key >>= Expr) * (Val >>= Expr))
207 inline const auto wf_result =
208 (Top <<= Results | Undefined)
209 | (Results <<= Result++[1])
210 | (Result <<= Terms * Bindings)
212 | (Bindings <<= Binding++)
213 | (Binding <<= (Key >>= Var) * (Val >>= Term))[Key]
214 | (Term <<= Scalar | Array | Object | Set)
217 | (Object <<= ObjectItem++)
218 | (ObjectItem <<= (Key >>= Term) * (Val >>= Term))
219 | (Scalar <<= JSONString | Int | Float | True | False | Null)
220 | (Error <<= ErrorMsg * ErrorAst * ErrorCode)
258 const Location&
loc()
const;
262 std::optional<std::int64_t>
to_int()
const;
370 std::string quotient;
371 std::string remainder;
374 static bool less_than(
375 const std::string_view& lhs,
const std::string_view& rhs);
376 static bool greater_than(
377 const std::string_view& lhs,
const std::string_view& rhs);
378 static bool equal(
const std::string_view& lhs,
const std::string_view& rhs);
379 static std::string add(
380 const std::string_view& lhs,
const std::string_view& rhs,
bool negative);
381 static std::string subtract(
382 const std::string_view& lhs,
const std::string_view& rhs,
bool negative);
383 static DivideResult divide(
384 const std::string_view& lhs,
const std::string_view& rhs);
385 static std::string multiply(
386 const std::string_view& lhs,
const std::string_view& rhs);
387 std::string_view digits()
const;
389 static Location Zero;
450 const std::string&
code()
const;
460 const std::string&
pre()
const;
482 const std::string&
func()
const;
493 const std::vector<Token>&
types()
const;
519 bool m_specify_number;
521 std::string m_prefix;
522 std::string m_message;
524 std::vector<Token> m_types;
597 const Node& node,
const std::string_view&
key);
689 const std::size_t
AnyArity = std::numeric_limits<std::size_t>::max();
692 inline const auto Arg =
TokenDef(
"rego-builtin-arg");
697 inline const auto Return =
TokenDef(
"rego-builtins-return");
698 inline const auto Name =
TokenDef(
"rego-builtin-name", flag::print);
700 TokenDef(
"rego-builtin-description", flag::print);
707 inline const auto Set =
TokenDef(
"rego-builtin-set");
712 inline const auto Any =
TokenDef(
"rego-builtin-any");
713 inline const auto String =
TokenDef(
"rego-builtin-string");
862 typedef BuiltIn (*BuiltInFactory)();
954 template <
typename T>
957 m_lookup_behavior = BuiltInsDef::LookupBehavior::Whitelist;
971 template <
typename T>
974 m_lookup_behavior = BuiltInsDef::LookupBehavior::Whitelist;
987 template <
typename T>
990 m_lookup_behavior = BuiltInsDef::LookupBehavior::Blacklist;
1005 template <
typename T>
1008 m_lookup_behavior = BuiltInsDef::LookupBehavior::Blacklist;
1021 static std::shared_ptr<BuiltInsDef>
create();
1026 enum class LookupBehavior
1033 LookupBehavior m_lookup_behavior;
1034 std::set<Location> m_list;
1035 std::map<Location, BuiltIn> m_builtins;
1036 bool m_strict_errors;
1040 using BuiltIns = std::shared_ptr<BuiltInsDef>;
1063 const std::string&
msg,
1103 const trieste::Node& node,
1219 ObjectInsertOnce = 26,
1266 std::variant<CallExt, CallDynamicExt, WithExt, std::vector<Block>,
Block>
1322 std::shared_ptr<const StatementExt>
ext;
1423 void save(
const std::filesystem::path& path)
const;
1507 typedef std::vector<Node> Frame;
1524 Node read_local(
size_t index)
const;
1525 void write_local(
size_t index,
Node value);
1526 bool is_defined(
size_t key)
const;
1527 void reset_local(
size_t key);
1528 void add_result(
Node node);
1529 const Nodes& result_set()
const;
1531 std::string_view root_function_name()
const;
1534 const Nodes& errors()
const;
1536 void add_error_multiple_output(
Node inst);
1537 void add_error_object_insert(
Node inst);
1540 bool in_with()
const;
1543 bool in_break()
const;
1544 void push_break(
size_t levels);
1546 size_t stmt_count()
const;
1553 std::vector<Location> m_call_stack;
1554 std::vector<size_t> m_num_args;
1555 std::map<Location, Node> m_function_cache;
1557 size_t m_with_count;
1558 size_t m_break_count;
1559 size_t m_stmt_count;
1562 void run_plan(
const bundle::Plan&
plan, State&
state)
const;
1565 State&
state,
size_t index,
const bundle::Statement&
stmt)
const;
1566 Code run_scan(State&
state,
const bundle::Statement&
stmt)
const;
1567 Code run_with(State&
state,
const bundle::Statement&
stmt)
const;
1571 const std::vector<bundle::Operand>&
args,
1572 size_t target)
const;
1576 bool insert_into_object(
1578 Node to_term(
const Node& value)
const;
1579 Node unpack_operand(
1580 const State&
state,
const bundle::Operand&
operand)
const;
1581 Node write_and_swap(
1584 const std::vector<size_t>& path,
1590 size_t m_stmt_limit;
1787 const std::initializer_list<std::string>&
entrypoints);
2027 std::vector<std::string> m_entrypoints;
2028 std::filesystem::path m_debug_path;
2029 bool m_debug_enabled;
2030 bool m_wf_check_enabled;
2034 std::unique_ptr<Reader> m_reader;
2035 std::unique_ptr<Reader> m_json;
2036 std::unique_ptr<Rewriter> m_data_from_json;
2037 std::unique_ptr<Rewriter> m_input_from_json;
2038 std::unique_ptr<Rewriter> m_to_input;
2039 std::unique_ptr<Rewriter> m_bundle;
2040 std::unique_ptr<Rewriter> m_write_bundle;
2041 std::unique_ptr<Rewriter> m_read_bundle;
2043 std::size_t m_data_count;
2044 std::map<std::string, Node> m_cache;
2046 std::string m_c_error;
2061 inline const auto Plan =
TokenDef(
"rego-plan", flag::lookup | flag::symtab);
2062 inline const auto Block =
TokenDef(
"rego-block");
2063 inline const auto Function =
2064 TokenDef(
"rego-function", flag::lookup | flag::symtab);
2066 inline const auto Operand =
TokenDef(
"rego-operand");
2067 inline const auto Int32 =
TokenDef(
"rego-int32", flag::print);
2068 inline const auto Int64 =
TokenDef(
"rego-int64", flag::print);
2115 TokenDef(
"rego-objectinsertoncestmt");
Big Integer implemention based on strings.
Definition rego.hh:244
friend BigInt operator+(const BigInt &lhs, const BigInt &rhs)
Adds two BigInts.
std::optional< std::size_t > to_size() const
Attempts to convert the BigInt to a size_t integer.
friend BigInt operator*(const BigInt &lhs, const BigInt &rhs)
Multiplies two BigInts.
friend bool operator<(const BigInt &lhs, const BigInt &rhs)
Compares two BigInts for less-than.
friend bool operator>(const BigInt &lhs, const BigInt &rhs)
Compares two BigInts for greater-than.
std::optional< std::int64_t > to_int() const
Attempts to convert the BigInt to a 64-bit integer.
friend BigInt operator-(const BigInt &lhs, const BigInt &rhs)
Subtracts two BigInts.
BigInt negate() const
Negates the BigInt.
friend bool operator!=(const BigInt &lhs, const BigInt &rhs)
Compares two BigInts for inequality.
bool is_negative() const
Checks if the BigInt is negative.
friend bool operator<=(const BigInt &lhs, const BigInt &rhs)
Compares two BigInts for less-than-or-equal.
static bool is_int(const Location &loc)
Checks if a Location represents a valid integer string.
friend BigInt operator%(const BigInt &lhs, const BigInt &rhs)
Computes the remainder of dividing two BigInts.
bool is_zero() const
Checks if the BigInt is zero.
friend bool operator==(const BigInt &lhs, const BigInt &rhs)
Compares two BigInts for equality.
BigInt increment() const
Increments the BigInt by one.
BigInt(std::int64_t value)
Constructs a BigInt from a 64-bit integer.
BigInt()
Default constructor, initializes to zero.
BigInt(const Location &value)
Constructs a BigInt from a Location representing a arbitrary precision integer string.
const Location & loc() const
Gets the Location representing the integer string.
friend BigInt operator/(const BigInt &lhs, const BigInt &rhs)
Divides two BigInts.
BigInt decrement() const
Decrements the BigInt by one.
friend std::ostream & operator<<(std::ostream &os, const BigInt &value)
Outputs a BigInt to a stream.
BigInt abs() const
Gets the absolute value of the BigInt.
friend bool operator>=(const BigInt &lhs, const BigInt &rhs)
Compares two BigInts for greater-than-or-equal.
Manages the set of builtins used by an interpreter to resolve built-in calls.
Definition rego.hh:874
static std::shared_ptr< BuiltInsDef > create()
Creates the standard builtin set.
bool is_builtin(const Location &name)
Determines whether the provided name refers to a built-in.
bool is_deprecated(const Location &version, const Location &name) const
Determines whether the provided builtin name is deprecated in the provided version.
bool strict_errors() const
Whether to throw built-in errors.
Node call(const Location &name, const Location &version, const Nodes &args)
Calls the built-in with the provided name and arguments.
BuiltInsDef & blacklist(const std::initializer_list< T > &forbidden)
Sets a blacklist of built-in names that are forbidden from being loaded.
Definition rego.hh:988
void clear()
Called to clear any persistent state or caching.
BuiltInsDef & allow_all()
Allow all built-ins to be loaded from the standard library.
BuiltInsDef & register_builtins(const T &built_ins)
Registers a set of built-ins.
Definition rego.hh:934
BuiltInsDef & register_standard_builtins()
This method no longer needs to be called.
BuiltInsDef & whitelist(T begin, T end)
Sets a whitelist of built-in names that are allowed to be loaded.
Definition rego.hh:972
BuiltInsDef & blacklist(T begin, T end)
Sets a blacklist of built-in names that are forbidden from being loaded.
Definition rego.hh:1006
BuiltInsDef & whitelist(const std::initializer_list< T > &allowed)
Sets a whitelist of built-in names that are allowed to be loaded.
Definition rego.hh:955
BuiltIn at(const Location &name)
Gets the built-in with the provided name.
BuiltInsDef() noexcept
Constructor.
BuiltInsDef & register_builtin(const BuiltIn &built_in)
Registers a built-in.
Node decl(const Location &name)
Gets the declaration node for the specified built-in.
This class forms the main interface to the Rego library.
Definition rego.hh:1697
Node query_bundle(const Bundle &bundle)
Performs a query against a bundle.
Interpreter & debug_path(const std::filesystem::path &prefix)
The path to the debug directory.
std::string query(const std::string &query_expr)
Executes a query against the interpreter.
Node add_module(const std::string &name, const std::string &contents)
Adds a module (i.e. virtual document) to the interpreter.
const std::filesystem::path & debug_path() const
Gets the debug path.
Node set_input_term(const std::string &term)
Sets the input term of the interpreter.
std::string query()
Executes the documents against the interpreter.
Node add_data_json_file(const std::filesystem::path &path)
Adds a base document to the interpreter.
Interpreter & stmt_limit(size_t stmt_limit)
Sets the maximum number of statements that will execute before a timeout.
Node set_input_json_file(const std::filesystem::path &path)
Sets the input document to the interpreter.
Interpreter & entrypoints(const std::initializer_list< std::string > &entrypoints)
Sets the entrypoints to include when building a bundle.
Node save_bundle(const std::filesystem::path &dir, const Node &bundle)
Saves a bundle to a directory in JSON format.
Node query_bundle(const Bundle &bundle, const std::string &endpoint)
Performs a query against a bundle.
LogLevel log_level() const
Returns the current log level of this interpreter.
Node set_input_json(const std::string &json)
Sets the input document to the interpreter.
bool wf_check_enabled() const
Checks if well-formedness checks are enabled.
Interpreter & log_level(LogLevel level)
Sets the log level of the interpreter.
Output query_output(const std::string &query_expr)
Executes a query against the interpreter.
Node set_input(const Node &node)
Sets the input document to the interpreter.
BuiltIns builtins() const
The built-ins used by the interpreter.
std::vector< std::string > & entrypoints()
Gets the entrypoints to include when building a bundle.
std::string output_to_string(const Node &output) const
Converts an output node into a human-readable string.
Interpreter & c_error(const std::string &error)
Sets the most recent error message.
Node add_data_json(const std::string &json)
Adds a base document to the interpreter.
Interpreter()
Constructor.
Output query_output()
Executes a query against the interpreter.
Node query_node()
Executes a query against the interpreter.
Interpreter & log_level(const std::string &level)
Sets the logging level for the interpreter from a string.
const std::vector< std::string > & entrypoints() const
Gets the entrypoints to include when building a bundle.
Node query_node(const std::string &query_expr)
Executes a query against the interpreter.
Interpreter & wf_check_enabled(bool enabled)
Sets whether well-formedness checks are enabled.
Node load_bundle(const std::filesystem::path &dir)
Loads a bundle in JSON format from a direction.
Interpreter & entrypoints(const std::vector< std::string > &entrypoints)
Sets the entrypoints to include when building a bundle.
Node build()
Builds a bundle from the current state of the interpreter.
size_t stmt_limit() const
Gets the maximum number of statements that will execute before a timeout.
bool debug_enabled() const
Checks if debug mode is enabled.
Node add_data(const Node &node)
Adds a base document to the interpreter.
Interpreter & debug_enabled(bool enabled)
Sets whether debug mode is enabled.
const std::string & c_error() const
Returns a string representing the most recent error message.
Node add_module_file(const std::filesystem::path &path)
Adds a module (i.e. virtual document) file to the interpreter.
Node set_query(const std::string &query)
Sets the query expression of the interpreter.
Encapsulates the output of a Rego query.
Definition rego.hh:1628
Node binding_at(size_t index, const std::string &name) const
Gets the binding for the specified name at the specified result index.
const std::string & json() const
Gets the JSON representation of the output.
std::vector< std::string > errors() const
Gets the errors in the output.
size_t size() const
Gets the number of results.
Node expressions_at(size_t index) const
Gets the expressions for the result at the specified index.
Node binding(const std::string &name) const
Gets the binding for the specified name at the first result.
Node node() const
Gets the underlying node.
Node expressions() const
Gets the expressions for the first result.
Output(Node node)
Constructor.
bool ok() const
Whether the Output is OK (i.e., has not resulted in one or more errors)
Options for unwrapping an argument.
Definition rego.hh:420
bool exclude_got() const
Whether the statement indicating what was received instead of the expected type should be excluded.
const std::string & func() const
The name of the function. If provide, will be a prefix on the message as "<func-name>:".
const Token & type() const
The singular type to match against.
UnwrapOpt & type(const Token &value)
Sets the singular type to match against.
UnwrapOpt & pre(const std::string &value)
Sets the error preamble.
UnwrapOpt & exclude_got(bool exclude_got)
Sets whether to exclude the "got" statement in the error message.
UnwrapOpt & specify_number(bool specify_number)
Sets whether to specify in the error message which kind of number was received.
UnwrapOpt(std::size_t index)
Construct an UnwrapOpt.
bool specify_number() const
Whether to specify in the error message which kind of number was received (i.e. integer or floating p...
UnwrapOpt & code(const std::string &value)
Sets the error code for the error message.
const std::string & pre() const
The error preamble. If omitted, a default preamble will be constructed from the operation metadata in...
const std::string & code() const
The error code for the error message. Default value if omitted is EvalTypeError.
const std::string & message() const
The full error message. If this is set, no message will be generated and instead this will be returne...
Node unwrap(const Nodes &args) const
Unwraps an argument from the provided vector of nodes.
UnwrapOpt & message(const std::string &value)
Sets the full error message. If this is set, no message will be generated and instead this will be re...
UnwrapOpt & func(const std::string &value)
Sets the name of the function.
UnwrapOpt & types(const std::vector< Token > &value)
Sets the types to match against.
const std::vector< Token > & types() const
The types to match against. The operand must be one of the provided types or else an error node will ...
This class implements a virtual machine that can execute compiled Rego bundles.
Definition rego.hh:1457
BuiltIns builtins() const
Gets the built-in functions used during execution.
VirtualMachine & stmt_limit(size_t stmt_limit)
Sets the maximum number of statements that will execute before a timeout.
VirtualMachine & bundle(Bundle bundle)
Sets the bundle to use during execution.
Node run_query(Node input) const
Executes the query plan in the bundle with the provided input.
Bundle bundle() const
Gets the bundle used during execution.
VirtualMachine & builtins(BuiltIns builtins)
Sets the built-in functions to use during execution.
size_t stmt_limit() const
Gets the maximum number of statements that will execute before a timeout.
Node run_entrypoint(const Location &entrypoint, Node input) const
Executes the entrypoint plan in the bundle with the provided input.
OperandType
The type of an operand.
Definition rego.hh:1126
StatementType
The type of an IR statement.
Definition rego.hh:1192
std::vector< Statement > Block
A block of statements.
Definition rego.hh:1232
SetFormat
Controls how sets are rendered by to_key().
Definition rego.hh:1086
@ Angle
Angle brackets: <1, 2, 3> (internal key representation).
@ Rego
Curly braces / set(): {1, 2, 3} or set() (OPA Rego display format).
@ Square
Square brackets: [1, 2, 3] (JSON-compatible array format).
bool get_bool(const Node &node)
Extracts the value of a node as a boolean.
std::optional< Node > try_get_item(const Node &node, const std::string_view &key)
Tries to get an item within an object using its key.
Node scalar()
Creates a null scalar.
std::optional< bool > try_get_bool(const Node &node)
Attempts to extract the value of a node as a boolean.
std::optional< double > try_get_double(const Node &node)
Attempts to extract the value of a node as an 64-bit floating point number.
Node null()
Creates a null scalar.
std::shared_ptr< BuiltInDef > BuiltIn
A pointer to a BuiltInDef.
Definition rego.hh:229
Node object_item(const Node &key_term, const Node &val_term)
Converts the key and val terms to an object item.
Node array(const std::initializer_list< Node > &array_members)
Converts the value to an array node.
BigInt get_int(const Node &node)
Extracts the value of a node as an integer.
double get_double(const Node &node)
Extracts the value of a node as an double.
Node unwrap_arg(const Nodes &args, const UnwrapOpt &options)
Unwraps an argument from the provided vector of nodes.
Rewriter json_to_bundle()
Rewrites an OPA bundle JSON to a Bundle AST.
Node err(NodeRange &r, const std::string &msg, const std::string &code=UnknownError)
Generates an error node.
std::optional< BigInt > try_get_int(const Node &node)
Attempts to extract the value of a node as an integer. In the case that the node is a double,...
std::function< Node(const Nodes &)> BuiltInBehavior
The function pointer to the behavior of the built-in.
Definition rego.hh:232
Reader file_to_rego()
Parses Rego queries and virtual documents.
Rewriter bundle_to_json()
Rewrites a Bundle AST to a JSON AST in OPA bundle JSON format.
std::optional< std::string > try_get_string(const Node &node)
Attempts to extract the value of a node as a string.
Rewriter rego_to_bundle(BuiltIns builtins=BuiltInsDef::create())
Rewrites a Rego AST to a Bundle AST.
std::shared_ptr< BundleDef > Bundle
A pointer to a BundleDef.
Definition rego.hh:1367
std::string_view get_raw_string(const Node &node)
Returns the raw location of the node from the source.
Node version()
Returns a node representing the version of the library.
UnwrapResult unwrap(const Node &term, const Token &type)
Attempts to unwrap a node to a specified type.
LogLevel log_level_from_string(const std::string &value)
Converts a string to a log level (case insensitive).
Node number(double value)
Converts the value to a scalar node.
Node string(const char *value)
Converts the value to a scalar node.
LogLevel
The logging level.
Definition rego.hh:1110
Rewriter rego_to_input()
Rewrites a Query AST to an input term.
Node set(const std::initializer_list< Node > &set_members)
Converts the value to a set node.
Rewriter json_to_rego(bool as_term=false)
Rewrites a JSON AST to a Rego data input AST.
std::string get_string(const Node &node)
Extracts the value of a node as a string.
std::string to_key(const trieste::Node &node, SetFormat set_format=SetFormat::Angle, bool sort_arrays=false, const char *list_delim=",")
Converts a node to a unique key representation that can be used for comparison.
Rewriter rego_to_yaml()
Rewrites a Rego binding term to a YAML AST.
Rewriter rego_to_json()
Rewrites a Rego binding term to a JSON AST.
Node boolean(bool value)
Converts the value to a scalar node.
Node object(const std::initializer_list< Node > &object_items)
Converts the value to an object node.
uint_least32_t regoEnum
Enum type.
Definition rego_c.h:32
Struct which defines a built-in function.
Definition rego.hh:793
bool available
Whether the builtin is available.
Definition rego.hh:811
Node decl
The declaration node which adheres to the builtins::wf_decl well-formedness definition.
Definition rego.hh:800
static BuiltIn create(const Location &name, size_t arity, BuiltInBehavior behavior)
Creates a new built-in.
virtual void clear()
Called to clear any persistent state or caching.
static BuiltIn placeholder(const Location &name, Node decl, const std::string &message)
Creates a placeholder for a built-in which is not available on this platform.
BuiltInDef(Location name_, Node decl_, BuiltInBehavior behavior_, bool available_)
Constructor.
BuiltInBehavior behavior
The function which will be called when the built-in is evaluated.
Definition rego.hh:808
static BuiltIn create(const Location &name, Node decl, BuiltInBehavior behavior)
Creates a new built-in.
std::size_t arity
The number of expected arguments.
Definition rego.hh:805
Location name
The name used to match against expression calls in the rego program.
Definition rego.hh:796
Represents a compiled Rego bundle.
Definition rego.hh:1371
std::map< Location, size_t > name_to_plan
Map from function names to their indices.
Definition rego.hh:1379
std::vector< bundle::Function > functions
The functions in the bundle.
Definition rego.hh:1383
std::map< Location, size_t > name_to_func
Map from plan names to their indices.
Definition rego.hh:1377
static Bundle load(const std::filesystem::path &path)
Loads a bundle from a file.
std::vector< Location > strings
The string table for the bundle.
Definition rego.hh:1385
std::vector< Source > files
The module source files which were compiled into the bundle.
Definition rego.hh:1387
static Bundle from_node(Node bundle)
Constructs a bundle from an AST node.
std::vector< bundle::Plan > plans
The plans in the bundle.
Definition rego.hh:1381
void save(const std::filesystem::path &path) const
Saves the bundle to a file.
Source query
The query, if one was included.
Definition rego.hh:1394
Node data
The merged base data document.
Definition rego.hh:1373
std::optional< size_t > find_function(const Location &name) const
Finds a function by name.
std::optional< size_t > find_plan(const Location &name) const
Finds a plan by name.
std::map< Location, Node > builtin_functions
The built-in functions required by the bundle.
Definition rego.hh:1375
static Bundle load(std::istream &stream)
Loads a bundle from a stream.
size_t local_count
The number of local variables required by the bundle.
Definition rego.hh:1389
std::optional< size_t > query_plan
The index of the query plan, if one was included.
Definition rego.hh:1391
bool is_function(const Location &name) const
Determines whether the provided name refers to a function.
void save(std::ostream &stream) const
Saves the bundle to a stream.
Result of unwrapping a node.
Definition rego.hh:395
bool success
True if the argument was unwrapped successfully.
Definition rego.hh:400
Node node
The unwrapped argument or nullptr (if unsuccessful).
Definition rego.hh:397
Additional information for CallDynamic statements.
Definition rego.hh:1245
std::vector< Operand > ops
The arguments to the function.
Definition rego.hh:1249
std::vector< Operand > path
The path to the function being called.
Definition rego.hh:1247
Additional information for Call statements.
Definition rego.hh:1236
std::vector< Operand > ops
The arguments to the function.
Definition rego.hh:1240
Location func
The function being called.
Definition rego.hh:1238
Represents a function in the IR.
Definition rego.hh:1346
std::vector< size_t > parameters
The local indices of the function parameters.
Definition rego.hh:1354
std::vector< Block > blocks
The blocks which make up the function.
Definition rego.hh:1358
Location name
The name of the function.
Definition rego.hh:1348
size_t arity
The arity of the function.
Definition rego.hh:1350
size_t result
The index of the result local.
Definition rego.hh:1356
std::vector< Location > path
The path of the function (the name broken into segments)
Definition rego.hh:1352
bool cacheable
Whether the function result can be cached.
Definition rego.hh:1360
Represents an operand in the IR.
Definition rego.hh:1146
size_t index
A local index (if type is Local, String, or Index).
Definition rego.hh:1154
std::int64_t value
An integer value (if type is Value).
Definition rego.hh:1152
OperandType type
The type of the operand.
Definition rego.hh:1148
Operand()
Constructs an Operand with type None.
static Operand from_op(const Node &n)
Constructs an Operand from the specified node.
friend std::ostream & operator<<(std::ostream &stream, const Operand &op)
Writes the operand to a stream (used for debugging purposes).
static Operand from_index(const Node &n)
Constructs an Operand from the specified node. Will have a type of Index.
static Operand from_value(const Node &n)
Constructs an Operand from the specified node. Will have a type of Value.
Represents a plan in the IR.
Definition rego.hh:1337
Location name
The name of the plan.
Definition rego.hh:1339
std::vector< Block > blocks
The blocks which make up the plan.
Definition rego.hh:1341
Additional information for Call, CallDynamic, With, Block, Not, and Scan statements.
Definition rego.hh:1264
const WithExt & with() const
Returns this extension as a WithExt.
const CallDynamicExt & call_dynamic() const
Returns this extension as a CallDynamicExt.
std::variant< CallExt, CallDynamicExt, WithExt, std::vector< Block >, Block > contents
The contents of the extension.
Definition rego.hh:1267
StatementExt(CallExt &&ext)
Constructs a StatementExt from a CallExt.
const std::vector< Block > & blocks() const
Returns this extension as a vector of Blocks.
const Block & block() const
Returns this extension as a Block.
StatementExt(Block &&block)
Constructs a StatementExt from a Block.
const CallExt & call() const
Returns this extension as a CallExt.
StatementExt(WithExt &&ext)
Constructs a StatementExt from a WithExt.
StatementExt(std::vector< Block > &&blocks)
Constructs a StatementExt from a vector of Blocks.
StatementExt(CallDynamicExt &&ext)
Constructs a StatementExt from a CallDynamicExt.
Represents a single IR statement.
Definition rego.hh:1306
std::int32_t target
The target of the statement.
Definition rego.hh:1319
StatementType type
The type of statement.
Definition rego.hh:1308
std::shared_ptr< const StatementExt > ext
The (optional) extended information for the statement.
Definition rego.hh:1322
Location location
The location of the statement in the source document.
Definition rego.hh:1310
friend std::ostream & operator<<(std::ostream &stream, const Statement &stmt)
Writes the statement to a stream (used for debugging purposes)
Operand op1
The second operand of the statement.
Definition rego.hh:1316
Statement()
Default constructor.
Operand op0
The first operand of the statement.
Definition rego.hh:1313
Additional information for With statements.
Definition rego.hh:1254
std::vector< size_t > path
The path to the value being replaced.
Definition rego.hh:1256
Block block
The block to execute with the replacement.
Definition rego.hh:1258