-
Notifications
You must be signed in to change notification settings - Fork 65
/
SlangTyper.class.st
343 lines (306 loc) · 11.6 KB
/
SlangTyper.class.st
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
Class {
#name : #SlangTyper,
#superclass : #Object,
#instVars : [
'codeGenerator',
'stopOnErrors'
],
#category : #'Slang-TypeInference'
}
{ #category : #'instance creation' }
SlangTyper class >> on: aCCodeGenerator [
^ self new
codeGenerator: aCCodeGenerator;
yourself
]
{ #category : #'type inference' }
SlangTyper >> addTypesFor: node inMethod: method to: typeSet [
"Add the value types for the node to typeSet.
Answer if any type was derived from an as-yet-untyped method or variable, which allows us to abort
inferReturnTypeFromReturnsIn: if the return type depends on a yet-to-be-typed method or variable."
| expr |
expr := node.
[ expr isAssignment or: [ expr isStatementList ] ] whileTrue: [
expr isAssignment ifTrue: [ expr := expr variable ].
expr isStatementList ifTrue: [ expr := expr statements last ] ].
expr isSend ifTrue: [
(#( ifTrue: ifFalse: #ifTrue:ifFalse: #ifFalse:ifTrue: ) includes:
expr selector) ifTrue: [
^ expr arguments inject: false into: [ :asYetUntyped :block |
asYetUntyped
| (self addTypesFor: block inMethod: method to: typeSet) ] ].
(codeGenerator returnTypeForSend: expr in: method ifNil: nil)
ifNil: [
^ (codeGenerator methodNamed: expr selector) notNil and: [
expr selector ~~ method selector ] ]
ifNotNil: [ :type |
typeSet add: type.
^ false ] ].
expr isVariable ifTrue: [
(codeGenerator typeOfVariable: expr name)
ifNotNil: [ :type | typeSet add: type ]
ifNil: [
(typeSet add: (expr name = 'self'
ifTrue: [ #void ]
ifFalse: [ expr typeFrom: codeGenerator in: method ]))
== #sqInt ifTrue: [ ^ true ] ] ].
expr isConstant ifTrue: [
(expr value isInteger and: [ expr value >= 0 ])
ifTrue: [ typeSet add: expr value ]
ifFalse: [
(expr typeOrNilFrom: codeGenerator in: method) ifNotNil: [ :type |
typeSet add: type ] ] "cannot determine if signed or unsigned yet..." ].
^ false
]
{ #category : #accessing }
SlangTyper >> codeGenerator [
^ codeGenerator
]
{ #category : #accessing }
SlangTyper >> codeGenerator: aCCodeGenerator [
codeGenerator := aCCodeGenerator
]
{ #category : #'type inference' }
SlangTyper >> inferReturnTypeFromReturnsOf: aMethod [
"Attempt to infer the return type of the receiver from returns in the parse tree."
"this for determining which returns have which return types:"
"aCodeGen
pushScope: declarations
while: [parseTree
nodesSelect: [:n| n isReturn]
thenCollect: [:n| | s |
s := Set new.
self addTypesFor: n expression to: s in: aCodeGen.
{n. s}]]"
codeGenerator maybeBreakForTestToInline: aMethod selector in: aMethod.
aMethod returnType ifNotNil: [ ^ self ].
codeGenerator
pushScope: aMethod
while:
[| hasReturn returnTypes |
hasReturn := false.
returnTypes := Set new.
"Debug:
(| rettypes |
rettypes := Dictionary new.
parseTree nodesDo:
[:node|
node isReturn ifTrue:
[| types |
self addTypesFor: node expression to: (types := Set new) in: aCodeGen.
rettypes at: node expression put: types]].
rettypes)"
aMethod parseTree nodesDo: [ :node |
node isReturn ifTrue: [
hasReturn := true.
"If we encounter a send of an as-yet-untyped method then abort,
retrying and computing the type when that method is fully typed."
(self
addTypesFor: node expression
inMethod: aMethod
to: returnTypes) ifTrue: [ ^ self ] ] ].
returnTypes remove: #implicit ifAbsent: [ ].
returnTypes := codeGenerator harmonizeReturnTypesIn: returnTypes.
hasReturn
ifTrue: [
returnTypes size > 1 ifTrue: [
| message |
message := String streamContents: [ :s |
s nextPutAll: 'conflicting return types '.
returnTypes
do: [ :t | s nextPutAll: t ]
separatedBy: [ s nextPutAll: ', ' ].
s
nextPutAll: ' in ';
nextPutAll: aMethod definingClass name;
nextPutAll: ' >> ';
nextPutAll: aMethod selector;
cr ].
Notification signal: message.
codeGenerator logger
newLine;
show: message ].
returnTypes size = 1 ifTrue: [
aMethod returnType: returnTypes anyOne ] ]
ifFalse: [
aMethod returnType:
(codeGenerator implicitReturnTypeFor: aMethod selector) ] ]
]
{ #category : #'type inference' }
SlangTyper >> inferReturnTypeOf: aMethod [
"Attempt to infer the return type of the receiver and answer if it changed."
| existingReturnType |
existingReturnType := aMethod returnType.
self inferReturnTypeFromReturnsOf: aMethod.
^existingReturnType ~= aMethod returnType
]
{ #category : #'type inference' }
SlangTyper >> inferTypes [
| typeConflicts |
typeConflicts := OrderedCollection new.
[ self inferTypesForImplicitlyTypedVariablesAndMethods ]
on: Notification
do: [ :n |
typeConflicts add: n copy freeze.
n resume ].
(stopOnErrors and: [ typeConflicts isNotEmpty ]) ifTrue: [ Error signal: 'there were type errors' ]
]
{ #category : #'type inference' }
SlangTyper >> inferTypesForImplicitlyTypedVariablesAndMethods [
"Infer the return tupe and the types of untyped variables.
As far as variables go, for now we try only to infer variables
assigned the result of #longLongAt:, but much more could be
done here."
"Iterate over all methods, inferring #void return types, until we reach a fixed point."
| allMethods |
allMethods := codeGenerator apiMethods
ifNil: [codeGenerator methods]
ifNotNil: [(Set withAll: codeGenerator methods)
addAll: codeGenerator apiMethods;
yourself].
"Make an initial pass to assign the return types of all simple methods that return constants,
or those that have explicit return types."
allMethods do:
[:m|
m removeFinalSelfReturnIn: codeGenerator. "must precede recordDeclarationsIn: because it may set returnType"
m recordDeclarationsIn: codeGenerator.
(m returnType isNil
and: [m isReturnConstant]) ifTrue:
[self inferReturnTypeOf: m]].
"now iterate until we reach a fixed point"
[| changedReturnType |
changedReturnType := false.
allMethods do:
[:m|
self inferTypesForImplicitlyTypedVariablesIn: m.
(self inferReturnTypeOf: m) ifTrue:
[changedReturnType := true]].
changedReturnType] whileTrue.
"Type all as-yet-untyped methods as the default"
codeGenerator methods do:
[:m|
m returnType ifNil:
[m returnType: (m returnsExpression
ifTrue: [codeGenerator defaultType]
ifFalse: [codeGenerator implicitReturnTypeFor: m])].
m transformReturns].
"Make a final pass to type anything assigned from the default type"
allMethods do: [ :m |
self inferTypesForImplicitlyTypedVariablesIn: m ]
]
{ #category : #'type inference' }
SlangTyper >> inferTypesForImplicitlyTypedVariablesIn: aMethod [
" Infer types for untyped variables from assignments and arithmetic uses "
| alreadyExplicitlyTypedOrNotToBeTyped asYetUntyped mustBeSigned newDeclarations |
codeGenerator maybeBreakForTestToInline: aMethod selector in: aMethod.
alreadyExplicitlyTypedOrNotToBeTyped := aMethod declarations keys
asSet.
asYetUntyped := aMethod allLocals copyWithoutAll:
alreadyExplicitlyTypedOrNotToBeTyped.
mustBeSigned := Set new.
newDeclarations := Dictionary new.
aMethod parseTree nodesDo: [ :node |
| type var |
"If there is something of the form i >= 0, then i should be signed, not unsigned."
(node isSend and: [
(aMethod allLocals includes: (var := node receiver variableNameOrNil))
and: [
(#( <= < >= > ) includes: node selector) and: [
node arguments first isConstant and: [
node arguments first value = 0 ] ] ] ]) ifTrue: [
mustBeSigned add: var ].
"if an assignment to an untyped local of a known type, set the local's type to that type.
Only observe known sends (methods in the current set) and typed local variables."
(node isAssignment and: [
(aMethod allLocals includes: (var := node variable name)) and: [
(alreadyExplicitlyTypedOrNotToBeTyped includes: var) not ] ])
ifTrue: [ "don't be fooled by previously inferred types"
type := self
tryExtractTypeFromAssignmentNode: node
inMethod: aMethod.
type
ifNil: [ "Further, if the type derives from an as-yet-untyped method, we must defer."
alreadyExplicitlyTypedOrNotToBeTyped add: var.
(node expression isSend and: [
(codeGenerator methodNamed: node expression selector) notNil ])
ifTrue: [ newDeclarations removeKey: var ifAbsent: nil ] ]
ifNotNil: [ "Merge simple types (but *don't* merge untyped vars); complex types must be defined by the programmer.""If untyped, then cannot type the variable yet. A subsequent assignment may assign a subtype of what this type ends up being"
(codeGenerator isSimpleType: type) ifTrue: [
(asYetUntyped includes: var)
ifTrue: [
newDeclarations at: var put: type , ' ' , var.
asYetUntyped remove: var ]
ifFalse: [
self
mergeTypeOf: var
in: newDeclarations
with: type
method: aMethod ] ] ] ] ].
mustBeSigned do: [ :var |
(newDeclarations at: var ifAbsent: nil) ifNotNil: [ :decl |
| type |
type := codeGenerator extractTypeFor: var fromDeclaration: decl.
type first == $u ifTrue: [
newDeclarations
at: var
put: (self signedTypeForIntegralType: type) , ' ' , var ] ] ].
newDeclarations keysAndValuesDo: [ :var :decl |
aMethod declarations at: var put: decl ]
]
{ #category : #'type inference' }
SlangTyper >> mergeTypeOf: var in: aDictionary with: newType method: tMethod [
"var is a variable that has been assigned an expression of type newType.
Either assign its type, if it is as yet untyped, or merge newType with its existing type.
N.B. We refuse to promote a variable that already has integral type to a floating point
type. The existing plugins depend on this; one can always use an explicit type in future."
| existingType mergedType |
existingType := codeGenerator
extractTypeFor: var
fromDeclaration: (aDictionary at: var ifAbsentPut: [newType, ' ', var]).
existingType ~= newType ifTrue:
[((codeGenerator isPointerCType: existingType)
or: [codeGenerator isPointerCType: newType])
ifTrue:
[existingType = #'void *' ifTrue: [^newType].
newType = #'void *' ifTrue: [^existingType].
codeGenerator logger show: 'conflicting types ', existingType, ' ', newType, ' for ', var, ' in ', tMethod selector.
^existingType]
ifFalse:
[((codeGenerator isIntegralCType: existingType)
and: [codeGenerator isFloatingPointCType: newType]) ifFalse:
[mergedType := codeGenerator promoteArithmeticTypes: existingType and: newType.
aDictionary at: var put: mergedType, ' ', var]]]
]
{ #category : #'type inference' }
SlangTyper >> signedTypeForIntegralType: aCTypeString [
(aCTypeString beginsWith: 'unsigned ') ifTrue:
[^aCTypeString allButFirst: 8].
(aCTypeString beginsWith: 'usq') ifTrue:
[^aCTypeString allButFirst].
aCTypeString = 'size_t' ifTrue: [^#usqIntptr_t].
self error: 'unknown type'.
^#long
]
{ #category : #accessing }
SlangTyper >> stopOnErrors [
^ stopOnErrors
]
{ #category : #accessing }
SlangTyper >> stopOnErrors: anObject [
stopOnErrors := anObject
]
{ #category : #'type inference' }
SlangTyper >> tryExtractTypeFromAssignmentNode: node inMethod: aMethod [
^ node expression isSend
ifTrue: [
codeGenerator
returnTypeForSend: node expression
in: aMethod
ifNil: nil ]
ifFalse: [
(node expression isAssignment
ifTrue: [ node expression variable ]
ifFalse: [ node expression ])
typeFrom: codeGenerator
in: aMethod ]
]