-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
repl.go
1368 lines (1103 loc) · 28.9 KB
/
repl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
// Package repl implements a Read-Eval-Print-Loop (REPL) for interacting with the policy engine.
//
// The REPL is typically used from the command line, however, it can also be used as a library.
package repl
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"strconv"
"strings"
"github.com/peterh/liner"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/format"
pr "github.com/open-policy-agent/opa/internal/presentation"
"github.com/open-policy-agent/opa/metrics"
"github.com/open-policy-agent/opa/profiler"
"github.com/open-policy-agent/opa/rego"
"github.com/open-policy-agent/opa/storage"
"github.com/open-policy-agent/opa/topdown"
"github.com/open-policy-agent/opa/topdown/lineage"
)
// REPL represents an instance of the interactive shell.
type REPL struct {
output io.Writer
store storage.Store
runtime *ast.Term
modules map[string]*ast.Module
currentModuleID string
buffer []string
txn storage.Transaction
metrics metrics.Metrics
profiler bool
// TODO(tsandall): replace this state with rule definitions
// inside the default module.
outputFormat string
explain explainMode
instrument bool
historyPath string
initPrompt string
bufferPrompt string
banner string
types bool
unknowns []*ast.Term
bufferDisabled bool
undefinedDisabled bool
errLimit int
prettyLimit int
}
type explainMode string
const (
explainOff explainMode = "off"
explainFull = "full"
explainNotes = "notes"
explainFails = "fails"
)
const defaultPrettyLimit = 80
const exitPromptMessage = "Do you want to exit ([y]/n)? "
// New returns a new instance of the REPL.
func New(store storage.Store, historyPath string, output io.Writer, outputFormat string, errLimit int, banner string) *REPL {
return &REPL{
output: output,
store: store,
modules: map[string]*ast.Module{},
outputFormat: outputFormat,
explain: explainOff,
historyPath: historyPath,
initPrompt: "> ",
bufferPrompt: "| ",
banner: banner,
errLimit: errLimit,
prettyLimit: defaultPrettyLimit,
}
}
func defaultModule() *ast.Module {
return ast.MustParseModule(`package repl`)
}
func defaultPackage() *ast.Package {
return ast.MustParsePackage(`package repl`)
}
func (r *REPL) getCurrentOrDefaultModule() *ast.Module {
if r.currentModuleID == "" {
return defaultModule()
}
return r.modules[r.currentModuleID]
}
func (r *REPL) initModule(ctx context.Context) error {
if r.currentModuleID != "" {
return nil
}
return r.evalStatement(ctx, defaultPackage())
}
// Loop will run until the user enters "exit", Ctrl+C, Ctrl+D, or an unexpected error occurs.
func (r *REPL) Loop(ctx context.Context) {
// Initialize the liner library.
line := liner.NewLiner()
defer line.Close()
line.SetCtrlCAborts(true)
line.SetMultiLineMode(true)
r.loadHistory(line)
if len(r.banner) > 0 {
fmt.Fprintln(r.output, r.banner)
}
line.SetCompleter(r.complete)
loop:
for true {
input, err := line.Prompt(r.getPrompt())
// prompt on ctrl+d
if err == io.EOF {
goto exitPrompt
}
// reset on ctrl+c
if err == liner.ErrPromptAborted {
continue
}
// exit on unknown error
if err != nil {
fmt.Fprintln(r.output, "error (fatal):", err)
os.Exit(1)
}
if err := r.OneShot(ctx, input); err != nil {
switch err := err.(type) {
case stop:
goto exit
default:
fmt.Fprintln(r.output, err)
}
}
line.AppendHistory(input)
}
exitPrompt:
fmt.Fprintln(r.output)
for true {
input, err := line.Prompt(exitPromptMessage)
// exit on ctrl+d
if err == io.EOF {
break
}
// reset on ctrl+c
if err == liner.ErrPromptAborted {
goto loop
}
// exit on unknown error
if err != nil {
fmt.Fprintln(r.output, "error (fatal):", err)
os.Exit(1)
}
switch strings.ToLower(input) {
case "", "y", "yes":
goto exit
case "n", "no":
goto loop
}
}
exit:
r.saveHistory(line)
}
// OneShot evaluates the line and prints the result. If an error occurs it is
// returned for the caller to display.
func (r *REPL) OneShot(ctx context.Context, line string) error {
var err error
r.txn, err = r.store.NewTransaction(ctx)
if err != nil {
return err
}
defer r.store.Abort(ctx, r.txn)
if r.metrics != nil {
defer r.metrics.Clear()
}
if len(r.buffer) == 0 {
if cmd := newCommand(line); cmd != nil {
switch cmd.op {
case "dump":
return r.cmdDump(ctx, cmd.args)
case "json":
return r.cmdFormat("json")
case "show":
return r.cmdShow(cmd.args)
case "unset":
return r.cmdUnset(ctx, cmd.args)
case "pretty":
return r.cmdFormat("pretty")
case "pretty-limit":
return r.cmdPrettyLimit(cmd.args)
case "trace":
return r.cmdTrace(explainFull)
case "notes":
return r.cmdTrace(explainNotes)
case "fails":
return r.cmdTrace(explainFails)
case "metrics":
return r.cmdMetrics()
case "instrument":
return r.cmdInstrument()
case "profile":
return r.cmdProfile()
case "types":
return r.cmdTypes()
case "unknown":
return r.cmdUnknown(cmd.args)
case "help":
return r.cmdHelp(cmd.args)
case "exit":
return r.cmdExit()
}
}
r.buffer = append(r.buffer, line)
return r.evalBufferOne(ctx)
}
r.buffer = append(r.buffer, line)
if len(line) == 0 {
return r.evalBufferMulti(ctx)
}
return nil
}
// DisableMultiLineBuffering causes the REPL to not buffer lines when a parse
// error occurs. Instead, the error will be returned to the caller.
func (r *REPL) DisableMultiLineBuffering(yes bool) *REPL {
r.bufferDisabled = yes
return r
}
// DisableUndefinedOutput causes the REPL to not print any output when the query
// is undefined.
func (r *REPL) DisableUndefinedOutput(yes bool) *REPL {
r.undefinedDisabled = yes
return r
}
// WithRuntime sets the runtime data to provide to the evaluation engine.
func (r *REPL) WithRuntime(term *ast.Term) *REPL {
r.runtime = term
return r
}
func (r *REPL) complete(line string) []string {
c := []string{}
set := map[string]struct{}{}
ctx := context.Background()
txn, err := r.store.NewTransaction(ctx)
if err != nil {
fmt.Fprintln(r.output, "error:", err)
return c
}
defer r.store.Abort(ctx, txn)
// add imports
for _, mod := range r.modules {
for _, imp := range mod.Imports {
path := imp.Name().String()
if strings.HasPrefix(path, line) {
set[path] = struct{}{}
}
}
}
// add virtual docs defined in repl
for _, mod := range r.modules {
for _, rule := range mod.Rules {
path := rule.Path().String()
if strings.HasPrefix(path, line) {
set[path] = struct{}{}
}
}
}
mods, err := r.loadModules(ctx, txn)
if err != nil {
fmt.Fprintln(r.output, "error:", err)
return c
}
// add virtual docs defined by policies
for _, mod := range mods {
for _, rule := range mod.Rules {
path := rule.Path().String()
if strings.HasPrefix(path, line) {
set[path] = struct{}{}
}
}
}
for path := range set {
c = append(c, path)
}
return c
}
func (r *REPL) cmdDump(ctx context.Context, args []string) error {
if len(args) == 0 {
return r.cmdDumpOutput(ctx)
}
return r.cmdDumpPath(ctx, args[0])
}
func (r *REPL) cmdDumpOutput(ctx context.Context) error {
return dumpStorage(ctx, r.store, r.txn, r.output)
}
func (r *REPL) cmdDumpPath(ctx context.Context, filename string) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
return dumpStorage(ctx, r.store, r.txn, f)
}
func (r *REPL) cmdExit() error {
return stop{}
}
func (r *REPL) cmdFormat(s string) error {
r.outputFormat = s
return nil
}
func (r *REPL) cmdPrettyLimit(s []string) error {
if len(s) != 1 {
return fmt.Errorf("usage: pretty-limit <n>")
}
i64, err := strconv.ParseInt(s[0], 10, 0)
if err != nil {
return err
}
r.prettyLimit = int(i64)
return nil
}
func (r *REPL) cmdHelp(args []string) error {
if len(args) == 0 {
printHelp(r.output, r.initPrompt)
} else {
if desc, ok := topics[args[0]]; ok {
return desc.fn(r.output)
}
return fmt.Errorf("unknown topic '%v'", args[0])
}
return nil
}
func (r *REPL) cmdShow(args []string) error {
if len(args) == 0 {
if r.currentModuleID == "" {
fmt.Fprintln(r.output, "no rules defined")
return nil
}
module := r.modules[r.currentModuleID]
bs, err := format.Ast(module)
if err != nil {
return err
}
fmt.Fprint(r.output, string(bs))
return nil
} else if strings.Compare(args[0], "debug") == 0 {
debug := replDebugState{
Explain: r.explain,
Metrics: r.metricsEnabled(),
Instrument: r.instrument,
Profile: r.profilerEnabled(),
}
b, err := json.MarshalIndent(debug, "", "\t")
if err != nil {
return fmt.Errorf("error: %v", err)
}
fmt.Fprintln(r.output, string(b))
return nil
} else {
return fmt.Errorf("unknown option '%v'", args[0])
}
}
type replDebugState struct {
Explain explainMode `json:"explain"`
Metrics bool `json:"metrics"`
Instrument bool `json:"instrument"`
Profile bool `json:"profile"`
}
func (r *REPL) cmdTrace(mode explainMode) error {
if r.explain == mode {
r.explain = explainOff
} else {
r.explain = mode
}
return nil
}
func (r *REPL) metricsEnabled() bool {
if r.metrics != nil {
return true
}
return false
}
func (r *REPL) cmdMetrics() error {
if r.metrics == nil {
r.metrics = metrics.New()
} else {
r.metrics = nil
}
r.instrument = false
return nil
}
func (r *REPL) cmdInstrument() error {
if r.instrument {
r.metrics = nil
r.instrument = false
} else {
r.metrics = metrics.New()
r.instrument = true
}
return nil
}
func (r *REPL) profilerEnabled() bool {
return r.profiler
}
func (r *REPL) cmdProfile() error {
if r.profiler {
r.profiler = false
} else {
r.profiler = true
}
return nil
}
func (r *REPL) cmdTypes() error {
r.types = !r.types
return nil
}
var errUnknownUsage = fmt.Errorf("usage: unknown <input/data reference> [<input/data reference> [...]] (hint: try 'input')")
func (r *REPL) cmdUnknown(s []string) error {
if len(s) == 0 && len(r.unknowns) == 0 {
return errUnknownUsage
}
unknowns := make([]*ast.Term, len(s))
for i := range unknowns {
ref, err := ast.ParseRef(s[i])
if err != nil {
return errUnknownUsage
}
unknowns[i] = ast.NewTerm(ref)
}
r.unknowns = unknowns
return nil
}
func (r *REPL) cmdUnset(ctx context.Context, args []string) error {
if len(args) != 1 {
return newBadArgsErr("unset <var>: expects exactly one argument")
}
term, err := ast.ParseTerm(args[0])
if err != nil {
return newBadArgsErr("argument must identify a rule")
}
v, ok := term.Value.(ast.Var)
if !ok {
ref, ok := term.Value.(ast.Ref)
if !ok || !ast.RootDocumentNames.Contains(ref[0]) {
return newBadArgsErr("arguments must identify a rule")
}
v = ref[0].Value.(ast.Var)
}
unset, err := r.unsetRule(ctx, v)
if err != nil {
return err
} else if !unset {
fmt.Fprintln(r.output, "warning: no matching rules in current module")
}
return nil
}
func (r *REPL) unsetRule(ctx context.Context, name ast.Var) (bool, error) {
if r.currentModuleID == "" {
return false, nil
}
mod := r.modules[r.currentModuleID]
rules := []*ast.Rule{}
for _, r := range mod.Rules {
if !r.Head.Name.Equal(name) {
rules = append(rules, r)
}
}
if len(rules) == len(mod.Rules) {
return false, nil
}
cpy := mod.Copy()
cpy.Rules = rules
err := r.recompile(ctx, cpy)
if err != nil {
return false, err
}
return true, nil
}
func (r *REPL) timerStart(msg string) {
if r.metrics != nil {
r.metrics.Timer(msg).Start()
}
}
func (r *REPL) timerStop(msg string) {
if r.metrics != nil {
r.metrics.Timer(msg).Stop()
}
}
func (r *REPL) recompile(ctx context.Context, cpy *ast.Module) error {
policies, err := r.loadModules(ctx, r.txn)
if err != nil {
return err
}
policies[r.currentModuleID] = cpy
for id, mod := range r.modules {
if id != r.currentModuleID {
policies[id] = mod
}
}
compiler := ast.NewCompiler().SetErrorLimit(r.errLimit)
if r.instrument {
compiler.WithMetrics(r.metrics)
}
if compiler.Compile(policies); compiler.Failed() {
return compiler.Errors
}
r.modules[r.currentModuleID] = cpy
return nil
}
func (r *REPL) compileBody(ctx context.Context, compiler *ast.Compiler, body ast.Body) (ast.Body, *ast.TypeEnv, error) {
r.timerStart(metrics.RegoQueryCompile)
defer r.timerStop(metrics.RegoQueryCompile)
qctx := ast.NewQueryContext()
if r.currentModuleID != "" {
qctx = qctx.WithPackage(r.modules[r.currentModuleID].Package).WithImports(r.modules[r.currentModuleID].Imports)
}
qc := compiler.QueryCompiler()
body, err := qc.WithContext(qctx).Compile(body)
return body, qc.TypeEnv(), err
}
func (r *REPL) compileRule(ctx context.Context, rule *ast.Rule) error {
var unset bool
if rule.Head.Assign {
var err error
unset, err = r.unsetRule(ctx, rule.Head.Name)
if err != nil {
return err
}
}
r.timerStart(metrics.RegoModuleCompile)
defer r.timerStop(metrics.RegoModuleCompile)
if err := r.initModule(ctx); err != nil {
return err
}
mod := r.modules[r.currentModuleID]
prev := mod.Rules
mod.Rules = append(mod.Rules, rule)
ast.WalkRules(rule, func(r *ast.Rule) bool {
r.Module = mod
return false
})
policies, err := r.loadModules(ctx, r.txn)
if err != nil {
return err
}
for id, mod := range r.modules {
policies[id] = mod
}
compiler := ast.NewCompiler().SetErrorLimit(r.errLimit)
if r.instrument {
compiler.WithMetrics(r.metrics)
}
if compiler.Compile(policies); compiler.Failed() {
mod.Rules = prev
return compiler.Errors
}
switch r.outputFormat {
case "json":
default:
var msg string
if unset {
msg = "re-defined"
} else {
msg = "defined"
}
fmt.Fprintf(r.output, "Rule '%v' %v in %v. Type 'show' to see rules.\n", rule.Head.Name, msg, mod.Package)
}
return nil
}
func (r *REPL) evalBufferOne(ctx context.Context) error {
line := strings.Join(r.buffer, "\n")
if len(strings.TrimSpace(line)) == 0 {
r.buffer = []string{}
return nil
}
// The user may enter lines with comments on the end or
// multiple lines with comments interspersed. In these cases
// the parser will return multiple statements.
r.timerStart(metrics.RegoQueryParse)
stmts, _, err := ast.ParseStatements("", line)
r.timerStop(metrics.RegoQueryParse)
if err != nil {
if r.bufferDisabled {
return err
}
return nil
}
r.buffer = []string{}
for _, stmt := range stmts {
if err := r.evalStatement(ctx, stmt); err != nil {
return err
}
}
return nil
}
func (r *REPL) evalBufferMulti(ctx context.Context) error {
line := strings.Join(r.buffer, "\n")
r.buffer = []string{}
if len(strings.TrimSpace(line)) == 0 {
return nil
}
r.timerStart(metrics.RegoQueryParse)
stmts, _, err := ast.ParseStatements("", line)
r.timerStop(metrics.RegoQueryParse)
if err != nil {
return err
}
for _, stmt := range stmts {
if err := r.evalStatement(ctx, stmt); err != nil {
return err
}
}
return nil
}
func (r *REPL) loadCompiler(ctx context.Context) (*ast.Compiler, error) {
r.timerStart(metrics.RegoModuleCompile)
defer r.timerStop(metrics.RegoModuleCompile)
policies, err := r.loadModules(ctx, r.txn)
if err != nil {
return nil, err
}
for id, mod := range r.modules {
policies[id] = mod
}
compiler := ast.NewCompiler().SetErrorLimit(r.errLimit)
if r.instrument {
compiler.WithMetrics(r.metrics)
}
if compiler.Compile(policies); compiler.Failed() {
return nil, compiler.Errors
}
return compiler, nil
}
// loadInput returns the input defined in the REPL. The REPL loads the
// input from the data.repl.input document.
func (r *REPL) loadInput(ctx context.Context, compiler *ast.Compiler) (ast.Value, error) {
q := topdown.NewQuery(ast.MustParseBody("data.repl.input = x")).
WithCompiler(compiler).
WithStore(r.store).
WithTransaction(r.txn)
qrs, err := q.Run(ctx)
if err != nil {
return nil, err
}
if len(qrs) != 1 {
return nil, nil
}
return qrs[0][ast.Var("x")].Value, nil
}
func (r *REPL) evalStatement(ctx context.Context, stmt interface{}) error {
switch stmt := stmt.(type) {
case ast.Body:
compiler, err := r.loadCompiler(ctx)
if err != nil {
return err
}
input, err := r.loadInput(ctx, compiler)
if err != nil {
return err
}
if ok, err := r.interpretAsRule(ctx, compiler, stmt); ok || err != nil {
return err
}
compiledBody, typeEnv, err := r.compileBody(ctx, compiler, stmt)
if err != nil {
return err
}
if len(r.unknowns) > 0 {
err = r.evalPartial(ctx, compiler, input, compiledBody)
} else {
err = r.evalBody(ctx, compiler, input, stmt)
if r.types {
r.printTypes(ctx, typeEnv, compiledBody)
}
}
return err
case *ast.Rule:
return r.compileRule(ctx, stmt)
case *ast.Import:
return r.evalImport(ctx, stmt)
case *ast.Package:
return r.evalPackage(stmt)
}
return nil
}
func (r *REPL) evalBody(ctx context.Context, compiler *ast.Compiler, input ast.Value, body ast.Body) error {
var tracebuf *topdown.BufferTracer
var prof *profiler.Profiler
args := []func(*rego.Rego){
rego.Compiler(compiler),
rego.Store(r.store),
rego.Transaction(r.txn),
rego.ParsedImports(r.getCurrentOrDefaultModule().Imports),
rego.ParsedPackage(r.getCurrentOrDefaultModule().Package),
rego.ParsedQuery(body),
rego.ParsedInput(input),
rego.Metrics(r.metrics),
rego.Instrument(r.instrument),
rego.Runtime(r.runtime),
}
if r.explain != explainOff {
tracebuf = topdown.NewBufferTracer()
args = append(args, rego.Tracer(tracebuf))
}
if r.profiler {
prof = profiler.New()
args = append(args, rego.Tracer(prof))
}
eval := rego.New(args...)
rs, err := eval.Eval(ctx)
output := pr.Output{
Errors: pr.NewOutputErrors(err),
Result: rs,
Metrics: r.metrics,
}
if r.profiler {
output.Profile = prof.ReportTopNResults(-1, pr.DefaultProfileSortOrder)
}
output = output.WithLimit(r.prettyLimit)
switch r.explain {
case explainFull:
output.Explanation = *tracebuf
case explainNotes:
output.Explanation = lineage.Notes(*tracebuf)
case explainFails:
output.Explanation = lineage.Fails(*tracebuf)
}
switch r.outputFormat {
case "json":
return pr.JSON(r.output, output)
default:
return pr.Pretty(r.output, output)
}
}
func (r *REPL) evalPartial(ctx context.Context, compiler *ast.Compiler, input ast.Value, body ast.Body) error {
var buf *topdown.BufferTracer
if r.explain != explainOff {
buf = topdown.NewBufferTracer()
}
eval := rego.New(
rego.Compiler(compiler),
rego.Store(r.store),
rego.Transaction(r.txn),
rego.ParsedImports(r.getCurrentOrDefaultModule().Imports),
rego.ParsedPackage(r.getCurrentOrDefaultModule().Package),
rego.ParsedQuery(body),
rego.ParsedInput(input),
rego.Metrics(r.metrics),
rego.Tracer(buf),
rego.Instrument(r.instrument),
rego.ParsedUnknowns(r.unknowns),
rego.Runtime(r.runtime),
)
pq, err := eval.Partial(ctx)
output := pr.Output{
Metrics: r.metrics,
Partial: pq,
Errors: pr.NewOutputErrors(err),
}
switch r.explain {
case explainFull:
output.Explanation = *buf
case explainNotes:
output.Explanation = lineage.Notes(*buf)
case explainFails:
output.Explanation = lineage.Fails(*buf)
}
switch r.outputFormat {
case "json":
return pr.JSON(r.output, output)
default:
return pr.Pretty(r.output, output)
}
}
func (r *REPL) evalImport(ctx context.Context, i *ast.Import) error {
if err := r.initModule(ctx); err != nil {
return err
}
mod := r.modules[r.currentModuleID]
for _, other := range mod.Imports {
if other.Equal(i) {
return nil
}
}
mod.Imports = append(mod.Imports, i)
return nil
}
func (r *REPL) evalPackage(p *ast.Package) error {
moduleID := p.Path.String()
if _, ok := r.modules[moduleID]; ok {
r.currentModuleID = moduleID
return nil
}
r.modules[moduleID] = &ast.Module{
Package: p,
}
r.currentModuleID = moduleID
return nil
}
// interpretAsRule attempts to interpret the supplied query as a rule
// definition. If the query is a single := or = statement and it can be
// converted into a rule and compiled, then it will be interpreted as such. This
// allows users to define constants in the REPL. For example:
//
// > a = 1
// > a
// 1
//
// If the expression is a = statement, then an additional check on the left
// hand side occurs. For example:
//
// > b = 2
// > b = 2
// true # not redefined!
func (r *REPL) interpretAsRule(ctx context.Context, compiler *ast.Compiler, body ast.Body) (bool, error) {
if len(body) != 1 {
return false, nil
}
expr := body[0]