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
|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package repl
import (
"errors"
"fmt"
"strings"
antlr "github.com/antlr/antlr4/runtime/Go/antlr/v4"
"github.com/google/cel-go/repl/parser"
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
)
var (
compileUsage = `Compile emits a textproto representation of the compiled expression.
%compile <expr>`
declareUsage = `Declare introduces a variable or function for type checking, but
doesn't define a value for it:
%declare <identifier> : <type>
%declare <identifier> (<param_identifier> : <param_type>, ...) : <result-type>`
deleteUsage = `Delete removes a variable or function declaration from the evaluation context.
%delete <identifier>`
letUsage = `Let introduces a variable or function defined by a sub-CEL expression.
%let <identifier> (: <type>)? = <expr>
%let <identifier> (<param_identifier> : <param_type>, ...) : <result-type> -> <expr>`
optionUsage = `Option enables a CEL environment option which enables configuration and
optional language features.
%option --container 'google.protobuf'
%option --extension 'all'`
exitUsage = `Exit terminates the REPL.
%exit`
helpUsage = `Help prints usage information for the commands supported by the REPL.
%help`
)
type letVarCmd struct {
identifier string
typeHint *exprpb.Type
src string
}
type letFnCmd struct {
identifier string
resultType *exprpb.Type
params []letFunctionParam
src string
}
type delCmd struct {
identifier string
}
type simpleCmd struct {
cmd string
args []string
}
type compileCmd struct {
expr string
}
type evalCmd struct {
expr string
}
// Cmder interface provides normalized command name from a repl command.
// Command specifics are available via checked type casting to the specific
// command type.
type Cmder interface {
// Cmd returns the normalized name for the command.
Cmd() string
}
func (c *letVarCmd) Cmd() string {
if c.src == "" {
return "declare"
}
return "let"
}
func (c *letFnCmd) Cmd() string {
if c.src == "" {
return "declare"
}
return "let"
}
func (c *delCmd) Cmd() string {
return "delete"
}
func (c *simpleCmd) Cmd() string {
return c.cmd
}
func (c *compileCmd) Cmd() string {
return "compile"
}
func (c *evalCmd) Cmd() string {
return "eval"
}
type commandParseListener struct {
antlr.DefaultErrorListener
parser.BaseCommandsListener
errs []error
cmd Cmder
usage string
}
func (c *commandParseListener) reportIssue(e error) {
c.errs = append(c.errs, e)
}
// extractSourceText extracts original text from a parse rule match.
// Preserves original whitespace if possible.
func extractSourceText(ctx antlr.ParserRuleContext) string {
if ctx.GetStart() == nil || ctx.GetStop() == nil ||
ctx.GetStart().GetStart() < 0 || ctx.GetStop().GetStop() < 0 {
// fallback to the normalized parse
return ctx.GetText()
}
s, e := ctx.GetStart().GetStart(), ctx.GetStop().GetStop()
return ctx.GetStart().GetInputStream().GetText(s, e)
}
// Parse parses a repl command line into a command object. This provides
// the normalized command name plus any parsed parameters (e.g. variable names
// in let statements).
//
// An error is returned if the statement isn't well formed. See the parser
// pacakage for details on the antlr grammar.
func Parse(line string) (Cmder, error) {
line = strings.TrimSpace(line)
listener := &commandParseListener{}
is := antlr.NewInputStream(line)
lexer := parser.NewCommandsLexer(is)
lexer.RemoveErrorListeners()
lexer.AddErrorListener(listener)
p := parser.NewCommandsParser(antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel))
p.RemoveErrorListeners()
p.AddErrorListener(listener)
antlr.ParseTreeWalkerDefault.Walk(listener, p.StartCommand())
if len(listener.errs) > 0 {
errFmt := make([]string, len(listener.errs))
for i, err := range listener.errs {
errFmt[i] = err.Error()
}
if listener.usage != "" {
errFmt = append(errFmt, "", "Usage:", listener.usage)
}
return nil, fmt.Errorf("invalid command: %v", strings.Join(errFmt, "\n"))
}
if listener.cmd.Cmd() == "help" {
return nil, errors.New(strings.Join([]string{
compileUsage,
declareUsage,
deleteUsage,
letUsage,
optionUsage,
helpUsage,
exitUsage,
}, "\n\n"))
}
return listener.cmd, nil
}
// ANTLR interface implementations
// Implement antlr ErrorListener interface for syntax errors.
func (c *commandParseListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol any, line, column int, msg string, e antlr.RecognitionException) {
c.errs = append(c.errs, fmt.Errorf("(%d:%d) %s", line, column, msg))
}
// Implement ANTLR interface for commands listener.
func (c *commandParseListener) EnterSimple(ctx *parser.SimpleContext) {
cmd := "undefined"
if ctx.GetCmd() != nil {
cmd = ctx.GetCmd().GetText()[1:]
}
var args []string
for _, arg := range ctx.GetArgs() {
a := arg.GetText()
if strings.HasPrefix(a, "-") {
a = "--" + strings.ToLower(strings.TrimLeft(a, "-"))
} else {
a = strings.Trim(a, "\"'")
}
args = append(args, a)
}
c.cmd = &simpleCmd{cmd: cmd, args: args}
}
func (c *commandParseListener) EnterHelp(ctx *parser.HelpContext) {
c.cmd = &simpleCmd{cmd: "help"}
}
func (c *commandParseListener) EnterEmpty(ctx *parser.EmptyContext) {
c.cmd = &simpleCmd{cmd: "null"}
}
func (c *commandParseListener) EnterLet(ctx *parser.LetContext) {
c.usage = letUsage
if ctx.GetFn() != nil {
c.cmd = &letFnCmd{}
} else if ctx.GetVar_() != nil {
c.cmd = &letVarCmd{}
} else {
c.errs = append(c.errs, fmt.Errorf("missing declaration in let"))
}
}
func (c *commandParseListener) EnterDeclare(ctx *parser.DeclareContext) {
c.usage = declareUsage
if ctx.GetFn() != nil {
c.cmd = &letFnCmd{}
} else if ctx.GetVar_() != nil {
c.cmd = &letVarCmd{}
} else {
c.errs = append(c.errs, fmt.Errorf("missing declaration in declare"))
}
}
func (c *commandParseListener) ExitDeclare(ctx *parser.DeclareContext) {
var typeHint *exprpb.Type
switch cmd := c.cmd.(type) {
case *letVarCmd:
typeHint = cmd.typeHint
case *letFnCmd:
typeHint = cmd.resultType
}
if typeHint == nil {
c.reportIssue(errors.New("result type required for declare"))
}
}
func (c *commandParseListener) EnterDelete(ctx *parser.DeleteContext) {
c.usage = deleteUsage
if ctx.GetVar_() == nil && ctx.GetFn() == nil {
c.reportIssue(errors.New("missing identifier in delete"))
return
}
c.cmd = &delCmd{}
}
func (c *commandParseListener) EnterCompile(ctx *parser.CompileContext) {
c.cmd = &compileCmd{}
}
func (c *commandParseListener) EnterExprCmd(ctx *parser.ExprCmdContext) {
c.cmd = &evalCmd{}
}
func (c *commandParseListener) ExitFnDecl(ctx *parser.FnDeclContext) {
switch cmd := c.cmd.(type) {
case *letFnCmd:
if ctx.GetId() == nil {
c.reportIssue(errors.New("missing identifier in function declaration"))
return
}
if ctx.GetRType() == nil {
c.reportIssue(errors.New("missing result type in function declaration"))
return
}
cmd.identifier = ctx.GetId().GetText()
ty, err := ParseType(ctx.GetRType().GetText())
if err != nil {
c.reportIssue(err)
}
for _, p := range ctx.GetParams() {
if p.GetT() == nil {
c.reportIssue(errors.New("missing type in function param declaration"))
continue
}
if p.GetPid() == nil {
c.reportIssue(errors.New("missing identifier in function param declaration"))
}
ty, err := ParseType(p.GetT().GetText())
if err != nil {
c.reportIssue(err)
}
cmd.params = append(cmd.params, letFunctionParam{
identifier: p.GetPid().GetText(),
typeHint: ty,
})
}
cmd.resultType = ty
case *delCmd:
if ctx.GetId() == nil {
c.reportIssue(errors.New("missing identifier in delete"))
}
cmd.identifier = ctx.GetId().GetText()
default:
c.reportIssue(errors.New("unexepected function declaration"))
}
}
func (c *commandParseListener) ExitQualId(ctx *parser.QualIdContext) {
if ctx.GetRid() == nil {
c.reportIssue(errors.New("missing root identifier"))
}
}
func (c *commandParseListener) ExitVarDecl(ctx *parser.VarDeclContext) {
switch cmd := c.cmd.(type) {
case *letVarCmd:
if ctx.GetId() == nil {
c.reportIssue(errors.New("no identifier in variable declaration"))
return
}
cmd.identifier = ctx.GetId().GetText()
if ctx.GetT() != nil {
ty, err := ParseType(ctx.GetT().GetText())
if err != nil {
c.reportIssue(err)
}
cmd.typeHint = ty
}
case *delCmd:
if ctx.GetId() == nil {
c.reportIssue(errors.New("missing identifier in delete"))
}
cmd.identifier = ctx.GetId().GetText()
default:
c.reportIssue(errors.New("unexpected var declaration"))
}
}
func (c *commandParseListener) ExitExpr(ctx *parser.ExprContext) {
expr := extractSourceText(ctx)
switch cmd := c.cmd.(type) {
case *compileCmd:
cmd.expr = expr
case *evalCmd:
cmd.expr = expr
case *letFnCmd:
cmd.src = expr
case *letVarCmd:
cmd.src = expr
default:
c.reportIssue(errors.New("unexpected CEL expression"))
}
}
|