-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeclaration.go
More file actions
335 lines (318 loc) · 9.62 KB
/
Copy pathdeclaration.go
File metadata and controls
335 lines (318 loc) · 9.62 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package analysis
import (
"fmt"
"github.com/ProCode-Software/klar/internal/ast"
"github.com/ProCode-Software/klar/internal/klarerrs"
"github.com/ProCode-Software/klar/internal/ranges"
)
type DeclarationInfo struct {
node ast.Statement
varInfo *varInfo // For var/const declaration.
funcKind funcKind // For function declaration.
receiver *Object // For method or initializer. Should be [*TypeName]
}
type varInfo struct {
lhs ast.Destructurable // Where the variable was defined. Undestructured
rhs ast.Expression // Undestructured RHS expression
expType Type // If the decl has an explicit type. Use as [*Expr.hint]
// Set when rhs is checked, or the explicit type is known. Pointer is
// never nil, but the *Expr can be.
rhsExpr **Expr
}
type funcKind uint8
const (
normalFunc funcKind = iota
methodFunc
initFunc
)
// declareWithInfo declares an object into the given context with the
// given attributes and [DeclarationInfo]. If declareToCtx == false,
// only the object's information is recorded and is not added to the context.
// If *attrs != nil, the attributes are parsed and drained.
func (c *Checker) declareWithInfo(obj *Object, ctx *Context,
attrs *[]*ast.Attribute, declareToCtx bool,
) {
if declareToCtx {
c.declare(ctx, obj)
} else {
obj.Context = ctx // Still set the object's context
}
// Parse the attributes if any (top-level only)
if attrs != nil {
obj.attrs = c.parseAttributes(
*attrs, attrTargetKindOf(obj.info.node, obj.Public), obj.Range, obj.File,
)
*attrs = (*attrs)[:0]
}
if obj.Name == "_" {
// Since the object won't be added to the context, it won't be checked.
// For discarded idents, it's guaranteed there are no dependencies
obj.Context = ctx
obj.Order = uint32(len(ctx.Declarations))
c.checkDeclaration(obj)
}
}
func (c *Checker) checkDeclaration(o *Object) {
/*
Red: Type isn't known yet. Not in objPathIndex.
White: Type is pending. Is in objPathIndex.
Blue: Type is known. Not in objPathIndex.
Blue can only depend on blue. White/grey can only depend on red or blue.
A dependency on white is a (possibly invalid) cycle.
When marked white, it is pushed onto the object path stack, and its index
is recorded in objPathIndex. It's removed from the map and the stack when marked blue.
*/
if _, ok := c.objPathIndex[o]; ok {
switch typ := o.Type.(type) {
case *Variable:
if !c.checkCycle(o) || typ.Type == nil {
typ.Type = InvalidType
}
case *Constant:
if !c.checkCycle(o) || typ.Type == nil {
typ.Type = InvalidType
}
case *TypeName:
if !c.checkCycle(o) {
typ.Type = InvalidType
}
case *Function, *Overload:
c.checkCycle(o) // TODO: is this needed?
case *FunctionAlias:
// TODO
default:
panic(fmt.Sprintf("unhandled declaration type: %T", o.Type))
}
if Underlying(o.Type) == nil {
panic("underlying type is still nil")
}
return
}
if Underlying(o.Type) != nil {
return // Blue, already checked
}
// White, not checked yet
c.pushToPath(o)
defer c.popPath()
switch o.Type.(type) {
case *Variable:
c.checkVarDecl(o)
case *Constant:
c.checkConstDecl(o)
case *TypeName:
c.checkTypeDecl(o)
case *Function:
c.checkFuncDecl(o)
case *Overload:
return // Overloads are part of functions
case *FunctionAlias:
c.checkFuncAlias(o)
default:
panic(fmt.Sprintf("unhandled declaration type: %T", o.Type))
}
}
// checkCycle checks if a cycle involving the given object is valid.
// An error is reported if checkCycle returns false.
func (c *Checker) checkCycle(o *Object) bool {
start := c.objPathIndex[o]
cycle := c.objPath[start:]
// Number of type defs and values (const or var) in the cycle
var typeDefCount, valCount int
for _, obj := range cycle {
switch typ := obj.Type.(type) {
case *TypeName:
if _, ok := typ.Type.(*TypeAlias); !ok {
// Only increase the count for non-aliases
typeDefCount++
}
case *Variable, *Constant:
valCount++
case *Function:
default:
panic(fmt.Sprintf("isValidCycle: unhandled declaration type: %T", obj.Type))
}
}
switch {
case valCount == len(cycle):
// Go: A cycle involving only constants and variables is invalid but we
// ignore them here because they are reported via the initialization
// cycle check.
return true
case valCount == 0 && typeDefCount > 0:
// A cycle involving only type definitions (and maybe functions) must have
// at least 1 type definition to be valid. Alias-only cycles are invalid.
return true
default:
// Invalid cycle
c.error(cycleError(cycle))
return false
}
}
// collectMethods associates methods with the type with name typeName. The
// receiver for the methods is looked up within the context and validated.
func (c *Checker) collectMethods(ctx *Context, typeName string, methods []methodInfo) {
if len(methods) == 0 {
return
}
selfObj := ctx.Lookup(typeName)
if selfObj == nil {
c.validateReceiver(typeName, ctx.LookupRecursive(typeName), methods, true)
return
}
if !c.validateReceiver(typeName, selfObj, methods, false) {
return
}
self := Underlying(selfObj.Type).(SupportsMethods)
for _, meth := range methods {
meth.obj.info.funcKind = methodFunc
meth.obj.info.receiver = selfObj
if err := self.AddMethod(meth.obj); err != nil {
if err.Code == klarerrs.ErrFieldAndMethodSameName {
err.SetParam("type", typeName)
}
c.fileError(err, meth.obj.File)
return
}
}
// Typecheck the [*Function] or [*FunctionAlias] objects, not overloads from `methods`
for _, obj := range self.GetMethods() {
c.checkDeclaration(obj)
}
}
// collectInitializers checks the signature of each initializer function and
// associates them with the type with name typeName. Each [*Object] in inits
// should have type [*Overload]. The type with name typeName is looked up
// within the context and validated.
func (c *Checker) collectInitializers(ctx *Context, typeName string, inits []*Object) {
identRange := func(obj *Object) ranges.Range {
return obj.info.node.(*ast.FunctionDeclaration).Identifier.Range()
}
// TODO: typeName was already looked up in [Checker.getOverloadParent].
// Don't repeat this process again, and move error reporting
// for initializers in other scopes to that function.
selfObj := ctx.Lookup(typeName)
if selfObj == nil {
selfObj = ctx.LookupRecursive(typeName)
if selfObj == nil {
// Undefined
for _, o := range inits {
err := klarerrs.Undefined(typeName, identRange(o))
c.fileError(err, o.File)
}
return
}
// Found, but in a different scope
det := []klarerrs.Detail{{
File: selfObj.FilePath(),
Range: selfObj.Range,
Message: klarerrs.Quote(typeName) + " was declared here",
}}
for _, o := range inits {
node := o.info.node.(*ast.FunctionDeclaration)
err := klarerrs.Node(klarerrs.ErrMethodInOtherScope, node)
err.SetParam("initializer", true)
err.Details = det
c.fileError(err, o.File)
}
return
}
switch self := selfObj.TypeName().Type.(type) {
case *Struct:
self.Initializers = inits
case *Enum:
self.Initializers = inits
case *TypeAlias:
// Similar to method receivers, this can't be an alias
for _, o := range inits {
err := klarerrs.Range(klarerrs.ErrAliasSelfType, identRange(o))
err.SetParam("initializer", true)
err.Label = "Initializer target can't be an alias"
c.fileError(err, o.File)
}
return
default:
// Type doesn't support initializers
for _, o := range inits {
err := klarerrs.Range(klarerrs.ErrUnsupportedInitType, identRange(o))
err.Label = "Can't create initializers on this kind of type"
c.fileError(err, o.File)
}
return
}
for _, obj := range inits {
obj.info.funcKind = initFunc
obj.info.receiver = selfObj
c.checkOverload(obj.Type.(*Overload), nil)
}
}
func (c *Checker) validateReceiver(name string, self *Object,
methods []methodInfo, isOtherScope bool,
) bool {
selfRange := func(meth methodInfo) ranges.Range {
if meth.decl != nil {
return meth.decl.SelfType.Range()
} else {
return meth.alias.Struct.Range()
}
}
// Error if:
// - Object is nil
// - Object is not a type
// - Object is declared in another scope
// - Object is in another module or is a builtin (TODO)
// - Object is a type alias
// - Object doesn't accept methods
switch {
case self == nil:
// Self type doesn't exist
for _, meth := range methods {
err := klarerrs.Undefined(name, selfRange(meth))
c.fileError(err, meth.obj.File)
}
case isOtherScope:
// typeName was declared in a different scope from the method
det := []klarerrs.Detail{{
File: self.FilePath(),
Range: self.Range,
Message: klarerrs.Quote(name) + " was declared here",
}}
for _, meth := range methods {
err := klarerrs.Node(klarerrs.ErrMethodInOtherScope, meth.decl)
err.Details = det
c.fileError(err, meth.obj.File)
}
case self.Module != methods[0].obj.Module:
// TODO: check that receiver is not a primitive
return false
default:
tn, ok := self.Type.(*TypeName)
if !ok {
// Receiver is not a type
for _, m := range methods {
err := klarerrs.Range(klarerrs.ErrUnsupportedSelfType, selfRange(m))
err.Label = "This isn't a type"
c.fileError(err, m.obj.File)
}
return false
}
switch tn.Type.(type) {
case *TypeAlias:
// Self type is a type alias
for _, m := range methods {
err := klarerrs.Range(klarerrs.ErrAliasSelfType, selfRange(m))
err.Label = "Self type can't be an alias"
c.fileError(err, m.obj.File)
}
default:
// Self type doesn't support methods
for _, m := range methods {
err := klarerrs.Range(klarerrs.ErrUnsupportedSelfType, selfRange(m))
err.Label = "Can't declare methods on this kind of type"
c.fileError(err, m.obj.File)
}
case SupportsMethods:
return true
}
}
return false
}