forked from carbon-language/carbon-lang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandle_binding_pattern.cpp
More file actions
448 lines (407 loc) · 18.3 KB
/
handle_binding_pattern.cpp
File metadata and controls
448 lines (407 loc) · 18.3 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
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
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "toolchain/check/context.h"
#include "toolchain/check/convert.h"
#include "toolchain/check/facet_type.h"
#include "toolchain/check/handle.h"
#include "toolchain/check/inst.h"
#include "toolchain/check/interface.h"
#include "toolchain/check/name_lookup.h"
#include "toolchain/check/pattern.h"
#include "toolchain/check/return.h"
#include "toolchain/check/type.h"
#include "toolchain/check/type_completion.h"
#include "toolchain/diagnostics/format_providers.h"
#include "toolchain/parse/node_ids.h"
#include "toolchain/sem_ir/ids.h"
#include "toolchain/sem_ir/inst.h"
#include "toolchain/sem_ir/pattern.h"
#include "toolchain/sem_ir/typed_insts.h"
namespace Carbon::Check {
auto HandleParseNode(Context& context, Parse::UnderscoreNameId node_id)
-> bool {
context.node_stack().Push(node_id, SemIR::NameId::Underscore);
return true;
}
// TODO: make this function shorter by factoring pieces out.
static auto HandleAnyBindingPattern(Context& context, Parse::NodeId node_id,
Parse::NodeKind node_kind) -> bool {
// TODO: split this into smaller, more focused functions.
auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
auto [cast_type_inst_id, cast_type_id] =
ExprAsType(context, type_node, parsed_type_id);
SemIR::ExprRegionId type_expr_region_id =
EndSubpatternAsExpr(context, cast_type_inst_id);
// The name in a generic binding may be wrapped in `template`.
bool is_generic = node_kind == Parse::NodeKind::CompileTimeBindingPattern;
bool is_template =
context.node_stack()
.PopAndDiscardSoloNodeIdIf<Parse::NodeKind::TemplateBindingName>();
// A non-generic template binding is diagnosed by the parser.
is_template &= is_generic;
// The name in a runtime binding may be wrapped in `ref`.
bool is_ref =
context.node_stack()
.PopAndDiscardSoloNodeIdIf<Parse::NodeKind::RefBindingName>();
SemIR::InstKind pattern_inst_kind;
switch (node_kind) {
case Parse::NodeKind::CompileTimeBindingPattern:
pattern_inst_kind = SemIR::InstKind::SymbolicBindingPattern;
break;
case Parse::NodeKind::LetBindingPattern:
if (is_ref) {
pattern_inst_kind = SemIR::InstKind::RefBindingPattern;
} else {
pattern_inst_kind = SemIR::InstKind::ValueBindingPattern;
}
break;
case Parse::NodeKind::VarBindingPattern:
pattern_inst_kind = SemIR::InstKind::RefBindingPattern;
break;
default:
CARBON_FATAL("Unexpected node kind: {0}", node_kind);
}
auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
const DeclIntroducerState& introducer =
context.decl_introducer_state_stack().innermost();
auto make_binding_pattern = [&]() -> SemIR::InstId {
// TODO: Eventually the name will need to support associations with other
// scopes, but right now we don't support qualified names here.
auto binding =
AddBindingPattern(context, name_node, name_id, cast_type_id,
type_expr_region_id, pattern_inst_kind, is_template);
// TODO: If `is_generic`, then `binding.bind_id is a SymbolicBinding. Subst
// the `.Self` of type `type` in the `cast_type_id` type (a `FacetType`)
// with the `binding.bind_id` itself, and build a new pattern with that.
// This is kind of cyclical. So we need to reuse the EntityNameId, which
// will also reuse the CompileTimeBinding for the new SymbolicBinding.
if (name_id != SemIR::NameId::Underscore) {
// Add name to lookup immediately, so it can be used in the rest of the
// enclosing pattern.
auto name_context =
context.decl_name_stack().MakeUnqualifiedName(name_node, name_id);
context.decl_name_stack().AddNameOrDiagnose(
name_context, binding.bind_id,
introducer.modifier_set.GetAccessKind());
context.full_pattern_stack().AddBindName(name_id);
}
return binding.pattern_id;
};
// A `self` binding can only appear in an implicit parameter list.
if (name_id == SemIR::NameId::SelfValue &&
!context.node_stack().PeekIs(Parse::NodeKind::ImplicitParamListStart)) {
CARBON_DIAGNOSTIC(
SelfOutsideImplicitParamList, Error,
"`self` can only be declared in an implicit parameter list");
context.emitter().Emit(node_id, SelfOutsideImplicitParamList);
}
// Allocate an instruction of the appropriate kind, linked to the name for
// error locations.
switch (context.full_pattern_stack().CurrentKind()) {
case FullPatternStack::Kind::ImplicitParamList:
case FullPatternStack::Kind::ExplicitParamList: {
// Parameters can have incomplete types in a function declaration, but not
// in a function definition. We don't know which kind we have here.
bool had_error = false;
switch (introducer.kind) {
case Lex::TokenKind::Fn: {
if (context.full_pattern_stack().CurrentKind() ==
FullPatternStack::Kind::ImplicitParamList &&
!(is_generic || name_id == SemIR::NameId::SelfValue)) {
CARBON_DIAGNOSTIC(
ImplictParamMustBeConstant, Error,
"implicit parameters of functions must be constant or `self`");
context.emitter().Emit(node_id, ImplictParamMustBeConstant);
had_error = true;
}
break;
}
case Lex::TokenKind::Choice:
if (context.scope_stack().PeekInstId().has_value()) {
// We are building a pattern for a choice alternative, not the
// choice type itself.
// Implicit param lists are prevented during parse.
CARBON_CHECK(context.full_pattern_stack().CurrentKind() !=
FullPatternStack::Kind::ImplicitParamList,
"choice alternative with implicit parameters");
// Don't fall through to the `Class` logic for choice alternatives.
break;
}
[[fallthrough]];
case Lex::TokenKind::Class:
case Lex::TokenKind::Impl:
case Lex::TokenKind::Interface: {
if (name_id == SemIR::NameId::SelfValue) {
CARBON_DIAGNOSTIC(SelfParameterNotAllowed, Error,
"`self` parameter only allowed on functions");
context.emitter().Emit(node_id, SelfParameterNotAllowed);
had_error = true;
} else if (!is_generic) {
CARBON_DIAGNOSTIC(GenericParamMustBeConstant, Error,
"parameters of generic types must be constant");
context.emitter().Emit(node_id, GenericParamMustBeConstant);
had_error = true;
}
break;
}
default:
break;
}
auto result_inst_id = SemIR::InstId::None;
if (had_error) {
if (name_id != SemIR::NameId::Underscore) {
AddNameToLookup(context, name_id, SemIR::ErrorInst::InstId);
}
// Replace the parameter with `ErrorInst` so that we don't try
// constructing a generic based on it.
result_inst_id = SemIR::ErrorInst::InstId;
} else {
result_inst_id = make_binding_pattern();
// A binding pattern in a function signature is a `Call` parameter
// unless it's nested inside a `var` pattern (because then the
// enclosing `var` pattern is), or it's a compile-time binding pattern
// (because then it's not passed to the `Call` inst).
if (node_kind == Parse::NodeKind::LetBindingPattern) {
if (is_ref) {
result_inst_id = AddPatternInst<SemIR::RefParamPattern>(
context, node_id,
{.type_id = context.insts().Get(result_inst_id).type_id(),
.subpattern_id = result_inst_id,
.index = SemIR::CallParamIndex::None});
} else {
result_inst_id = AddPatternInst<SemIR::ValueParamPattern>(
context, node_id,
{.type_id = context.insts().Get(result_inst_id).type_id(),
.subpattern_id = result_inst_id,
.index = SemIR::CallParamIndex::None});
}
}
}
context.node_stack().Push(node_id, result_inst_id);
break;
}
case FullPatternStack::Kind::NameBindingDecl: {
auto incomplete_diagnoser = [&] {
CARBON_DIAGNOSTIC(IncompleteTypeInBindingDecl, Error,
"binding pattern has incomplete type {0} in name "
"binding declaration",
InstIdAsType);
return context.emitter().Build(type_node, IncompleteTypeInBindingDecl,
cast_type_inst_id);
};
if (node_kind == Parse::NodeKind::VarBindingPattern) {
cast_type_id = AsConcreteType(
context, cast_type_id, type_node, incomplete_diagnoser, [&] {
CARBON_DIAGNOSTIC(
AbstractTypeInVarPattern, Error,
"binding pattern has abstract type {0} in `var` "
"pattern",
SemIR::TypeId);
return context.emitter().Build(
type_node, AbstractTypeInVarPattern, cast_type_id);
});
} else {
cast_type_id = AsCompleteType(context, cast_type_id, type_node,
incomplete_diagnoser);
}
auto binding_pattern_id = make_binding_pattern();
if (node_kind == Parse::NodeKind::VarBindingPattern) {
CARBON_CHECK(!is_generic);
if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Returned)) {
// TODO: Should we check this for the `var` as a whole, rather than
// for the name binding?
auto bind_id = context.bind_name_map()
.Lookup(binding_pattern_id)
.value()
.bind_name_id;
RegisterReturnedVar(context,
introducer.modifier_node_id(ModifierOrder::Decl),
type_node, cast_type_id, bind_id);
}
}
context.node_stack().Push(node_id, binding_pattern_id);
break;
}
}
return true;
}
auto HandleParseNode(Context& context, Parse::LetBindingPatternId node_id)
-> bool {
return HandleAnyBindingPattern(context, node_id,
Parse::NodeKind::LetBindingPattern);
}
auto HandleParseNode(Context& context, Parse::VarBindingPatternId node_id)
-> bool {
return HandleAnyBindingPattern(context, node_id,
Parse::NodeKind::VarBindingPattern);
}
auto HandleParseNode(Context& context,
Parse::CompileTimeBindingPatternStartId node_id) -> bool {
// Make a scope to contain the `.Self` facet value for use in the type of the
// compile time binding. This is popped when handling the
// CompileTimeBindingPatternId.
context.scope_stack().PushForSameRegion();
// The `.Self` must have a type of `FacetType`, so that it gets wrapped in
// `FacetAccessType` when used in a type position, such as in `U:! I(.Self)`.
// This allows substitution with other facet values without requiring an
// additional `FacetAccessType` to be inserted.
SemIR::FacetTypeId facet_type_id =
context.facet_types().Add(SemIR::FacetTypeInfo{});
auto const_id = EvalOrAddInst<SemIR::FacetType>(
context, node_id,
{.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id});
auto type_id = context.types().GetTypeIdForTypeConstantId(const_id);
MakePeriodSelfFacetValue(context, type_id);
return true;
}
auto HandleParseNode(Context& context,
Parse::CompileTimeBindingPatternId node_id) -> bool {
// Pop the `.Self` facet value name introduced by the
// CompileTimeBindingPatternStart.
context.scope_stack().Pop();
auto node_kind = Parse::NodeKind::CompileTimeBindingPattern;
const DeclIntroducerState& introducer =
context.decl_introducer_state_stack().innermost();
if (introducer.kind == Lex::TokenKind::Let) {
// Disallow `let` outside of function and interface definitions.
// TODO: Find a less brittle way of doing this. A `scope_inst_id` of `None`
// can represent a block scope, but is also used for other kinds of scopes
// that aren't necessarily part of a function decl.
// We don't need to check if the scope is an interface here as this is
// already caught in the parse phase by the separated associated constant
// logic.
auto scope_inst_id = context.scope_stack().PeekInstId();
if (scope_inst_id.has_value()) {
auto scope_inst = context.insts().Get(scope_inst_id);
if (!scope_inst.Is<SemIR::FunctionDecl>()) {
context.TODO(
node_id,
"`let` compile time binding outside function or interface");
node_kind = Parse::NodeKind::LetBindingPattern;
}
}
}
return HandleAnyBindingPattern(context, node_id, node_kind);
}
auto HandleParseNode(Context& context,
Parse::AssociatedConstantNameAndTypeId node_id) -> bool {
auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
auto [cast_type_inst_id, cast_type_id] =
ExprAsType(context, type_node, parsed_type_id);
EndSubpatternAsExpr(context, cast_type_inst_id);
auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
if (name_id == SemIR::NameId::Underscore) {
// The action item here may be to document this as not allowed, and
// add a proper diagnostic.
context.TODO(node_id, "_ used as associated constant name");
}
cast_type_id = AsCompleteType(context, cast_type_id, type_node, [&] {
CARBON_DIAGNOSTIC(IncompleteTypeInAssociatedConstantDecl, Error,
"associated constant has incomplete type {0}",
SemIR::TypeId);
return context.emitter().Build(
type_node, IncompleteTypeInAssociatedConstantDecl, cast_type_id);
});
SemIR::AssociatedConstantDecl assoc_const_decl = {
.type_id = cast_type_id,
.assoc_const_id = SemIR::AssociatedConstantId::None,
.decl_block_id = SemIR::InstBlockId::None};
auto decl_id =
AddPlaceholderInstInNoBlock(context, node_id, assoc_const_decl);
assoc_const_decl.assoc_const_id = context.associated_constants().Add(
{.name_id = name_id,
.parent_scope_id = context.scope_stack().PeekNameScopeId(),
.decl_id = decl_id,
.generic_id = SemIR::GenericId::None,
.default_value_id = SemIR::InstId::None});
ReplaceInstBeforeConstantUse(context, decl_id, assoc_const_decl);
context.node_stack().Push(node_id, decl_id);
return true;
}
auto HandleParseNode(Context& context, Parse::FieldNameAndTypeId node_id)
-> bool {
auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
auto [cast_type_inst_id, cast_type_id] =
ExprAsType(context, type_node, parsed_type_id);
auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
auto parent_class_decl =
context.scope_stack().GetCurrentScopeAs<SemIR::ClassDecl>();
CARBON_CHECK(parent_class_decl);
cast_type_id = AsConcreteType(
context, cast_type_id, type_node,
[&] {
CARBON_DIAGNOSTIC(IncompleteTypeInFieldDecl, Error,
"field has incomplete type {0}", SemIR::TypeId);
return context.emitter().Build(type_node, IncompleteTypeInFieldDecl,
cast_type_id);
},
[&] {
CARBON_DIAGNOSTIC(AbstractTypeInFieldDecl, Error,
"field has abstract type {0}", SemIR::TypeId);
return context.emitter().Build(type_node, AbstractTypeInFieldDecl,
cast_type_id);
});
if (cast_type_id == SemIR::ErrorInst::TypeId) {
cast_type_inst_id = SemIR::ErrorInst::TypeInstId;
}
auto& class_info = context.classes().Get(parent_class_decl->class_id);
auto field_type_id = GetUnboundElementType(
context, context.types().GetInstId(class_info.self_type_id),
cast_type_inst_id);
auto field_id =
AddInst<SemIR::FieldDecl>(context, node_id,
{.type_id = field_type_id,
.name_id = name_id,
.index = SemIR::ElementIndex::None});
context.field_decls_stack().AppendToTop(field_id);
auto name_context =
context.decl_name_stack().MakeUnqualifiedName(node_id, name_id);
context.decl_name_stack().AddNameOrDiagnose(
name_context, field_id,
context.decl_introducer_state_stack()
.innermost()
.modifier_set.GetAccessKind());
return true;
}
auto HandleParseNode(Context& context, Parse::AddrId node_id) -> bool {
auto param_pattern_id = context.node_stack().PopPattern();
if (SemIR::IsSelfPattern(context.sem_ir(), param_pattern_id)) {
auto param_type_id = ExtractScrutineeType(
context.sem_ir(), context.insts().Get(param_pattern_id).type_id());
auto pointer_type =
context.types().TryGetAs<SemIR::PointerType>(param_type_id);
if (pointer_type) {
auto addr_pattern_id = AddPatternInst<SemIR::AddrPattern>(
context, node_id,
{.type_id = GetPatternType(
context, GetSingletonType(context, SemIR::AutoType::TypeInstId)),
.inner_id = param_pattern_id});
context.node_stack().Push(node_id, addr_pattern_id);
} else {
CARBON_DIAGNOSTIC(
AddrOnNonPointerType, Error,
"`addr` can only be applied to a binding with a pointer type");
context.emitter().Emit(node_id, AddrOnNonPointerType);
context.node_stack().Push(node_id, param_pattern_id);
}
} else {
CARBON_DIAGNOSTIC(AddrOnNonSelfParam, Error,
"`addr` can only be applied to a `self` parameter");
context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
AddrOnNonSelfParam);
context.node_stack().Push(node_id, param_pattern_id);
}
return true;
}
auto HandleParseNode(Context& context, Parse::RefBindingNameId node_id)
-> bool {
context.node_stack().Push(node_id);
return true;
}
auto HandleParseNode(Context& context, Parse::TemplateBindingNameId node_id)
-> bool {
context.node_stack().Push(node_id);
return true;
}
} // namespace Carbon::Check