Skip to content

Compile a rule and scan data

Docs for v0.11.1 · Go 1.27.0+ · Go API

Compile the rule once, scan a byte slice, and read the matching rule names from the result. This example looks for hello, ignoring case.

Run go-yara v0.11.1 locally in your browser. Rules and input bytes are not uploaded. The first scan downloads a 12.9 MiB runtime.

Selecting an example replaces the rules and input without starting a scan.

The greeting rule finds hello regardless of case.

Scanner not loaded.

Playground limits

16 KiB of rule source, 1 MiB of input, and three seconds for compilation and scanning. Each scan uses a fresh worker with a hard 128 MiB Wasm linear-memory ceiling and a soft 64 MiB Go runtime memory target. Browser and JavaScript overhead are additional; this is not a total tab-memory limit.

Results show at most 100 rule names and 200 occurrences, within 64 KiB of result JSON. Evidence copies at most 256 bytes per capture inside the worker and displays at most 20 findings and 80 field rows. These share the same result JSON budget. Display truncation happens after condition evaluation and correlation. If a scan runs out of time or memory, it produces no complete result. Cancellation discards the worker; browser timer delays can affect when it stops.

Select an example for text, hex, occurrence counts, a false condition, or credential evidence. Selection fills the editors; Compile and scan starts the local worker. The evidence examples show ready, partial, ambiguous, and truncated captures. Captured values are redacted before leaving the worker; field names, byte spans, and extraction status remain visible. The input editor still contains the original text.

The playground does not validate credentials or contact services. The credential evidence examples show how a Go application can pass complete findings to a separate validator.

With Go installed, create an empty directory and add go-yara:

Terminal window
mkdir yara-example
cd yara-example
go mod init example.com/yara-example
go get github.com/cawalch/go-yara/compiler@v0.11.1

See installation for the required Go version and CLI downloads.

Save this as main.go:

main.go
package main
import (
"context"
"fmt"
"log"
"github.com/cawalch/go-yara/compiler"
)
func main() {
program, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), `
rule greeting {
strings:
$text = "hello" nocase
condition:
$text
}`)
if err != nil {
log.Fatal(err)
}
result, err := program.Scan([]byte("Hello from Go"))
if err != nil {
log.Fatal(err)
}
for _, match := range result.MatchedRules {
fmt.Println(match.Rule)
}
}

Run it:

Terminal window
go run .

The output is:

greeting

The rule matches because the input contains Hello. Changing the input to Goodbye produces no output. Compilation and scanning return separate errors; handle both in application code.

Keep the compiled program when scanning more than one input. Its convenience methods manage pooled scanners, and the program supports concurrent scans. For custom options or repeated scans in one worker, create a reusable scanner.

Use CompileFileWithContext(ctx, path) for a rule file. Relative include paths resolve from the containing file’s directory. For source strings containing relative includes, set the compiler’s base directory with SetBaseDir before compilation. import makes a registered module namespace available to the rules; include loads another rule file.

Compilation normally fails on an invalid rule. For an ingestion workflow that deliberately accepts a reduced rule set, WithIgnoreInvalidRules(true) keeps valid rules and reports omissions through GetIgnoredRules. Dependencies on rejected rules are omitted too; an invalid global rule can therefore remove otherwise valid rules. Fatal program-level errors still return an error.

Complete Go example: inspect omitted rules and their dependents
main.go
package main
import (
"context"
"fmt"
"log"
"sort"
"github.com/cawalch/go-yara/compiler"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
const source = `
rule broken { condition: missing_identifier }
rule dependent { condition: broken }
rule good { condition: true }`
_, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), source)
fmt.Printf("strict compilation fails: %t\n", err != nil)
c := compiler.NewCompiler(compiler.WithIgnoreInvalidRules(true))
program, err := c.CompileSourceWithContext(context.Background(), source)
if err != nil {
return err
} // Fatal errors still stop compilation.
ignored := c.GetIgnoredRules()
sort.Slice(ignored, func(i, j int) bool { return ignored[i].Rule < ignored[j].Rule })
for _, diagnostic := range ignored {
fmt.Printf("omitted: %s\n", diagnostic.Rule)
// A diagnostic also carries Phase, Message, Line, and Column for reports.
}
matches, err := program.MatchingRules(nil)
if err != nil {
return err
}
for _, match := range matches {
fmt.Printf("matched: %s\n", match.Rule)
}
return nil
}
Output
strict compilation fails: true
omitted: broken
omitted: dependent
matched: good

Inspect each diagnostic’s Phase, Message, Line, Column, and dependency information before accepting the resulting program. A successful tolerant compile does not mean every submitted rule is active. Keep strict compilation for workflows that require the whole rule set.

Compilation checks the meaning of a parsed rule before producing an executable program. The semantic layer resolves identifiers and rule references, checks operator and function argument types, validates module fields against registered schemas, and rejects circular rule dependencies. Capture-group references and evidence declarations are checked here too.

Compile-time checks
  1. Parse sourceBuild an AST; resolve includes and imports
  2. Validate meaningNames, types, module signatures, dependencies, evidence
  3. Compile programSearch plans and condition bytecode
Accepted types do not guarantee defined values for every input. Runtime conditions still evaluate bytes, occurrences, and bound module data.

Forward references to other rules are allowed; dependency cycles are rejected. A well-typed rule can still encounter undefined values when it runs. For example, string.to_int("oops") is a valid function call whose result is undefined. Use defined when the condition needs to distinguish that case. Semantic analysis does not inspect future input bytes or establish whether an extracted credential works.

Complete Go example: inspect semantic diagnostics and runtime undefined values
main.go
package main
import (
"context"
"errors"
"fmt"
"log"
"github.com/cawalch/go-yara/compiler"
"github.com/cawalch/go-yara/semantic"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
cases := []struct{ name, source string }{
{"forward reference", `rule first { condition: second } rule second { condition: true }`},
{"unknown name", `rule bad { condition: missing_identifier }`},
{"argument type", `import "math" rule bad { condition: math.in_range("x", 0.0, 1.0) }`},
{"dependency cycle", `rule first { condition: second } rule second { condition: first }`},
{"capture group", `rule bad { strings: $a = /(a)/ capture(value = 2) condition: $a }`},
}
for _, example := range cases {
c := compiler.NewCompiler()
_, err := c.CompileSourceWithContext(context.Background(), example.source)
if err == nil {
fmt.Printf("%s: accepted\n", example.name)
continue
}
var diagnostic *semantic.Error
if !errors.As(err, &diagnostic) {
return err
}
fmt.Printf("%s: %s\n", example.name, diagnostic.Code)
// GetErrors returns all compiler diagnostics, with Phase, Code, Line,
// Column, and Message. The wrapped semantic.Error above is the first.
for _, item := range c.GetErrors() {
if item.Phase != "semantic" || item.Line < 1 || item.Column < 1 {
return fmt.Errorf("missing semantic diagnostic location (phase=%s line=%d col=%d): %w", item.Phase, item.Line, item.Column, item)
}
}
}
// A well-typed call can still produce undefined for a particular value.
program, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), `
import "string"
rule conversion { condition: defined string.to_int("oops") }`)
if err != nil {
return err
}
matched, err := program.Matches(nil)
if err != nil {
return err
}
fmt.Printf("runtime conversion: compiled=true defined=%t\n", matched)
return nil
}
Output
forward reference: accepted
unknown name: undefined-identifier
argument type: invalid-argument-type
dependency cycle: circular-dependency
capture group: invalid-evidence
runtime conversion: compiled=true defined=false

Compiler.GetErrors() exposes compiler diagnostics with Phase, Code, Message, Line, and Column. For semantic failures, the returned error wraps the first semantic.Error; errors.As retrieves its code, position, rule, and optional suggestion. Use structured codes for classification and the message for display. Parsing and later compilation failures do not necessarily wrap a semantic error.

Most applications should compile through compiler, which resolves includes and supplies the registered module signatures and schemas to the validator. The exported semantic.Validator also accepts an AST for tooling that already owns one. A standalone validator needs the applicable module definitions; semantic.NewValidator() does not populate the compiler’s built-in module registry.

See the semantic error reference and compiler diagnostic reference. Custom field types and function signatures are described under modules and host data.