-
Notifications
You must be signed in to change notification settings - Fork 176
/
astCache.go
53 lines (46 loc) · 1.48 KB
/
astCache.go
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
package fvm
import (
"fmt"
lru "github.com/hashicorp/golang-lru"
"github.com/onflow/cadence/runtime/ast"
"github.com/onflow/cadence/runtime/common"
)
// ASTCache is an interface to a cache for parsed program ASTs.
type ASTCache interface {
GetProgram(common.Location) (*ast.Program, error)
SetProgram(common.Location, *ast.Program) error
}
// LRUASTCache implements a program AST cache with a LRU cache.
type LRUASTCache struct {
lru *lru.Cache
}
// NewLRUASTCache creates a new LRU cache that implements the ASTCache interface.
func NewLRUASTCache(size int) (*LRUASTCache, error) {
lru, err := lru.New(size)
if err != nil {
return nil, fmt.Errorf("failed to create lru cache, %w", err)
}
return &LRUASTCache{
lru: lru,
}, nil
}
// GetProgram retrieves a program AST from the LRU cache.
func (cache *LRUASTCache) GetProgram(location common.Location) (*ast.Program, error) {
program, found := cache.lru.Get(location.ID())
if found {
cachedProgram, ok := program.(*ast.Program)
if !ok {
return nil, fmt.Errorf("could not convert cached value to ast.Program")
}
// Return a new program to clear importedPrograms.
// This will avoid a concurrent map write when attempting to
// resolveImports.
return ast.NewProgram(cachedProgram.Declarations()), nil
}
return nil, nil
}
// SetProgram adds a program AST to the LRU cache.
func (cache *LRUASTCache) SetProgram(location common.Location, program *ast.Program) error {
_ = cache.lru.Add(location.ID(), program)
return nil
}