/
VariableAccess.ooc
496 lines (418 loc) · 17.4 KB
/
VariableAccess.ooc
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
import ../frontend/[Token, BuildParams, AstBuilder], io/File
import BinaryOp, Visitor, Expression, VariableDecl, FunctionDecl,
TypeDecl, Declaration, Type, Node, ClassDecl, NamespaceDecl,
EnumDecl, PropertyDecl, FunctionCall, Module, Import, FuncType,
NullLiteral, AddressOf, BaseType, StructLiteral, Return,
Argument, InlineContext, Scope, CoverDecl, StringLiteral
import tinker/[Resolver, Response, Trail, Errors]
import structs/ArrayList
// for built-ins
import net/DNS, os/Time, rock/RockVersion, rock/frontend/Target
VariableAccess: class extends Expression {
_warned := false
_staticFunc : FunctionDecl = null
expr: Expression {
get
set (newExpr) {
expr = newExpr
match newExpr {
case acc: VariableAccess => acc reverseExpr = this
}
}
}
reverseExpr: VariableAccess
name: String
ref: Declaration
init: func ~variableAccess (.name, .token) {
init(null, name, token)
}
init: func ~variableAccessWithExpr (=expr, =name, .token) {
super(token)
}
init: func ~varDecl (varDecl: VariableDecl, .token) {
super(token)
name = varDecl getName()
ref = varDecl
}
clone: func -> This {
new(expr ? expr clone() : null, name, token)
}
init: func ~typeAccess (type: Type, .token) {
super(token)
name = type getName()
if(type getRef() instanceOf?(VariableDecl)) {
varDecl := type getRef() as VariableDecl
if(varDecl getOwner() != null) {
if(varDecl isStatic) {
expr = VariableAccess new(varDecl getOwner() getInstanceType(), token)
} else {
expr = VariableAccess new("this", token)
}
}
} else {
// else, it's safe to carry the ref
ref = type getRef()
}
}
accept: func (visitor: Visitor) {
visitor visitVariableAccess(this)
}
// It's just an access, it has no side-effects whatsoever
hasSideEffects : func -> Bool { false }
debugCondition: inline func -> Bool {
false
}
suggest: func (node: Node) -> Bool {
match node {
case candidate: VariableDecl =>
// if we're accessing a member, we're expecting the
// candidate to belong to a TypeDecl..
if(isMember() && !candidate isMember()) {
return false
}
if(_staticFunc && candidate isMember() && candidate == candidate owner thisDecl) {
//token formatMessage("Got thisDecl of " + candidate owner toString() + " in static func " + _staticFunc toString(), "INFO") println()
// Can't access an instance variable from static function
return false
}
ref = candidate
if(isMember() && candidate owner isMeta) {
expr = VariableAccess new(candidate owner getNonMeta() getInstanceType(), candidate token)
}
true
case candidate: FunctionDecl =>
// if we're accessing a member, we're expecting the candidate
// to belong to a TypeDecl..
if((expr != null) && (candidate owner == null)) {
return false
}
ref = candidate
true
case tDecl: TypeDecl =>
// TODO: the use of 'val' here is a workaround - an if/else should
// be an expression.
val := true
if(tDecl isAddon()) {
// First rule of resolve club is: you do not resolve to an addon.
// Always resolve to the base instead.
val = suggest(tDecl getBase() getNonMeta())
} else {
ref = node
}
val
case nDecl: NamespaceDecl =>
ref = node
true
case =>
false
}
}
isResolved: func -> Bool { ref != null && getType() != null }
resolve: func (trail: Trail, res: Resolver) -> Response {
if(debugCondition()) {
"%s is of type %s" printfln(name, getType() ? getType() toString() : "(nil)")
}
// resolve built-ins first
builtin := getBuiltin(name)
if (builtin) {
if(!trail peek() replace(this, builtin)) {
res throwError(CouldntReplace new(token, this, builtin, trail))
}
res wholeAgain(this, "builtin replaced")
return Response OK
}
trail onOuter(FunctionDecl, |fDecl|
if(fDecl isStatic()) _staticFunc = fDecl
)
if(expr) {
trail push(this)
response := expr resolve(trail, res)
trail pop(this)
if(!response ok()) return response
//printf("Resolved expr, type = %s\n", expr getType() ? expr getType() toString() : "(nil)")
}
if(expr && name == "class") {
if(expr getType() == null || expr getType() getRef() == null) {
res wholeAgain(this, "expr type or expr type ref is null")
return Response OK
}
if(!expr getType() getRef() instanceOf?(ClassDecl)) {
name = expr getType() getName()
ref = expr getType() getRef()
expr = null
}
}
/*
* Try to resolve the access from the expr
*/
if(!ref && expr) {
if(expr instanceOf?(VariableAccess) && expr as VariableAccess getRef() != null \
&& expr as VariableAccess getRef() instanceOf?(NamespaceDecl)) {
expr as VariableAccess getRef() resolveAccess(this, res, trail)
} else {
exprType := expr getType()
if(exprType == null) {
res wholeAgain(this, "expr's type isn't resolved yet, and it's needed to resolve the access")
return Response OK
}
//printf("Null ref and non-null expr (%s), looking in type %s\n", expr toString(), exprType toString())
typeDecl := exprType getRef()
if(!typeDecl) {
if(res fatal) res throwError(UnresolvedType new(expr token, expr getType(), "Can't resolve type %s" format(expr getType() toString())))
res wholeAgain(this, "unresolved access, looping")
return Response OK
}
typeDecl resolveAccess(this, res, trail)
//If we did'nt get the ref, we try to get it from the cover's "from type"
if(!ref && typeDecl instanceOf?(CoverDecl)) {
typeDecl as CoverDecl resolveAccessInFromType(this, res, trail)
}
}
}
/*
* Try to resolve the access from the trail
*
* It's far simpler than resolving a function call, we just
* explore the trail from top to bottom and retain the first match.
*/
if(!ref && !expr) {
depth := trail getSize() - 1
while(depth >= 0) {
node := trail get(depth)
if(node instanceOf?(TypeDecl)) {
tDecl := node as TypeDecl
if(tDecl isMeta) node = tDecl getNonMeta()
// in initialization of a member object!
if(!ref && name == "this" && trail find(Scope) == -1) {
suggest(node as TypeDecl thisDecl)
}
}
node resolveAccess(this, res, trail)
if(ref) {
if(expr) {
if(expr instanceOf?(VariableAccess)) {
trail push(this)
response := expr resolve(trail, res)
trail pop(this)
if(!response ok()) return Response LOOP
varAcc := expr as VariableAccess
}
}
// only accesses to variable decls need to be partialed (not type decls)
if(ref instanceOf?(VariableDecl) && !ref as VariableDecl isGlobal() && expr == null) {
closureIndex := trail find(FunctionDecl)
if(closureIndex > depth) { // if it's not found (-1), this will be false anyway
closure := trail get(closureIndex, FunctionDecl)
mode := "v"
if(closure isAnon()) {
bOpIDX := trail find(BinaryOp)
if (trail find(BinaryOp) != -1) {
bOp := trail get(bOpIDX, BinaryOp)
if (bOp getLeft() == this && bOp isAssign()) mode = "r"
}
closure markForPartialing(ref as VariableDecl, mode)
closure clsAccesses add(this)
}
}
}
break // break on first match
}
depth -= 1
}
}
if (getType() instanceOf?(FuncType) ) {
fType := getType() as FuncType
parent := trail peek()
if (!fType isClosure) {
closureElements := [
this
NullLiteral new(token)
] as ArrayList<VariableAccess>
closureType: FuncType = null
if (parent instanceOf?(FunctionCall)) {
/*
* The case we're looking for is this one:
*
* registerCallback(exit)
*
* If registerCallback is an ooc function and the arg is
* a FuncType we need to make a StructLiteral out of ourselves.
*/
fCall := parent as FunctionCall
ourIndex := fCall args indexOf(this)
fDecl := fCall getRef()
if(!fDecl) {
res wholeAgain(this, "need ref!")
return Response OK
}
// 1.) extern C functions don't accept a Closure_struct
// 2.) If ref is not a FDecl, it's probably already "closured" and doesn't need to be wrapped a second time
if (!fDecl isExtern() && ref instanceOf?(FunctionDecl)) {
if(fDecl args size <= ourIndex) {
res wholeAgain(this, "bad index for ref")
return Response OK
}
closureType = fDecl args get(ourIndex) getType()
}
} elseif (parent instanceOf?(BinaryOp)) {
binOp := parent as BinaryOp
if(binOp isAssign() && binOp getRight() == this) {
if(binOp getLeft() getType() == null) {
res wholeAgain(this, "need type of BinOp's lhs")
return Response OK
}
closureType = binOp getLeft() getType() clone()
}
} elseif (parent instanceOf?(Return)) {
fIndex := trail find(FunctionDecl)
if (fIndex != -1) {
closureType = trail get(fIndex, FunctionDecl) returnType clone()
}
} elseif (parent instanceOf?(VariableDecl)) {
/*
Handle the assignment of a first-class function.
Example:
f: func() {}
g := f
The right side needs to be a Closure having f and null as context.
*/
p := parent as VariableDecl
if (p expr == this) {
closureType = ref getType()
if (!closureType) {
res wholeAgain(this, "need type of FDecl")
return Response OK
}
}
}
if (closureType && closureType instanceOf?(FuncType)) {
fType isClosure = true
closure := StructLiteral new(closureType, closureElements, token)
if(!trail peek() replace(this, closure)) {
res throwError(CouldntReplace new(token, this, closure, trail))
}
}
}
}
// Simple property access? Replace myself with a getter call.
if(ref && ref instanceOf?(PropertyDecl)) {
// Make sure we're not in a getter/setter yet (the trail would
// contain `ref` then)
if(ref as PropertyDecl inOuterSpace(trail)) {
// Test that we're not part of an assignment (which will be replaced by a setter call)
// That's also the case for operators like +=, *=, /= ...
// TODO: This should be nicer.
if(!(trail peek() instanceOf?(BinaryOp) && trail peek() as BinaryOp isAssign())) {
property := ref as PropertyDecl
fCall := FunctionCall new(expr, property getGetterName(), token)
trail peek() replace(this, fCall)
return Response OK
}
} else {
// We are in a setter/getter and we're having a variable access. That means
// the property is not virtual.
ref as PropertyDecl setVirtual(false)
}
}
if(!_warned && trail peek() instanceOf?(Scope)) {
parent := trail peek() as Scope
size := parent list getSize()
idxOf := parent list indexOf(this)
if(idxOf != -1 && idxOf != (size - 1)) {
res throwError(Warning new(token, "Statement with no effect"))
}
_warned = true
}
if(!ref) {
if(res fatal) {
subject := this
if(reverseExpr && _staticFunc && name == "this") {
res throwError(InvalidAccess new(this,
"Can't access instance variable '%s' from static function '%s'!" format(reverseExpr getName(), _staticFunc getName())
))
}
if(res params veryVerbose) {
println("trail = " + trail toString())
}
msg := "Undefined symbol '%s'" format(subject toString())
if(res params helpful) {
similar := subject findSimilar(res)
if(similar) {
msg += similar
}
}
res throwError(UnresolvedAccess new(subject, msg))
}
if(res params veryVerbose) {
" - access to %s%s still not resolved, looping (ref = %s)" printfln(\
expr ? (expr toString() + "->") : "", name, ref ? ref toString() : "(nil)")
}
res wholeAgain(this, "Couldn't resolve varacc")
}
return Response OK
}
findSimilar: func (res: Resolver) -> String {
buff := Buffer new()
for(imp in res collectAllImports()) {
module := imp getModule()
type := module getTypes() get(name)
if(type) {
buff append(" (Hint: there's such a type in "). append(imp getPath()). append(")")
}
}
buff toString()
}
getBuiltin: func (name: String) -> Expression {
match name {
case "__BUILD_DATETIME__" =>
StringLiteral new(Time dateTime(), token)
case "__BUILD_TARGET__" =>
StringLiteral new(Target toString(), token)
case "__BUILD_ROCK_VERSION__" =>
StringLiteral new(RockVersion getName(), token)
case "__BUILD_HOSTNAME__" =>
StringLiteral new(DNS hostname(), token)
case =>
null
}
}
getRef: func -> Declaration { ref }
getType: func -> Type {
if(!ref) return null
if(ref instanceOf?(Expression)) {
return ref as Expression getType()
}
return null
}
isMember: func -> Bool {
(expr != null) &&
!(expr instanceOf?(VariableAccess) &&
expr as VariableAccess getRef() != null &&
expr as VariableAccess getRef() instanceOf?(NamespaceDecl)
)
}
getName: func -> String { name }
toString: func -> String {
expr ? (expr toString() + " " + name) : name
}
isReferencable: func -> Bool { true }
replace: func (oldie, kiddo: Node) -> Bool {
match oldie {
case expr => expr = kiddo as Expression; true
case => false
}
}
setRef: func(=ref) {}
}
UnresolvedAccess: class extends Error {
access: VariableAccess
init: func (=access, .message) {
super(access token, message)
}
}
InvalidAccess: class extends Error {
access: VariableAccess
init: func (=access, .message) {
super(access token, message)
}
}