MCPcopy Create free account
hub / github.com/cel-expr/cel-go / CreateAST

Method CreateAST

tools/compiler/compiler.go:497–545  ·  view source on GitHub ↗

CreateAST creates a CEL AST from a file using the provided compiler: - All policy metadata options are executed using the policy metadata map to extend the environment. - All policy compiler options are passed on to compile the parsed policy. The file must be in one of the following formats: - .cel

(compiler Compiler)

Source from the content-addressed store, hash-verified

495// - .cel: CEL string expression
496// - .celpolicy: CEL policy
497func (f *FileExpression) CreateAST(compiler Compiler) (*cel.Ast, map[string]any, error) {
498 e, err := compiler.CreateEnv()
499 if err != nil {
500 return nil, nil, err
501 }
502 format := InferFileFormat(f.Path)
503 switch format {
504 case CELString:
505 data, err := loadFile(f.Path)
506 if err != nil {
507 return nil, nil, err
508 }
509 src := common.NewStringSource(string(data), f.Path)
510 ast, iss := e.CompileSource(src)
511 if iss.Err() != nil {
512 return nil, nil, fmt.Errorf("e.CompileSource(%q) failed: %w", src.Content(), iss.Err())
513 }
514 return ast, nil, nil
515 case CELPolicy, TextYAML:
516 data, err := loadFile(f.Path)
517 if err != nil {
518 return nil, nil, err
519 }
520 src := policy.ByteSource(data, f.Path)
521 parser, err := compiler.CreatePolicyParser()
522 if err != nil {
523 return nil, nil, err
524 }
525 p, iss := parser.Parse(src)
526 if iss.Err() != nil {
527 return nil, nil, fmt.Errorf("parser.Parse(%q) failed: %w", src.Content(), iss.Err())
528 }
529 policyMetadata := clonePolicyMetadata(p)
530 if meta, ok := compiler.(CustomMetadataCompiler); ok {
531 for _, opt := range meta.PolicyMetadataEnvOptions() {
532 if e, err = e.Extend(opt(policyMetadata)); err != nil {
533 return nil, nil, fmt.Errorf("e.Extend() with metadata option failed: %w", err)
534 }
535 }
536 }
537 ast, iss := policy.Compile(e, p, compiler.PolicyCompilerOptions()...)
538 if iss.Err() != nil {
539 return nil, nil, fmt.Errorf("policy.Compile(%q) failed: %w", src.Content(), iss.Err())
540 }
541 return ast, policyMetadata, nil
542 default:
543 return nil, nil, fmt.Errorf("invalid file extension wanted: .cel or .celpolicy or .yaml found: %v", format)
544 }
545}
546
547func clonePolicyMetadata(p *policy.Policy) map[string]any {
548 metadataKeys := p.MetadataKeys()

Callers 1

Calls 15

NewStringSourceFunction · 0.92
ByteSourceFunction · 0.92
CompileFunction · 0.92
InferFileFormatFunction · 0.85
loadFileFunction · 0.85
clonePolicyMetadataFunction · 0.85
CompileSourceMethod · 0.80
ErrMethod · 0.80
CreateEnvMethod · 0.65
ContentMethod · 0.65
CreatePolicyParserMethod · 0.65
ParseMethod · 0.65

Tested by 1