-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtype_declaration.go
More file actions
298 lines (275 loc) · 8.35 KB
/
Copy pathtype_declaration.go
File metadata and controls
298 lines (275 loc) · 8.35 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
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"
)
// TypeName represents a type declaration.
//
// Type is one of these types:
// - [*TypeAlias]
// - [*Struct]
// - [*Interface]
// - [*Enum]
// - [*Tag]
type TypeName struct {
Type
Name string
}
// String returns the name of the type.
func (n *TypeName) String() string {
if alias, ok := n.Type.(*TypeAlias); ok {
return alias.Type.String()
}
return n.Name
}
func (n *TypeName) Underlying() Type { return n.Type }
func (n *TypeName) objKind() {}
// Alias
// =======
type TypeAlias struct {
Name string
Type
resolved Type
}
func (a *TypeAlias) Resolve() Type {
if a.resolved == nil {
if subAlias, ok := a.Type.(*TypeAlias); ok {
// This also recursively resolves aliases for upstream type aliases
a.resolved = subAlias.Resolve()
} else {
// a's underlying type isn't an alias, so it is already resolved
a.resolved = a.Type
}
}
return a.resolved
}
func (a *TypeAlias) Kind() Kind { return a.Resolve().Kind() }
func (a *TypeAlias) Underlying() Type { return a.Resolve() }
func (c *Checker) checkTypeAlias(o *Object, node *ast.TypeAliasDeclaration) {
alias := &TypeAlias{Name: o.Name}
o.TypeName().Type = alias
rhs := c.parseType(node.Type, o.LookupContext())
// Set to invalid if we couldn't typecheck the rhs
if rhs == nil {
rhs = InvalidType
}
// TODO: What if the generic is in a union?
if rhs.Kind() == KindGeneric {
// The target of a type alias cannot be a generic type
err := klarerrs.Range(klarerrs.ErrGenericTypeAlias, node.Type.GetRange())
err.Label = "This can't be a generic type"
c.fileError(err, o.File)
rhs = InvalidType
}
alias.Type = rhs
}
// TODO
func (c *Checker) checkFuncAlias(o *Object) {
info := o.info
targetExpr := info.node.(*ast.FuncAliasDeclaration).Target
// TODO: Lookup the target expression and make sure it resolves to a function
var target *Object = nil
if info.receiver != nil {
// Method alias
sym := targetExpr.(*ast.Symbol)
_ = sym
} else {
// Normal function
switch targetExpr.(type) {
case *ast.IndexExpression:
case *ast.Symbol:
}
}
o.Type.(*FunctionAlias).Target = target
}
func Unalias(t Type) Type {
if a, ok := t.(*TypeAlias); ok {
return a.Resolve()
}
return t
}
// Tag
// ======
// Tag represents a Klar tag type.
type Tag struct{ Implements map[Type]struct{} }
func (*Tag) Kind() Kind { return KindTag }
func (*Tag) String() string { return "<tag>" }
// checkTypeDecl checks the type declaration in decl.node and sets
// the type of o's Type. o's Type should be [*TypeName]. The completed
// declaration is created inside the [*TypeName].
func (c *Checker) checkTypeDecl(o *Object) {
node := o.info.node.(ast.TypeDeclaration)
_ = o.TypeName() // Should be a [*TypeName]
switch node := node.(type) {
case *ast.StructDeclaration:
c.checkStructDecl(o, node)
case *ast.EnumDeclaration:
c.checkEnumDecl(o, node)
case *ast.TypeAliasDeclaration:
c.checkTypeAlias(o, node)
case *ast.TagDeclaration:
c.checkTagType(o, node)
case *ast.InterfaceDeclaration:
c.checkInterfaceDecl(o, node)
default:
panic(fmt.Sprintf("unknown type declaration: %T", node))
}
}
func (c *Checker) checkTagType(o *Object, node *ast.TagDeclaration) {
// TODO: Check that each inherited type was declared within this module
o.TypeName().Type = &Tag{
Implements: c.checkInheritedTypes(node.InheritedTypes, KindTag, o.LookupContext()),
}
}
// checkInheritedTypes checks the inherited types to ensure they are
// compatible with the given target declaration kind.
func (c *Checker) checkInheritedTypes(
names []ast.Type, kind Kind, fctx *Context,
) (inherited map[Type]struct{}) {
if len(names) == 0 {
return nil
}
inherited = make(map[Type]struct{}, len(names))
existingMap := make(map[Type]ranges.Range, len(names))
for _, tn := range names {
var flags Flag
// Tags can only inherit from locally-declared tags
if kind == KindTag {
flags |= LocalOnly
}
typ := c.parseType(tn, fctx, flags)
underlying := Underlying(typ)
if typ.Kind() == InvalidType {
continue
}
if _, ok := inherited[underlying]; ok {
// Type specified twice
err := klarerrs.Range(klarerrs.ErrDuplicateInheritedType, tn.GetRange())
err.Name = typ.String()
err.Highlights = append(err.Highlights, klarerrs.Highlight{
Range: existingMap[underlying],
Message: "It was already specified here",
})
c.fileError(err, fctx.File)
continue
}
if !c.validateInheritedType(tn, typ, kind, fctx.File) {
continue
}
inherited[underlying] = struct{}{}
existingMap[underlying] = tn.GetRange()
}
return inherited
}
// validateInheritedType checks the inherited type represented by node n
// and type t for validity as an inherited type for declaration kind declKind.
func (c *Checker) validateInheritedType(n ast.Type, t Type,
targetKind Kind, fid FileID,
) bool {
// TODO: Maybe we should allow inheriting from primitive types (not lists)
typeKind := t.Kind()
// Validate the node
newError := func(currType, allowedTypes string) {
err := klarerrs.Range(klarerrs.ErrInvalidInheritedType, n.GetRange())
err.Params = klarerrs.ErrorParams{"kind": currType, "allowedTypes": allowedTypes}
err.Label = currType + " can't inherit from " + klarerrs.WithA(typeKind.String())
c.fileError(err, fid)
}
if targetKind == typeKind || typeKind == InvalidType {
return true
}
switch n.(type) {
case *ast.TypeAlias, *ast.PrimitiveType, *ast.GenericType:
default:
// Change the kind so an error is reported below
typeKind = InvalidType
}
// Validate the actual type
switch targetKind {
case KindTag:
// Already checked via targetKind == typeKind, so this is invalid
newError("A tag", "another tag")
return false
case KindStruct:
if typeKind != KindInterface && typeKind != KindTag {
newError("A struct", "an interface, tag, or another struct")
return false
}
case KindInterface:
if typeKind != KindStruct && typeKind != KindTag {
newError("An interface", "a struct, tag, or another interface")
return false
}
case KindEnum:
if typeKind != KindInterface && typeKind != KindTag {
newError("An enum", "an interface, tag, or another enum")
return false
}
default:
panic(fmt.Sprintf("invalid target type kind %d", targetKind))
}
return true
}
/*
checkDirectCycles checks for direct cycles within the declarations in the
given context. Type aliases that directly refer to other type aliases are checked.
The algorithm for this is similar to [Checker.objPathIndex] and the one used
in Go's type checker:
- Not found in `pathI`: The type name hasn't been seen before (red)
- Found in `pathI` with a value >= 0: Has been seen but is not done (white)
- Value < 0: Seen and done (blue)
*/
func (c *Checker) checkDirectCycles(ctx *Context) {
pathI := make(map[*Object]int)
for _, obj := range ctx.SortedDecls() {
if !obj.IsTypeName() {
continue
}
var path []*Object
for {
if start, ok := pathI[obj]; start < 0 {
break // Object is blue
} else if ok {
// Object is white: there is a cycle starting at `path[start]`
obj.TypeName().Type = InvalidType
c.error(cycleError(path[start:]))
break
}
// Object is red
pathI[obj] = len(path)
path = append(path, obj)
// If this object isn't a type alias, we're at the end of the path and done.
aliasDecl, ok := obj.info.node.(*ast.TypeAliasDeclaration)
if !ok {
break
}
// TODO: We should also check for cycles in parenthesized types, tuples,
// and types with generics.
//
// Go only checks in aliases because recursive types are allowed in other
// wrapper types (such as pointers). `type T *T` is even allowed in Go.
// Though in this step, Go doesn't check inside structs.
var rhs *ast.TypeAlias
rhs, ok = aliasDecl.Type.(*ast.TypeAlias)
if !ok {
break
}
// Resolve the type the alias refers to. [Object.IsTypeName] handles nil
// objects. In that case, if the RHS is undefined, an error will be
// reported later. Also, we're not looking up recursively -- types can't be
// declared across contexts/scopes. Similar for imported types. In those
// cases, we can stop.
next := ctx.Lookup(rhs.Identifier)
if !next.IsTypeName() {
break
}
obj = next
}
// Mark all type names in the path blue
for _, obj := range path {
pathI[obj] = -1
}
}
}