Skip to content
This repository was archived by the owner on Sep 10, 2025. It is now read-only.
This repository was archived by the owner on Sep 10, 2025. It is now read-only.

Regex Built In should avoid MustCompile to avoid potential panic #94

@DeadlySurgeon

Description

@DeadlySurgeon

https://github.com/skx/monkey/blob/master/evaluator/stdlib_core.go#L174C59-L175C2

Instead of using MustCompile, you probably should use Compile so you can capture the error and return it. Potentially even caching the regex compiled.

var regexCacheLock sync.Mutex
var regexCache = map[string]*regexp.Regexp{}

func compileRegex(reg string) (*regexp.Regexp, error) {
    regexCacheLock.Lock()
    defer regexCacheLock.Unlock()
  
    reg, ok := regexCache[reg]
    if !ok {
        reg, err = regexp.MustCompile(reg)
        if err != nil {
            return nil, err
        }
        regexCache[reg] = reg
    }
  
    return reg, nil
}

...

// regular expression match
func matchFun(args ...object.Object) object.Object {

    // reg := regexp.MustCompile(args[0].(*object.String).Value)
    // Feel free to replace `compileRegex` with `regexp.Compile` if you dont want to use the cache.
    reg, err := compileRegex(args[0].(*object.String).Value)
    if err != nil {
        return newError("failed to compile regex: %v", err)
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions