| 1 |
// Copyright 2022 Google LLC |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
package repl |
| 16 |
|
| 17 |
import ( |
| 18 |
"errors" |
| 19 |
"fmt" |
| 20 |
"strings" |
| 21 |
|
| 22 |
antlr "github.com/antlr4-go/antlr/v4" |
| 23 |
|
| 24 |
"github.com/google/cel-go/repl/parser" |
| 25 |
|
| 26 |
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" |
| 27 |
) |
| 28 |
|
| 29 |
var ( |
| 30 |
compileUsage = `Compile emits a textproto representation of the compiled expression. |
| 31 |
%compile <expr>` |
| 32 |
|
| 33 |
parseUsage = `Parse emits a textproto representation of the parsed expression. |
| 34 |
%parse <expr>` |
| 35 |
|
| 36 |
declareUsage = `Declare introduces a variable or function for type checking, but |
| 37 |
doesn't define a value for it: |
| 38 |
%declare <identifier> : <type> |
| 39 |
%declare <identifier> (<param_identifier> : <param_type>, ...) : <result-type>` |
| 40 |
|
| 41 |
deleteUsage = `Delete removes a variable or function declaration from the evaluation context. |
| 42 |
%delete <identifier>` |
| 43 |
|
| 44 |
letUsage = `Let introduces a variable or function defined by a sub-CEL expression. |
| 45 |
%let <identifier> (: <type>)? = <expr> |
| 46 |
%let <identifier> (<param_identifier> : <param_type>, ...) : <result-type> -> <expr>` |
| 47 |
|
| 48 |
optionUsage = `Option enables a CEL environment option which enables configuration and |
| 49 |
optional language features. |
| 50 |
%option --container 'google.protobuf' |
| 51 |
%option --extension 'all'` |
| 52 |
|
| 53 |
loadDescriptorsUsage = `LoadDescriptors loads a protobuf descriptor file (google.protobuf.FileDescriptorSet) |
| 54 |
from disk or from a predefined package. Supported packages are "cel-spec-test-types" |
| 55 |
(TestAllTypes) and "google-rpc" (AttributeContext). |
| 56 |
%load_descriptors 'path/to/descriptor_set.binarypb' |
| 57 |
%load_descriptors --pkg 'cel-spec-test-types'` |
| 58 |
|
| 59 |
exitUsage = `Exit terminates the REPL. |
| 60 |
%exit` |
| 61 |
|
| 62 |
helpUsage = `Help prints usage information for the commands supported by the REPL. |
| 63 |
%help` |
| 64 |
|
| 65 |
statusUsage = `Status prints the current state of the REPL session |
| 66 |
%status |
| 67 |
%status --yaml` |
| 68 |
|
| 69 |
configUsage = `Config loads a canned REPL state from a config file |
| 70 |
%configure """%let foo : int = 42""" |
| 71 |
%configure --yaml --file 'path/to/env.yaml'` |
| 72 |
) |
| 73 |
|
| 74 |
type letVarCmd struct { |
| 75 |
identifier string |
| 76 |
typeHint *exprpb.Type |
| 77 |
src string |
| 78 |
} |
| 79 |
|
| 80 |
type letFnCmd struct { |
| 81 |
identifier string |
| 82 |
resultType *exprpb.Type |
| 83 |
params []letFunctionParam |
| 84 |
src string |
| 85 |
} |
| 86 |
|
| 87 |
type delCmd struct { |
| 88 |
identifier string |
| 89 |
} |
| 90 |
|
| 91 |
type simpleCmd struct { |
| 92 |
cmd string |
| 93 |
args []string |
| 94 |
} |
| 95 |
|
| 96 |
type compileCmd struct { |
| 97 |
expr string |
| 98 |
} |
| 99 |
|
| 100 |
type parseCmd struct { |
| 101 |
expr string |
| 102 |
} |
| 103 |
|
| 104 |
type evalCmd struct { |
| 105 |
parseOnly bool |
| 106 |
expr string |
| 107 |
} |
| 108 |
|
| 109 |
// Cmder interface provides normalized command name from a repl command. |
| 110 |
// Command specifics are available via checked type casting to the specific |
| 111 |
// command type. |
| 112 |
type Cmder interface { |
| 113 |
// Cmd returns the normalized name for the command. |
| 114 |
Cmd() string |
| 115 |
} |
| 116 |
|
| 117 |
func (c *letVarCmd) Cmd() string { |
| 118 |
if c.src == "" { |
| 119 |
return "declare" |
| 120 |
} |
| 121 |
return "let" |
| 122 |
} |
| 123 |
|
| 124 |
func (c *letFnCmd) Cmd() string { |
| 125 |
if c.src == "" { |
| 126 |
return "declare" |
| 127 |
} |
| 128 |
return "let" |
| 129 |
} |
| 130 |
|
| 131 |
func (c *delCmd) Cmd() string { |
| 132 |
return "delete" |
| 133 |
} |
| 134 |
|
| 135 |
func (c *simpleCmd) Cmd() string { |
| 136 |
return c.cmd |
| 137 |
} |
| 138 |
|
| 139 |
func (c *compileCmd) Cmd() string { |
| 140 |
return "compile" |
| 141 |
} |
| 142 |
|
| 143 |
func (c *parseCmd) Cmd() string { |
| 144 |
return "parse" |
| 145 |
} |
| 146 |
|
| 147 |
func (c *evalCmd) Cmd() string { |
| 148 |
return "eval" |
| 149 |
} |
| 150 |
|
| 151 |
type commandParseListener struct { |
| 152 |
antlr.DefaultErrorListener |
| 153 |
parser.BaseCommandsListener |
| 154 |
|
| 155 |
errs []error |
| 156 |
cmd Cmder |
| 157 |
usage string |
| 158 |
} |
| 159 |
|
| 160 |
func (c *commandParseListener) reportIssue(e error) { |
| 161 |
c.errs = append(c.errs, e) |
| 162 |
} |
| 163 |
|
| 164 |
// extractSourceText extracts original text from a parse rule match. |
| 165 |
// Preserves original whitespace if possible. |
| 166 |
func extractSourceText(ctx antlr.ParserRuleContext) string { |
| 167 |
if ctx.GetStart() == nil || ctx.GetStop() == nil || |
| 168 |
ctx.GetStart().GetStart() < 0 || ctx.GetStop().GetStop() < 0 { |
| 169 |
// fallback to the normalized parse |
| 170 |
return ctx.GetText() |
| 171 |
} |
| 172 |
s, e := ctx.GetStart().GetStart(), ctx.GetStop().GetStop() |
| 173 |
return ctx.GetStart().GetInputStream().GetText(s, e) |
| 174 |
} |
| 175 |
|
| 176 |
// Parse parses a repl command line into a command object. This provides |
| 177 |
// the normalized command name plus any parsed parameters (e.g. variable names |
| 178 |
// in let statements). |
| 179 |
// |
| 180 |
// An error is returned if the statement isn't well formed. See the parser |
| 181 |
// pacakage for details on the antlr grammar. |
| 182 |
func Parse(line string) (Cmder, error) { |
| 183 |
line = strings.TrimSpace(line) |
| 184 |
listener := &commandParseListener{} |
| 185 |
is := antlr.NewInputStream(line) |
| 186 |
lexer := parser.NewCommandsLexer(is) |
| 187 |
lexer.RemoveErrorListeners() |
| 188 |
lexer.AddErrorListener(listener) |
| 189 |
p := parser.NewCommandsParser(antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)) |
| 190 |
p.RemoveErrorListeners() |
| 191 |
p.AddErrorListener(listener) |
| 192 |
|
| 193 |
antlr.ParseTreeWalkerDefault.Walk(listener, p.StartCommand()) |
| 194 |
|
| 195 |
if len(listener.errs) > 0 { |
| 196 |
errFmt := make([]string, len(listener.errs)) |
| 197 |
for i, err := range listener.errs { |
| 198 |
errFmt[i] = err.Error() |
| 199 |
} |
| 200 |
|
| 201 |
if listener.usage != "" { |
| 202 |
errFmt = append(errFmt, "", "Usage:", listener.usage) |
| 203 |
} |
| 204 |
return nil, fmt.Errorf("invalid command: %v", strings.Join(errFmt, "\n")) |
| 205 |
} |
| 206 |
if listener.cmd.Cmd() == "help" { |
| 207 |
return nil, errors.New(strings.Join([]string{ |
| 208 |
compileUsage, |
| 209 |
parseUsage, |
| 210 |
declareUsage, |
| 211 |
deleteUsage, |
| 212 |
letUsage, |
| 213 |
statusUsage, |
| 214 |
configUsage, |
| 215 |
optionUsage, |
| 216 |
loadDescriptorsUsage, |
| 217 |
helpUsage, |
| 218 |
exitUsage, |
| 219 |
}, "\n\n")) |
| 220 |
} |
| 221 |
return listener.cmd, nil |
| 222 |
} |
| 223 |
|
| 224 |
// ANTLR interface implementations |
| 225 |
|
| 226 |
// Implement antlr ErrorListener interface for syntax errors. |
| 227 |
func (c *commandParseListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol any, line, column int, msg string, e antlr.RecognitionException) { |
| 228 |
c.errs = append(c.errs, fmt.Errorf("(%d:%d) %s", line, column, msg)) |
| 229 |
} |
| 230 |
|
| 231 |
// Implement ANTLR interface for commands listener. |
| 232 |
func (c *commandParseListener) EnterSimple(ctx *parser.SimpleContext) { |
| 233 |
cmd := "undefined" |
| 234 |
if ctx.GetCmd() != nil { |
| 235 |
cmd = ctx.GetCmd().GetText()[1:] |
| 236 |
} |
| 237 |
var args []string |
| 238 |
for _, arg := range ctx.GetArgs() { |
| 239 |
a := arg.GetText() |
| 240 |
if strings.HasPrefix(a, "-") { |
| 241 |
a = "--" + strings.ToLower(strings.TrimLeft(a, "-")) |
| 242 |
} else { |
| 243 |
a = strings.Trim(a, "\"'") |
| 244 |
} |
| 245 |
args = append(args, a) |
| 246 |
|
| 247 |
} |
| 248 |
c.cmd = &simpleCmd{cmd: cmd, args: args} |
| 249 |
} |
| 250 |
|
| 251 |
func (c *commandParseListener) EnterHelp(ctx *parser.HelpContext) { |
| 252 |
c.cmd = &simpleCmd{cmd: "help"} |
| 253 |
} |
| 254 |
|
| 255 |
func (c *commandParseListener) EnterEmpty(ctx *parser.EmptyContext) { |
| 256 |
c.cmd = &simpleCmd{cmd: "null"} |
| 257 |
} |
| 258 |
|
| 259 |
func (c *commandParseListener) EnterLet(ctx *parser.LetContext) { |
| 260 |
c.usage = letUsage |
| 261 |
if ctx.GetFn() != nil { |
| 262 |
c.cmd = &letFnCmd{} |
| 263 |
} else if ctx.GetVar_() != nil { |
| 264 |
c.cmd = &letVarCmd{} |
| 265 |
} else { |
| 266 |
c.errs = append(c.errs, fmt.Errorf("missing declaration in let")) |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
func (c *commandParseListener) EnterDeclare(ctx *parser.DeclareContext) { |
| 271 |
c.usage = declareUsage |
| 272 |
if ctx.GetFn() != nil { |
| 273 |
c.cmd = &letFnCmd{} |
| 274 |
} else if ctx.GetVar_() != nil { |
| 275 |
c.cmd = &letVarCmd{} |
| 276 |
} else { |
| 277 |
c.errs = append(c.errs, fmt.Errorf("missing declaration in declare")) |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
func (c *commandParseListener) ExitDeclare(ctx *parser.DeclareContext) { |
| 282 |
var typeHint *exprpb.Type |
| 283 |
switch cmd := c.cmd.(type) { |
| 284 |
case *letVarCmd: |
| 285 |
typeHint = cmd.typeHint |
| 286 |
case *letFnCmd: |
| 287 |
typeHint = cmd.resultType |
| 288 |
} |
| 289 |
if typeHint == nil { |
| 290 |
c.reportIssue(errors.New("result type required for declare")) |
| 291 |
} |
| 292 |
} |
| 293 |
|
| 294 |
func (c *commandParseListener) EnterDelete(ctx *parser.DeleteContext) { |
| 295 |
c.usage = deleteUsage |
| 296 |
if ctx.GetVar_() == nil && ctx.GetFn() == nil { |
| 297 |
c.reportIssue(errors.New("missing identifier in delete")) |
| 298 |
return |
| 299 |
} |
| 300 |
c.cmd = &delCmd{} |
| 301 |
} |
| 302 |
|
| 303 |
func (c *commandParseListener) EnterCompile(ctx *parser.CompileContext) { |
| 304 |
c.cmd = &compileCmd{} |
| 305 |
} |
| 306 |
|
| 307 |
func (c *commandParseListener) EnterParse(ctx *parser.ParseContext) { |
| 308 |
c.cmd = &parseCmd{} |
| 309 |
} |
| 310 |
|
| 311 |
func (c *commandParseListener) EnterExprCmd(ctx *parser.ExprCmdContext) { |
| 312 |
cmd := &evalCmd{} |
| 313 |
for _, f := range ctx.GetFlags() { |
| 314 |
ft := strings.TrimPrefix(strings.TrimPrefix(f.GetText(), "--"), "-") |
| 315 |
switch ft { |
| 316 |
case "parse-only": |
| 317 |
cmd.parseOnly = true |
| 318 |
default: |
| 319 |
c.reportIssue(fmt.Errorf("unknown or unsupported flag: %q", ft)) |
| 320 |
return |
| 321 |
} |
| 322 |
} |
| 323 |
c.cmd = cmd |
| 324 |
} |
| 325 |
|
| 326 |
func (c *commandParseListener) ExitFnDecl(ctx *parser.FnDeclContext) { |
| 327 |
switch cmd := c.cmd.(type) { |
| 328 |
case *letFnCmd: |
| 329 |
if ctx.GetId() == nil { |
| 330 |
c.reportIssue(errors.New("missing identifier in function declaration")) |
| 331 |
return |
| 332 |
} |
| 333 |
if ctx.GetRType() == nil { |
| 334 |
c.reportIssue(errors.New("missing result type in function declaration")) |
| 335 |
return |
| 336 |
} |
| 337 |
cmd.identifier = ctx.GetId().GetText() |
| 338 |
ty, err := ParseType(ctx.GetRType().GetText()) |
| 339 |
if err != nil { |
| 340 |
c.reportIssue(err) |
| 341 |
} |
| 342 |
for _, p := range ctx.GetParams() { |
| 343 |
if p.GetT() == nil { |
| 344 |
c.reportIssue(errors.New("missing type in function param declaration")) |
| 345 |
continue |
| 346 |
} |
| 347 |
if p.GetPid() == nil { |
| 348 |
c.reportIssue(errors.New("missing identifier in function param declaration")) |
| 349 |
} |
| 350 |
ty, err := ParseType(p.GetT().GetText()) |
| 351 |
if err != nil { |
| 352 |
c.reportIssue(err) |
| 353 |
} |
| 354 |
cmd.params = append(cmd.params, letFunctionParam{ |
| 355 |
identifier: p.GetPid().GetText(), |
| 356 |
typeHint: ty, |
| 357 |
}) |
| 358 |
|
| 359 |
} |
| 360 |
cmd.resultType = ty |
| 361 |
case *delCmd: |
| 362 |
if ctx.GetId() == nil { |
| 363 |
c.reportIssue(errors.New("missing identifier in delete")) |
| 364 |
} |
| 365 |
cmd.identifier = ctx.GetId().GetText() |
| 366 |
default: |
| 367 |
c.reportIssue(errors.New("unexepected function declaration")) |
| 368 |
} |
| 369 |
} |
| 370 |
|
| 371 |
func (c *commandParseListener) ExitQualId(ctx *parser.QualIdContext) { |
| 372 |
if ctx.GetRid() == nil { |
| 373 |
c.reportIssue(errors.New("missing root identifier")) |
| 374 |
} |
| 375 |
} |
| 376 |
|
| 377 |
func (c *commandParseListener) ExitVarDecl(ctx *parser.VarDeclContext) { |
| 378 |
switch cmd := c.cmd.(type) { |
| 379 |
case *letVarCmd: |
| 380 |
if ctx.GetId() == nil { |
| 381 |
c.reportIssue(errors.New("no identifier in variable declaration")) |
| 382 |
return |
| 383 |
} |
| 384 |
cmd.identifier = ctx.GetId().GetText() |
| 385 |
if ctx.GetT() != nil { |
| 386 |
ty, err := ParseType(ctx.GetT().GetText()) |
| 387 |
if err != nil { |
| 388 |
c.reportIssue(err) |
| 389 |
} |
| 390 |
cmd.typeHint = ty |
| 391 |
} |
| 392 |
case *delCmd: |
| 393 |
if ctx.GetId() == nil { |
| 394 |
c.reportIssue(errors.New("missing identifier in delete")) |
| 395 |
} |
| 396 |
cmd.identifier = ctx.GetId().GetText() |
| 397 |
default: |
| 398 |
c.reportIssue(errors.New("unexpected var declaration")) |
| 399 |
} |
| 400 |
} |
| 401 |
|
| 402 |
func (c *commandParseListener) ExitExpr(ctx *parser.ExprContext) { |
| 403 |
expr := extractSourceText(ctx) |
| 404 |
switch cmd := c.cmd.(type) { |
| 405 |
case *compileCmd: |
| 406 |
cmd.expr = expr |
| 407 |
case *parseCmd: |
| 408 |
cmd.expr = expr |
| 409 |
case *evalCmd: |
| 410 |
cmd.expr = expr |
| 411 |
case *letFnCmd: |
| 412 |
cmd.src = expr |
| 413 |
case *letVarCmd: |
| 414 |
cmd.src = expr |
| 415 |
default: |
| 416 |
c.reportIssue(errors.New("unexpected CEL expression")) |
| 417 |
} |
| 418 |
} |