func CompileRoot(node lexer.ASTNode) (regexps []Regexp, scope Scope, err error) { if !node.IsCommandType(0) { panic("Expecting root node") } regexps = make([]Regexp, 0) scope = NewScope() for _, child := range node.Children() { command := child.Command() switch command.Type { case lexer.CmdAliasDefinition: if scope, err = DefineAlias(*child, scope); err != nil { return regexps, scope, err } case lexer.CmdXExpression: regexp, scope, err := CompileExpression(*child, scope) if err != nil { return regexps, scope, err } regexps = append(regexps, regexp) } } return regexps, scope, err }
func compileExamples(node lexer.ASTNode, scope Scope) (output string, parentScope Scope, err error) { if !node.IsCommandType(lexer.CmdExample) { panic("Expecting example command") } for _, child := range node.Children() { command := child.Command() switch command.Type { case lexer.CmdExampleMatch: scope.CurrentRegexp.Examples = append(scope.CurrentRegexp.Examples, NewExample(true, command.Comment, child.Line())) case lexer.CmdExampleNonMatch: scope.CurrentRegexp.Examples = append(scope.CurrentRegexp.Examples, NewExample(false, command.Comment, child.Line())) } } return "", scope, nil }
func compileSelect(node lexer.ASTNode, scope Scope) (output string, parentScope Scope, err error) { cases := make([]string, len(node.Children())) for i, child := range node.Children() { if !child.IsCommandType(lexer.CmdCase) { return "", scope, child.Line().Error("Only 'Case' statements are valid inside a 'Select' statement") } if cases[i], scope, err = compileNodeChildren(*child, scope); err != nil { return "", scope, err } } // Join the cases with pipes and put it all into a non-capture group output = fmt.Sprintf("(?:%s)", strings.Join(cases, "|")) return output, scope, nil }
func compileNodeChildren(node lexer.ASTNode, scope Scope) (output string, parentScope Scope, err error) { for _, child := range node.Children() { childOutput := "" command := child.Command() switch child.Command().Type { case lexer.CmdDescription: scope.CurrentRegexp.Description = command.Comment case lexer.CmdLiteral: if childOutput, scope, err = compileLiteral(*child, scope); err != nil { return "", scope, child.Line().Error(err.Error()) } case lexer.CmdAliasCall: if childOutput, err = callAlias(command.Value, scope); err != nil { return "", scope, child.Line().Error(err.Error()) } case lexer.CmdGroup: if childOutput, scope, err = compileGroup(*child, scope); err != nil { return "", scope, err } case lexer.CmdSelect: if childOutput, scope, err = compileSelect(*child, scope); err != nil { return "", scope, err } case lexer.CmdExample: if childOutput, scope, err = compileExamples(*child, scope); err != nil { return "", scope, err } default: if childOutput, scope, err = compileNodeChildren(*child, scope); err != nil { return "", scope, err } } output += childOutput } return output, scope, nil }