Skip to content
← Back

src/syntax/process/compile-expressions/compile_tuples.ghul

1
namespace Syntax.Process is
2
use System.Exception
3
4
use Logging
5
6
use Semantic.LEAST_UPPER_BOUND_MAP
7
use Semantic.Types.Type
8
9
use IR.Values
10
use IR.VALUE_BOXER
11
12
use Ghul.Pipes
13
14
// Compiles tuple and list/array (`SEQUENCE`) literal expressions.
15
// Split out of COMPILE_EXPRESSIONS, which delegates pre(tuple),
16
// visit(tuple) and the inner sequence compile here. The
17
// exception-handling and walk orchestration for visit(sequence)
18
// stays on the visitor; visit_sequence is the enclosed logic.
19
class COMPILE_TUPLES is
20
_logger: Logger
21
_innate_symbol_lookup: Semantic.Lookups.InnateSymbolLookup
22
_value_boxer: VALUE_BOXER
23
_visitor: COMPILE_EXPRESSIONS
24
_placeholder_resolver: Semantic.SETTLED_PLACEHOLDER_RESOLVER
25
_match_propagator: Semantic.MATCH_PROPAGATOR
26
27
init(
28
logger: Logger,
29
innate_symbol_lookup: Semantic.Lookups.InnateSymbolLookup,
30
value_boxer: VALUE_BOXER,
31
visitor: COMPILE_EXPRESSIONS
32
) is
33
super.init()
34
35
_logger = logger
36
_innate_symbol_lookup = innate_symbol_lookup
37
_value_boxer = value_boxer
38
_visitor = visitor
39
_placeholder_resolver = Semantic.SETTLED_PLACEHOLDER_RESOLVER()
40
_match_propagator = Semantic.MATCH_PROPAGATOR(logger)
41
si
42
43
pre_tuple(tuple: Trees.Expressions.TUPLE) -> bool is
44
if tuple.elements.expressions.count == 1 then
45
// Single-element TUPLE is a parenthesised expression
46
// (TUPLE.visit unwraps its value). Forward whatever
47
// constraint applies to the outer expression directly
48
// to the inner one — splitting a value-tuple constraint
49
// across a phantom 1-tuple slot would push the wrong
50
// element type down into the inner expression.
51
if tuple.expected_type? then
52
let forward_pack = tuple.compile_expressions_state.pack_marker
53
let forward_slot = tuple.compile_expressions_state.pack_slot
54
55
tuple.elements.expressions[0].set_expected_type(tuple.expected_type, tuple.expected_type_error_message)
56
57
if forward_pack > 0 then
58
tuple.set_expects_pack(forward_pack - 1, forward_slot)
59
fi
60
else
61
tuple.elements.expressions[0].clear_expected_type()
62
fi
63
elif let expected_tuple = _expected_tuple(tuple) then
64
for (element, type) in tuple.elements |> zip(expected_tuple.arguments) do
65
element.set_expected_type(type, tuple.expected_type_error_message)
66
od
67
else
68
for element in tuple.elements do
69
element.clear_expected_type()
70
od
71
fi
72
73
return false
74
si
75
76
// The tuple type the literal's context expects, where it expects one:
77
// an optional tuple context expects the tuple it holds, which the
78
// literal is then wrapped in.
79
_expected_tuple(tuple: Trees.Expressions.TUPLE) -> Type? is
80
if let expected = tuple.expected_type then
81
let unwrapped = expected.optional_inner_type ?? expected
82
83
if unwrapped.is_value_tuple then
84
return unwrapped
85
fi
86
fi
87
88
return null
89
si
90
91
// Whether the literal's context expects a settled type that is not a
92
// tuple, such as `object`: no type it could take would give a bare
93
// `null` element a type, and a tuple holding an element of no type
94
// has no runtime representation.
95
_expects_other_than_tuple(tuple: Trees.Expressions.TUPLE) -> bool is
96
if let expected = tuple.expected_type then
97
let unwrapped = expected.optional_inner_type ?? expected
98
99
return
100
unwrapped.is_settled /\ !unwrapped.is_type_variable /\
101
!unwrapped.is_value_type /\ !unwrapped.is_value_tuple /\ !isa Semantic.Types.TUPLE(unwrapped)
102
fi
103
104
return false
105
si
106
107
visit_tuple(tuple: Trees.Expressions.TUPLE) is
108
// A type ascription on a parenthesised group only means
109
// something when the group turns out to be a lambda's
110
// destructured parameter, which consumes it before any
111
// value is compiled. Reaching here with one still attached
112
// means the group is an ordinary tuple value, where the
113
// ascription has no effect and would otherwise be dropped
114
// in silence.
115
if let tuple.type_expression? then
116
_logger.error(type_expression.location, "type not allowed here")
117
fi
118
119
let names: Collections.LIST[string]? mut = Collections.LIST[string]()
120
let values = Collections.LIST[Value]()
121
let types = Collections.LIST[Type]()
122
123
let element_constraints: Collections.List[Type]? mut = null
124
let expected_type_error_message: string? mut = null
125
126
if let expected_tuple = _expected_tuple(tuple) then
127
element_constraints = expected_tuple.arguments
128
expected_type_error_message = tuple.expected_type_error_message
129
fi
130
131
if tuple.elements.expressions.count == 1 then
132
// A single parenthesised element is a grouped expression,
133
// not a tuple — there are no single-element tuples (a bare
134
// `(x)` is just `x`). A named/typed sole element (`(x = 1)`
135
// / `(x: int)`) is an attempt at one; report it rather than
136
// collapsing to the element's unset value, which would
137
// poison to ERROR and crash IL emission far downstream.
138
if let element: Trees.Expressions.TUPLE_ELEMENT = tuple.elements.expressions[0] then
139
_logger.error(element.location, "single-element tuples are not supported; a tuple needs two or more elements")
140
tuple.compile_expressions_state.value = IR.Values.DUMMY(Semantic.Types.ERROR(), tuple.location)
141
else
142
tuple.compile_expressions_state.value = tuple.elements.expressions[0].value
143
fi
144
return
145
elif tuple.elements.expressions.count == 0 then
146
tuple.compile_expressions_state.value = IR.Values.DUMMY(Semantic.Types.ERROR(), tuple.location)
147
148
_logger.error(tuple.location, "empty tuple")
149
return
150
elif tuple.elements.expressions.count > Semantic.Lookups.INNATE_TYPE_LIMITS.MAX_TUPLE_ELEMENTS then
151
tuple.compile_expressions_state.value = IR.Values.DUMMY(Semantic.Types.ERROR(), tuple.location)
152
153
_logger.error(
154
tuple.location,
155
"a tuple literal cannot have more than {Semantic.Lookups.INNATE_TYPE_LIMITS.MAX_TUPLE_ELEMENTS} elements")
156
return
157
fi
158
159
let is_null_unreachable = _expects_other_than_tuple(tuple)
160
161
let seen_any_named mut = false
162
163
for (index, v) in tuple.elements |> index() do
164
let element_type_constraint =
165
if element_constraints? then
166
element_constraints[index]
167
else
168
null
169
fi
170
171
if isa Trees.Expressions.TUPLE_ELEMENT(v) then
172
let element = v
173
174
seen_any_named = true
175
names.add(element.name.name)
176
177
// An attribute pragma only makes sense on a lambda
178
// parameter — reaching here means the parenthesised
179
// list was never rewritten into one (no `->`/`=>`/
180
// `is`/`rec` followed), so this is a genuine tuple
181
// literal instead.
182
if element.pragmas? then
183
for pragma in element.pragmas do
184
_logger.error(pragma.location, "attribute is not allowed here")
185
od
186
fi
187
188
if element.initializer? then
189
if Value.check_is_consumable(_logger, element.initializer.location, element.initializer.value) then
190
if element.type_expression.type? then
191
let expr_type = element.type_expression.type
192
let type =
193
if element_type_constraint? then
194
element_type_constraint
195
else
196
expr_type
197
fi
198
199
let init_value = element.initializer!.value!
200
201
if element.type_expression.check_is_not_reference(_logger, "tuple element cannot be a ref type") then
202
if !type.is_assignable_from(init_value.type!) then
203
let use qualified = IoC.CONTAINER.instance.name_display.qualifying_alike(init_value.type, type)
204
_logger.error(element.location, "{init_value.type} is not assignable to {type}")
205
elif element_type_constraint? /\ !element_type_constraint.is_assignable_from(expr_type) then
206
let use qualified = IoC.CONTAINER.instance.name_display.qualifying_alike(expr_type, element_type_constraint)
207
_logger.error(
208
element.type_expression.location,
209
string.format(expected_type_error_message!, [expr_type, element_type_constraint]:object))
210
fi
211
fi
212
213
types.add(type)
214
values.add(_value_boxer.box_if_needed(init_value, type))
215
216
elif element_type_constraint? /\ element_type_constraint.is_settled /\ element_type_constraint.is_assignable_from(element.initializer!.value!.type!) then
217
let type = element_type_constraint
218
let init_value = element.initializer!.value!
219
220
types.add(type)
221
values.add(_value_boxer.box_if_needed(init_value, type))
222
elif is_null_unreachable /\ isa Semantic.Types.NULL(element.initializer!.value!.type) then
223
_logger.error(element.initializer!.location, "cannot infer type here")
224
225
values.add(IR.Values.DUMMY(Semantic.Types.ERROR(), element.location))
226
types.add(Semantic.Types.ERROR())
227
else
228
let init_value = element.initializer!.value!
229
types.add(init_value.type!)
230
values.add(init_value)
231
fi
232
233
continue
234
fi
235
else
236
_logger.error(element.location, "tuple element must have a value")
237
fi
238
239
values.add(IR.Values.DUMMY(Semantic.Types.ERROR(), element.location))
240
types.add(Semantic.Types.ERROR())
241
242
elif Value.check_is_consumable(_logger, v.location, v.value) then
243
let v_value = v.value!
244
245
if v.is_identifier then
246
// An unnamed element that is a plain identifier
247
// takes its name from that identifier: `(a, b)`
248
// is `(a = a, b = b)`. TUPLE_ELEMENT_NAME owns
249
// the underscore-strip corner cases.
250
let identifier_name = v.try_copy_as_identifer()!.name
251
let is_field_symbol =
252
isa IR.Values.Load.SYMBOL(v_value) /\
253
v_value.has_symbol /\
254
v_value.symbol.is_field
255
256
names.add(TUPLE_ELEMENT_NAME.infer(identifier_name, is_field_symbol))
257
seen_any_named = true
258
else
259
names.add("{index}")
260
fi
261
262
// An element takes the type of the slot the context
263
// expects only once that type is settled and the element
264
// fits it. Otherwise it keeps its own type, so a slot
265
// still being inferred is bound from the element, and a
266
// misfit is reported once, for the whole tuple, where the
267
// literal is used.
268
if element_type_constraint? /\ element_type_constraint.is_settled /\ element_type_constraint.is_assignable_from(v_value.type!) then
269
let type = element_type_constraint
270
271
types.add(type)
272
values.add(_value_boxer.box_if_needed(v_value, type))
273
elif is_null_unreachable /\ isa Semantic.Types.NULL(v_value.type) then
274
_logger.error(v.location, "cannot infer type here")
275
276
values.add(IR.Values.DUMMY(Semantic.Types.ERROR(), v.location))
277
types.add(Semantic.Types.ERROR())
278
else
279
types.add(v_value.type!)
280
values.add(v_value)
281
fi
282
else
283
values.add(IR.Values.DUMMY(Semantic.Types.ERROR(), v.location))
284
types.add(Semantic.Types.ERROR())
285
fi
286
287
debug_unindent()
288
od
289
290
if !seen_any_named then
291
names = null
292
fi
293
294
let type = _innate_symbol_lookup.get_tuple_type(_placeholder_resolver.resolve_all(types), names)
295
tuple.compile_expressions_state.value = TUPLE(type, values)
296
si
297
298
// The element type of an empty literal nothing around it has
299
// typed. The literal stands as an array of a placeholder while the
300
// body is walked: a sibling it joins with, or a formal it is
301
// passed to, bounds the placeholder, and the next walk types the
302
// literal from that. A placeholder nothing bounds is taken to
303
// object by the fixing step, and null here then lets the caller
304
// take that default.
305
_await_element_type(sequence: Trees.Expressions.SEQUENCE) -> Type? is
306
let function = _visitor.current_function
307
308
if !function? then
309
return null
310
fi
311
312
let origin =
313
Semantic.RESULT_ORIGINS.origin_for(
314
sequence,
315
sequence.location,
316
cast Semantic.Scope(function),
317
"$[]@{sequence.location.start_line}:{sequence.location.start_column}")
318
319
if !origin? \/ Semantic.OBLIGATIONS.has_default_for(origin) then
320
return null
321
fi
322
323
origin.description = "the element type of this list literal"
324
325
let inferred = origin.try_get_inferred_type()
326
327
if inferred? /\ inferred.is_settled then
328
return inferred
329
fi
330
331
let placeholder = Semantic.Types.INFERRED_VARIABLE_TYPE(origin)
332
333
Semantic.OBLIGATIONS.defer(Semantic.OBLIGATIONS.EMPTY_LITERAL, placeholder, sequence.location)
334
335
return placeholder
336
si
337
338
visit_sequence(sequence: Trees.Expressions.SEQUENCE) is
339
let type: Type? mut = _
340
let have_explicit_type: bool mut = _
341
342
let elements = Collections.LIST[Trees.Expressions.Expression](sequence.elements)
343
344
let constraint_type: Type? mut = _
345
if let sequence.expected_type? then
346
constraint_type = expected_type.get_element_type()
347
fi
348
349
if !isa Trees.TypeExpressions.INFER(sequence.type_expression) then
350
if sequence.type_expression.type? then
351
type = sequence.type_expression.type
352
353
have_explicit_type = true
354
else
355
// FIXME probably not needed - type pass will have given an error
356
_logger.error(sequence.type_expression.location, "bad explicit type expression")
357
return
358
fi
359
elif elements.count == 0 then
360
if constraint_type? then
361
type = constraint_type
362
have_explicit_type = true
363
elif let awaited = _await_element_type(sequence) then
364
type = awaited
365
else
366
// No elements to infer from, no constraint pushed by
367
// the surrounding context, and nothing the walks
368
// recorded against the element type: fall back to an
369
// object element type, the same as a literal whose
370
// elements are all null.
371
_logger.hint(
372
sequence.location,
373
"infer-object-from-list-literal",
374
"list literal element type inferred as object",
375
sequence.location,
376
"help: give the literal an explicit type")
377
378
type = _innate_symbol_lookup.get_object_type()
379
fi
380
else
381
let seen_any mut = false
382
let seen_error mut = false
383
let all_tuple_literals mut = elements.count > 0 // assume all tuples until proved otherwise
384
let tuples_element_count mut = -1
385
let any_tuple_argument_is_null mut = false
386
let lub = LEAST_UPPER_BOUND_MAP()
387
388
for v in elements do
389
let is_tuple =
390
v.is_tuple_literal \/
391
(v.value? /\ v.value.type? /\ (v.value.type.is_value_tuple \/ isa Semantic.Types.TUPLE(v.value.type)) /\ !v.value.type.is_optional)
392
393
if !is_tuple then
394
all_tuple_literals = false
395
fi
396
397
if let v.value? /\ value.type? then
398
if value.check_is_consumable(_logger, v.location) then
399
if value.type!.is_inferred then
400
// A placeholder answers `is_null`, so it is
401
// added to the join here, ahead of the null
402
// literal's own handling.
403
lub.add(value.type!)
404
elif !value.type!.is_null then
405
seen_any = true
406
lub.add(value.type!)
407
elif value.type!.is_error then
408
seen_error = true
409
fi
410
411
if is_tuple then
412
if tuples_element_count == -1 then
413
tuples_element_count = value.type!.arguments.count
414
elif value.type!.arguments.count != tuples_element_count then
415
all_tuple_literals = false
416
fi
417
418
// `Types.NULL.matches` answers true against
419
// any type, so a naive structural LUB over
420
// the whole tuple types below judges a
421
// `null`-carrying tuple argument position
422
// "the same as" a value-carrying one at a
423
// sibling element and picks one arbitrarily,
424
// instead of widening that position to its
425
// optional carrier. Route around the naive
426
// LUB and straight to the per-position
427
// TUPLE_ELEMENT_LUB whenever that can happen.
428
if value.type!.arguments |> any(a => a.is_null /\ !a.is_inferred) then
429
any_tuple_argument_is_null = true
430
fi
431
fi
432
else
433
seen_error = true
434
fi
435
else
436
seen_error = true
437
fi
438
od
439
440
if !type? then
441
type = lub.get_result()
442
443
// The join waits for an element whose type is still
444
// being inferred - a local assigned later in the body -
445
// so the literal waits with it rather than settling
446
// whatever it is assigned to at a type that element may
447
// not fit.
448
if type? /\ type.is_inferred /\ !constraint_type? then
449
_logger.mark_consumed_any()
450
_logger.error(sequence.location, "cannot infer type here")
451
452
sequence.compile_expressions_state.value = DUMMY(_innate_symbol_lookup.get_array_type(Semantic.Types.ERROR()), sequence.location)
453
return
454
fi
455
456
if all_tuple_literals /\ (!type? \/ !type.is_value_tuple \/ any_tuple_argument_is_null) then
457
let tuple_types = Collections.LIST[Type]()
458
459
for element in elements do
460
if let element.value? /\ value.type? then
461
tuple_types.add(value.type)
462
fi
463
od
464
465
// The join builds a tuple of as many elements as
466
// the widest element has, so an element that is
467
// not a usable tuple - one already reported, or
468
// one past the element limit - has no tuple type
469
// to join into. The element's own diagnostic is
470
// the one worth keeping.
471
if
472
tuple_types |> any(t =>
473
t.is_error \/
474
t.arguments.count == 0 \/
475
t.arguments.count >
476
Semantic.Lookups.INNATE_TYPE_LIMITS.MAX_TUPLE_ELEMENTS)
477
then
478
sequence.compile_expressions_state.value =
479
DUMMY(_innate_symbol_lookup.get_array_type(Semantic.Types.ERROR()), sequence.location)
480
481
return
482
fi
483
484
type = Semantic.TUPLE_ELEMENT_LUB(_innate_symbol_lookup).combine(tuple_types, lub.element_names)
485
486
let use retry_site = RETRY_SITE_STATS.enter("tuples.sequence_element_rewalk")
487
// going to walk the elements again, so roll back
488
// and re-speculate to avoid duplicate / misleading
489
// error messages
490
_logger.roll_back()
491
_logger.speculate()
492
493
// re-walk the type expression if present, to avoid
494
// hiding any error message it may generate
495
496
sequence.type_expression.walk(_visitor)
497
498
for e in sequence.elements do
499
e.set_expected_type(type, "element type {{0}} not compatible with inferred list type {{1}}")
500
_visitor.rewalk(e)
501
od
502
fi
503
fi
504
505
// Reconcile bottom-up LUB with any constraint pushed
506
// by the parent context. Prefer the more-specific
507
// bottom-up type when it satisfies the constraint —
508
// that preserves the runtime allocation precision the
509
// covariance idiom relies on (e.g. `let ao: object[]
510
// = ["a", "b"];` should produce a string[] at run
511
// time, even though the variable is declared
512
// object[]). When the LUB doesn't satisfy the
513
// constraint, fall back to the constraint's element
514
// type and drive per-element mismatch errors via the
515
// post-walk assignability check.
516
if constraint_type? then
517
if !type? \/ !constraint_type.is_assignable_from(type) then
518
type = constraint_type
519
have_explicit_type = true
520
fi
521
fi
522
523
if !type? then
524
if seen_error then
525
sequence.compile_expressions_state.value = DUMMY(_innate_symbol_lookup.get_array_type(Semantic.Types.ERROR()), sequence.location)
526
return
527
elif seen_any then
528
_logger.hint(
529
sequence.location,
530
"infer-object-from-list-literal",
531
"list literal element type inferred as object",
532
sequence.location,
533
"help: give the literal an explicit type")
534
type = _innate_symbol_lookup.get_object_type()
535
else
536
_logger.error(sequence.location, "cannot infer type of list literal with only null elements")
537
538
sequence.compile_expressions_state.value = DUMMY(_innate_symbol_lookup.get_array_type(Semantic.Types.ERROR()), sequence.location)
539
return
540
fi
541
fi
542
fi
543
544
let values = Collections.LIST[Value](sequence.elements.expressions.count)
545
546
for v in sequence.elements do
547
if let v.value? /\ value.type? then
548
let u = value.type
549
550
// An element whose own type is still being inferred - a
551
// local the body types from its uses - is one of those
552
// uses, so the element type the literal settled on is
553
// pushed back to it as a bound. The propagation recurses
554
// into generic arguments, so an element with a
555
// placeholder anywhere inside it is one to push into.
556
if u.contains_inferred then
557
_match_propagator.propagate_match(type, u)
558
559
values.add(v.value!)
560
561
continue
562
fi
563
564
// FIXME should push explicit type into element as constraint and retry
565
if have_explicit_type /\ !type.is_assignable_from(u) then
566
_logger.error(v.location, "element not compatible with explicit type")
567
fi
568
569
values.add(v.value!)
570
else
571
values.add(DUMMY(Semantic.Types.ERROR(), v.location))
572
fi
573
od
574
575
sequence.compile_expressions_state.value =
576
SEQUENCE(_innate_symbol_lookup.get_array_type(type), type, values)
577
si
578
si
579
si