Repository navigation
Expand file tree
/
Copy pathchecker.go
More file actions
264 lines (229 loc) 路 7.27 KB
/
Copy pathchecker.go
File metadata and controls
264 lines (229 loc) 路 7.27 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package analysis
import (
"fmt"
"io"
"maps"
"slices"
"sync"
"github.com/ProCode-Software/klar/internal/ast"
"github.com/ProCode-Software/klar/internal/char"
"github.com/ProCode-Software/klar/internal/config/klarbuild"
"github.com/ProCode-Software/klar/internal/klarerrs"
"github.com/ProCode-Software/klar/internal/target"
"github.com/ProCode-Software/klar/internal/version"
)
type Checker struct {
Programs map[string]*ast.Program // Files in the module that is being checked.
Errors []*klarerrs.Error // Errors reported while type checking.
Options *Options // Options for type checking.
Module *Module
// For tracking cycles
objPath []*Object // Path of object deps
objPathIndex map[*Object]int // Indices of objects in objPath
delayed []action
logger *debugLogger
}
// NewChecker returns an initialized Checker that checks the programs in mod.
// If opts == nil, default options are used.
func NewChecker(mod *Module, files map[string]*ast.Program, opts *Options) *Checker {
c := &Checker{}
c.Init(mod, files, opts)
return c
}
type Options struct {
// The [Importer] to use for importing modules. If set to nil, an error is
// raised when attempting to import a module.
Importer Importer
// The target platform for which the program is being compiled.
// This is needed for resolving platform-specific implementations
// and modules.
// TODO: Support multiple targets
Targets []target.Target
// The minimum version of Klar required to compile the program.
KlarVersion version.Version
// If Error != nil, it is called when an error is reported.
Error func(*klarerrs.Error)
// Whether the program is being typechecked for testing purposes.
IsTest bool
// If MaxErrors > 0, the type checker will terminate when this limit is reached.
MaxErrors int
// Whether to skip type checking function bodies.
IgnoreFuncBodies bool
// Whether to enforce that objects are supported on all targets in [Options.Targets].
EnforceTargetSupport bool
// Type checker options from klar.build
*klarbuild.CheckerOptions
}
// FileID is the numerical identifier for a [*ast.Program].
// - FileID <= -1: Builtin context
// - FileID == 0: Module context
// - FileID >= 1: File context.
type FileID int
func (fid FileID) TopLevel() bool { return fid == 0 }
func (fid FileID) Builtin() bool { return fid < 0 }
var DefaultCheckerOptions = &klarbuild.CheckerOptions{
ValidateExhaustiveness: klarbuild.NoExhaustiveness,
AllowAssertions: klarbuild.AllowAssertions,
ValidateExternals: false,
CheckAllResults: false,
UseAllValues: false,
}
func (c *Checker) Init(mod *Module, files map[string]*ast.Program, opts *Options) {
if opts == nil {
opts = &Options{}
}
if opts.CheckerOptions == nil {
opts.CheckerOptions = DefaultCheckerOptions
}
mod.Info = &Info{
Expressions: make(map[ast.Expression]*Expr),
Blocks: make(map[ast.Node]*stmtContext),
}
c.Module = mod
c.Programs = files
c.Options = opts
c.loadInternalModules()
}
func (c *Checker) Check() {
defer handlePanic()
sortedFiles := slices.Sorted(maps.Keys(c.Programs))
// Initialize contexts for each file
fileContexts := c.initFileContexts(sortedFiles)
// Perform imports
c.performImports(sortedFiles, fileContexts)
// Collect top-level objects in each file and put them in the module
collector := c.collectTopLevelObjects(sortedFiles, fileContexts)
// If we're currently bootstrapping, wrap the declared types to allow
// special operations on them. This must be queued before function bodies.
if c.Module.Flags.Has(BootstrapModule) {
c.queue(c.wrapBootstrapTypes, false)
}
// Check for direct cycles among those objects
c.checkDirectCycles(c.Module.Context)
// Typecheck those declarations, but not function bodies
c.checkContextDecls(c.Module.Context, collector)
// Check if any public declarations are named after JavaScript keywords
if target.Supports(c.Options.Targets, target.JavaScript) {
// TODO: Run in parallel
c.validateJSNames(c.Module.Context.SortedDecls())
// TODO: Ensure fields and methods in all structs aren't named 'constructor'
}
// Run delayed actions, including checking function bodies & top-level statements
c.runDelayed(0)
// Report warnings for unused top-level objects and imports
c.reportTopLevelUnused()
c.ResetState() // Free memory
}
func (c *Checker) initFileContexts(sortedFiles []string) map[string]*Context {
fileContexts := make(map[string]*Context, len(sortedFiles))
c.Module.fileID = make(map[FileID]string, len(sortedFiles))
c.Module.fileContext = make(map[FileID]*Context, len(sortedFiles))
for i, name := range sortedFiles {
i := FileID(i) + 1
c.Module.fileID[i] = name
fileContexts[name] = NewContext(c.Module.Context, i)
c.Module.fileContext[i] = fileContexts[name]
}
return fileContexts
}
func (c *Checker) FileContextOf(fid FileID) *Context { return c.Module.fileContext[fid] }
func (c *Checker) FilePathOf(fid FileID) string { return c.Module.ResolveFilePath(fid) }
// Keeps the created type information
func (c *Checker) ResetState() {
c.delayed = nil
c.objPath = nil
c.objPathIndex = nil
}
func (c *Checker) ResetAll() {
c.Module = nil
c.Errors = nil
c.Programs = nil
c.Options = nil
c.logger = nil
}
func (o *Options) NormalizedTargets(yield func(target.Target) bool) {
var hasJS bool
for _, t := range o.Targets {
if t.IsJavaScript() {
if hasJS {
continue
}
t = target.JavaScript
hasJS = true
}
if !yield(t) {
return
}
}
}
func (c *Checker) pushToPath(o *Object) {
if c.objPathIndex == nil {
c.objPathIndex = make(map[*Object]int)
}
c.objPathIndex[o] = len(c.objPath)
c.objPath = append(c.objPath, o)
}
func (c *Checker) popPath() {
i := len(c.objPath) - 1
delete(c.objPathIndex, c.objPath[i])
c.objPath[i] = nil
c.objPath = c.objPath[:i]
}
func (c *Checker) queue(f func(), runInParallel bool) {
c.delayed = append(c.delayed, action{f, runInParallel})
}
type action struct {
f func()
parallel bool
}
// runDelayed runs the delayed actions pushed after from.
func (c *Checker) runDelayed(from int) {
var wg sync.WaitGroup
// Don't use a 'range' loop because delayed functions could push to the stack
for i := from; i < len(c.delayed); i++ {
a := c.delayed[i]
if a.parallel {
// TODO: they could append, so be careful about races
// wg.Go(a.f)
a.f()
} else {
a.f()
}
}
wg.Wait()
c.delayed = c.delayed[:from]
}
func (c *Checker) reportTopLevelUnused() {
// Unused unexported top-level objects
c.reportUnusedWarnings(c.Module.Context)
// Unused imports
for _, fid := range slices.Sorted(maps.Keys(c.Module.fileContext)) {
fctx := c.Module.fileContext[fid]
// Errors may have already been reported while checking top-level statements
if fctx.getAttribute(unusedReported) != true {
c.reportUnusedWarnings(fctx)
}
}
}
// TODO: Print elapsed time for each depth
type debugLogger struct {
depth int
w io.Writer
}
func (c *Checker) EnableDebug(w io.Writer) { c.logger = &debugLogger{w: w} }
func (c *Checker) debug() bool { return c.logger != nil }
func (l *debugLogger) push(proc string) {
if l != nil {
l.depth++
var c byte = '='
if l.depth%2 == 0 {
c = '-'
}
fmt.Fprintf(l.w, "[Analysis] %*s %s\n", (l.depth*2)-1, char.Repeat(c, l.depth), proc)
}
}
func (l *debugLogger) pop() {
if l != nil {
l.depth--
}
}