1mod asm;
5mod format_args;
6mod generics;
7mod path;
8
9use std::{cell::OnceCell, mem};
10
11use base_db::{FxIndexSet, SourceDatabase};
12use cfg::CfgOptions;
13use either::Either;
14use hir_expand::{
15 HirFileId, InFile, MacroDefId,
16 mod_path::ModPath,
17 name::{AsName, Name},
18 span_map::SpanMap,
19};
20use intern::{Symbol, sym};
21use itertools::Itertools;
22use rustc_abi::ExternAbi;
23use rustc_hash::FxHashMap;
24use smallvec::SmallVec;
25use stdx::never;
26use syntax::{
27 AstNode, AstPtr, SyntaxNodePtr,
28 ast::{
29 self, ArrayExprKind, AstChildren, BlockExpr, ForBinder, HasArgList, HasGenericArgs,
30 HasGenericParams, HasLoopBody, HasName, HasTypeBounds, IsString, RangeItem,
31 SlicePatComponents,
32 },
33};
34use thin_vec::ThinVec;
35use tt::TextRange;
36
37use crate::{
38 AdtId, BlockId, BlockIdLt, ConstId, DefWithBodyId, FunctionId, GenericDefId, HasModule, ImplId,
39 ItemContainerId, LoweringMode, MacroId, ModuleDefId, ModuleId, TraitId, TypeAliasId,
40 UnresolvedMacro,
41 attrs::AttrFlags,
42 expr_store::{
43 Body, BodySourceMap, ExprPtr, ExprRoot, ExpressionStore, ExpressionStoreBuilder,
44 ExpressionStoreDiagnostics, ExpressionStoreSourceMap, HygieneId, LabelPtr, LifetimePtr,
45 MissingBodyItemKind, PatPtr, StoreVisitor, TypePtr,
46 body::Param,
47 expander::Expander,
48 lower::generics::ImplTraitLowerFn,
49 path::{AssociatedTypeBinding, GenericArg, GenericArgs, GenericArgsParentheses, Path},
50 },
51 hir::{
52 Array, Binding, BindingAnnotation, BindingId, BindingProblems, CaptureBy, ClosureKind,
53 CoroutineKind, CoroutineSource, Expr, ExprId, Item, Label, LabelId, Literal, LoopSource,
54 MatchArm, Movability, OffsetOf, Pat, PatId, RecordFieldPat, RecordLitField, RecordSpread,
55 Statement, Unsafe, generics::GenericParams,
56 },
57 item_scope::BuiltinShadowMode,
58 lang_item::{LangItemTarget, LangItems},
59 nameres::{DefMap, LocalDefMap, MacroSubNs, block_def_map},
60 signatures::TypeAliasSignature,
61 type_ref::{
62 ArrayType, ConstRef, FnType, LifetimeRef, LifetimeRefId, Mutability, PathId, Rawness,
63 RefType, TraitBoundModifier, TraitRef, TypeBound, TypeRef, TypeRefId, UseArgRef,
64 },
65 unstable_features::UnstableFeatures,
66};
67
68pub use self::path::hir_segment_to_ast_segment;
69
70pub(super) fn lower_body(
71 db: &dyn SourceDatabase,
72 owner: DefWithBodyId,
73 syntax_node: SyntaxNodePtr,
74 current_file_id: HirFileId,
75 module: ModuleId,
76 parameters: Option<ast::ParamList>,
77 body: Option<ast::Expr>,
78 is_async_fn: bool,
79 is_gen_fn: bool,
80) -> (Body, BodySourceMap) {
81 let mut self_param = None;
88 let mut source_map_self_param = None;
89 let mut params = vec![];
90 let mut collector = ExprCollector::new(db, module, current_file_id, LoweringMode::Analysis);
91
92 let skip_body = AttrFlags::query(
93 db,
94 match owner {
95 DefWithBodyId::FunctionId(it) => it.into(),
96 DefWithBodyId::StaticId(it) => it.into(),
97 DefWithBodyId::ConstId(it) => it.into(),
98 DefWithBodyId::VariantId(it) => it.into(),
99 },
100 )
101 .contains(AttrFlags::RUST_ANALYZER_SKIP);
102 if skip_body {
105 collector.with_expr_root(|collector| {
106 if let Some(param_list) = parameters {
107 if let Some(self_param_syn) =
108 param_list.self_param().filter(|self_param| collector.check_cfg(self_param))
109 {
110 let is_mutable = self_param_syn.mut_token().is_some()
111 && self_param_syn.amp_token().is_none();
112 let hygiene = self_param_syn
113 .name()
114 .map(|name| collector.hygiene_id_for(name.syntax().text_range()))
115 .unwrap_or(HygieneId::ROOT);
116 let binding_id: la_arena::Idx<Binding> = collector.alloc_binding(
117 Name::new_symbol_root(sym::self_),
118 BindingAnnotation::new(is_mutable, false),
119 hygiene,
120 );
121 self_param = Some(Param::new(binding_id));
122 source_map_self_param =
123 Some(collector.expander.in_file(AstPtr::new(&self_param_syn)));
124 }
125 let count = param_list.params().filter(|it| collector.check_cfg(it)).count();
126 params = (0..count).map(|_| Param::new(collector.missing_pat())).collect();
127 };
128
129 collector.missing_expr()
130 });
131 let (store, source_map) = collector.store.finish();
132 return (
133 Body { store, params: params.into_boxed_slice(), self_param },
134 BodySourceMap { self_param: source_map_self_param, store: source_map },
135 );
136 }
137 validate_required_body(db, owner, current_file_id, syntax_node, body.as_ref(), &mut collector);
138 collector.with_expr_root(|collector| {
139 if let DefWithBodyId::FunctionId(func) = owner
140 && let Some(param_list) = parameters
141 {
142 if let Some(self_param_syn) =
143 param_list.self_param().filter(|it| collector.check_cfg(it))
144 {
145 let is_mutable =
146 self_param_syn.mut_token().is_some() && self_param_syn.amp_token().is_none();
147 let hygiene = self_param_syn
148 .name()
149 .map(|name| collector.hygiene_id_for(name.syntax().text_range()))
150 .unwrap_or(HygieneId::ROOT);
151 let binding_id: la_arena::Idx<Binding> = collector.alloc_binding(
152 Name::new_symbol_root(sym::self_),
153 BindingAnnotation::new(is_mutable, false),
154 hygiene,
155 );
156 self_param = Some(Param::new(binding_id));
157 source_map_self_param =
158 Some(collector.expander.in_file(AstPtr::new(&self_param_syn)));
159 }
160
161 let params_are_bare_idents = match func.loc(db).container {
162 ItemContainerId::ExternBlockId(_) => true,
163 ItemContainerId::TraitId(_) => body.is_none(),
164 ItemContainerId::ModuleId(_) | ItemContainerId::ImplId(_) => false,
165 };
166
167 for param in param_list.params() {
168 if collector.check_cfg(¶m) {
169 let param_pat = match param.pat() {
170 Some(pat) => {
171 if params_are_bare_idents {
172 collector.collect_param_as_ident(pat)
173 } else {
174 collector.collect_pat_top(Some(pat))
175 }
176 }
177 None => collector.missing_pat(),
178 };
179 params.push(Param::new(param_pat));
180 }
181 }
182 }
183
184 collector.collect(
185 &mut self_param,
186 &mut params,
187 body,
188 if is_async_fn {
189 Awaitable::Yes
190 } else {
191 match owner {
192 DefWithBodyId::FunctionId(..) => Awaitable::No("non-async function"),
193 DefWithBodyId::StaticId(..) => Awaitable::No("static"),
194 DefWithBodyId::ConstId(..) => Awaitable::No("constant"),
195 DefWithBodyId::VariantId(..) => Awaitable::No("enum variant"),
196 }
197 },
198 is_async_fn,
199 is_gen_fn,
200 )
201 });
202
203 let (store, source_map) = collector.store.finish();
204 (
205 Body { store, params: params.into_boxed_slice(), self_param },
206 BodySourceMap { self_param: source_map_self_param, store: source_map },
207 )
208}
209
210fn validate_required_body(
211 db: &(dyn SourceDatabase + 'static),
212 owner: DefWithBodyId,
213 current_file_id: HirFileId,
214 syntax_node: SyntaxNodePtr,
215 body: Option<&ast::Expr>,
216 collector: &mut ExprCollector<'_>,
217) {
218 if body.is_some() {
219 return;
220 }
221 let diagnostic_kind = match owner {
222 DefWithBodyId::FunctionId(_function_id) => None,
225 DefWithBodyId::StaticId(id) => match id.loc(db).container {
226 ItemContainerId::ModuleId(_) => Some(MissingBodyItemKind::Static),
227 ItemContainerId::ExternBlockId(_)
228 | ItemContainerId::ImplId(_)
229 | ItemContainerId::TraitId(_) => None,
230 },
231 DefWithBodyId::ConstId(id) => match id.loc(db).container {
232 ItemContainerId::ModuleId(_) => Some(MissingBodyItemKind::Const),
233 ItemContainerId::ImplId(_) => Some(MissingBodyItemKind::AssocConst),
234 ItemContainerId::ExternBlockId(_) | ItemContainerId::TraitId(_) => None,
235 },
236 DefWithBodyId::VariantId(_) => None,
237 };
238 if let Some(kind) = diagnostic_kind {
239 let node = InFile::new(current_file_id, syntax_node);
240 collector.store.diagnostics.push(ExpressionStoreDiagnostics::MissingBody { node, kind });
241 }
242}
243
244pub(crate) fn lower_type_ref(
245 db: &dyn SourceDatabase,
246 module: ModuleId,
247 type_ref: InFile<Option<ast::Type>>,
248) -> (ExpressionStore, ExpressionStoreSourceMap, TypeRefId) {
249 let mut expr_collector =
250 ExprCollector::new(db, module, type_ref.file_id, LoweringMode::Analysis);
251 let type_ref =
252 expr_collector.lower_type_ref_opt(type_ref.value, &mut ExprCollector::impl_trait_allocator);
253 let (store, source_map) = expr_collector.store.finish();
254 (store, source_map, type_ref)
255}
256
257pub fn lower_generic_params(
258 db: &dyn SourceDatabase,
259 module: ModuleId,
260 def: GenericDefId,
261 file_id: HirFileId,
262 param_list: Option<ast::GenericParamList>,
263 where_clause: Option<ast::WhereClause>,
264 mode: LoweringMode,
265) -> (ExpressionStore, GenericParams, ExpressionStoreSourceMap) {
266 let mut expr_collector = ExprCollector::new(db, module, file_id, mode);
267 let mut collector = generics::GenericParamsCollector::new(def);
268 collector.lower(&mut expr_collector, param_list, where_clause);
269 let params = collector.finish();
270 let (store, source_map) = expr_collector.store.finish();
271 (store, params, source_map)
272}
273
274pub(crate) fn lower_impl(
275 db: &dyn SourceDatabase,
276 module: ModuleId,
277 impl_syntax: InFile<ast::Impl>,
278 impl_id: ImplId,
279) -> (ExpressionStore, ExpressionStoreSourceMap, TypeRefId, Option<TraitRef>, GenericParams) {
280 let mut expr_collector =
281 ExprCollector::new(db, module, impl_syntax.file_id, LoweringMode::Analysis);
282 let self_ty =
283 expr_collector.lower_type_ref_opt_disallow_impl_trait(impl_syntax.value.self_ty());
284 let trait_ = impl_syntax.value.trait_().and_then(|it| match &it {
285 ast::Type::PathType(path_type) => {
286 let path = expr_collector
287 .lower_path_type(path_type, &mut ExprCollector::impl_trait_allocator)?;
288 Some(TraitRef { path: expr_collector.alloc_path(path, AstPtr::new(&it)) })
289 }
290 _ => None,
291 });
292 let mut collector = generics::GenericParamsCollector::new(impl_id.into());
293 collector.lower(
294 &mut expr_collector,
295 impl_syntax.value.generic_param_list(),
296 impl_syntax.value.where_clause(),
297 );
298 let params = collector.finish();
299 let (store, source_map) = expr_collector.store.finish();
300 (store, source_map, self_ty, trait_, params)
301}
302
303pub(crate) fn lower_trait(
304 db: &dyn SourceDatabase,
305 module: ModuleId,
306 trait_syntax: InFile<ast::Trait>,
307 trait_id: TraitId,
308) -> (ExpressionStore, ExpressionStoreSourceMap, GenericParams) {
309 let mut expr_collector =
310 ExprCollector::new(db, module, trait_syntax.file_id, LoweringMode::Analysis);
311 let mut collector = generics::GenericParamsCollector::with_self_param(
312 &mut expr_collector,
313 trait_id.into(),
314 trait_syntax.value.type_bound_list(),
315 );
316 collector.lower(
317 &mut expr_collector,
318 trait_syntax.value.generic_param_list(),
319 trait_syntax.value.where_clause(),
320 );
321 let params = collector.finish();
322 let (store, source_map) = expr_collector.store.finish();
323 (store, source_map, params)
324}
325
326pub(crate) fn lower_type_alias(
327 db: &dyn SourceDatabase,
328 container: ItemContainerId,
329 alias: InFile<ast::TypeAlias>,
330 type_alias_id: TypeAliasId,
331) -> (ExpressionStore, ExpressionStoreSourceMap, GenericParams, Box<[TypeBound]>, Option<TypeRefId>)
332{
333 let mut expr_collector =
334 ExprCollector::new(db, container.module(db), alias.file_id, LoweringMode::Analysis);
335 let bounds = alias
336 .value
337 .type_bound_list()
338 .map(|bounds| {
339 bounds
340 .bounds()
341 .map(|bound| {
342 expr_collector.lower_type_bound(bound, &mut ExprCollector::impl_trait_allocator)
343 })
344 .collect()
345 })
346 .unwrap_or_default();
347 let mut collector = generics::GenericParamsCollector::new(type_alias_id.into());
348 collector.lower(
349 &mut expr_collector,
350 alias.value.generic_param_list(),
351 alias.value.where_clause(),
352 );
353 let params = collector.finish();
354 let type_ref = alias
355 .value
356 .ty()
357 .map(|ty| expr_collector.lower_type_ref(ty, &mut ExprCollector::impl_trait_allocator));
358 if alias.value.ty().is_none() {
359 let diagnostic_kind = match container {
360 ItemContainerId::ModuleId(_) => Some(MissingBodyItemKind::TypeAlias),
361 ItemContainerId::ImplId(_) => Some(MissingBodyItemKind::AssocType),
362 ItemContainerId::ExternBlockId(_) => None,
363 ItemContainerId::TraitId(_) => None,
364 };
365 if let Some(kind) = diagnostic_kind {
366 let node = InFile::new(alias.file_id, SyntaxNodePtr::new(alias.value.syntax()));
367 expr_collector
368 .store
369 .diagnostics
370 .push(ExpressionStoreDiagnostics::MissingBody { node, kind });
371 }
372 };
373 let (store, source_map) = expr_collector.store.finish();
374 (store, source_map, params, bounds, type_ref)
375}
376
377pub(crate) fn lower_function(
378 db: &dyn SourceDatabase,
379 module: ModuleId,
380 fn_: InFile<ast::Fn>,
381 function_id: FunctionId,
382) -> (
383 ExpressionStore,
384 ExpressionStoreSourceMap,
385 GenericParams,
386 Box<[TypeRefId]>,
387 Option<TypeRefId>,
388 bool,
389 bool,
390) {
391 let mut expr_collector = ExprCollector::new(db, module, fn_.file_id, LoweringMode::Analysis);
392 let mut collector = generics::GenericParamsCollector::new(function_id.into());
393 collector.lower(&mut expr_collector, fn_.value.generic_param_list(), fn_.value.where_clause());
394 let mut params = vec![];
395 let mut has_self_param = false;
396 let mut has_variadic = false;
397 collector.collect_impl_trait(&mut expr_collector, |collector, mut impl_trait_lower_fn| {
398 collector.with_lifetime_bound_scope(LifetimeBoundScope::Argument, |collector| {
399 if let Some(param_list) = fn_.value.param_list() {
400 if let Some(param) = param_list.self_param() {
401 let enabled = collector.check_cfg(¶m);
402 if enabled {
403 has_self_param = true;
404 params.push(match param.ty() {
405 Some(ty) => collector.lower_type_ref(ty, &mut impl_trait_lower_fn),
406 None => {
407 let self_type = collector.alloc_type_ref_desugared(TypeRef::Path(
408 Name::new_symbol_root(sym::Self_).into(),
409 ));
410 let lifetime = param
411 .lifetime()
412 .map(|lifetime| collector.lower_lifetime_ref(lifetime));
413 match param.kind() {
414 ast::SelfParamKind::Owned => self_type,
415 ast::SelfParamKind::Ref => collector.alloc_type_ref_desugared(
416 TypeRef::Reference(Box::new(RefType {
417 ty: self_type,
418 lifetime,
419 mutability: Mutability::Shared,
420 })),
421 ),
422 ast::SelfParamKind::MutRef => collector
423 .alloc_type_ref_desugared(TypeRef::Reference(Box::new(
424 RefType {
425 ty: self_type,
426 lifetime,
427 mutability: Mutability::Mut,
428 },
429 ))),
430 }
431 }
432 });
433 }
434 }
435 let p = param_list
436 .params()
437 .filter(|param| collector.check_cfg(param))
438 .filter(|param| {
439 let is_variadic = param.dotdotdot_token().is_some();
440 has_variadic |= is_variadic;
441 !is_variadic
442 })
443 .map(|param| param.ty())
444 .collect::<Vec<_>>();
446 for p in p {
447 params.push(collector.lower_type_ref_opt(p, &mut impl_trait_lower_fn));
448 }
449 }
450 })
451 });
452 let return_type = fn_.value.ret_type().map(|ret_type| {
453 expr_collector.with_lifetime_bound_scope(LifetimeBoundScope::Return, |this| {
454 this.lower_type_ref_opt(ret_type.ty(), &mut ExprCollector::impl_trait_allocator)
455 })
456 });
457 collector.update_to_late_bound_lifetimes(&expr_collector.named_lifetime_store);
458 let generics = collector.finish();
459
460 let return_type = if fn_.value.async_token().is_some() || fn_.value.gen_token().is_some() {
461 let (path, assoc_name) =
462 match (fn_.value.async_token().is_some(), fn_.value.gen_token().is_some()) {
463 (true, true) => {
464 (hir_expand::mod_path::path![core::async_iter::AsyncIterator], sym::Item)
465 }
466 (true, false) => (hir_expand::mod_path::path![core::future::Future], sym::Output),
467 (false, true) => (hir_expand::mod_path::path![core::iter::Iterator], sym::Item),
468 (false, false) => unreachable!(),
469 };
470 let mut generic_args: Vec<_> =
471 std::iter::repeat_n(None, path.segments().len() - 1).collect();
472 let binding = AssociatedTypeBinding {
473 name: Name::new_symbol_root(assoc_name),
474 args: None,
475 type_ref: Some(
476 return_type
477 .unwrap_or_else(|| expr_collector.alloc_type_ref_desugared(TypeRef::unit())),
478 ),
479 bounds: Box::default(),
480 };
481 generic_args
482 .push(Some(GenericArgs { bindings: Box::new([binding]), ..GenericArgs::empty() }));
483
484 let path = Path::from_known_path(path, generic_args);
485 let path = PathId::from_type_ref_unchecked(
486 expr_collector.alloc_type_ref_desugared(TypeRef::Path(path)),
487 );
488 let ty_bound = TypeBound::Path(path, TraitBoundModifier::None);
489 Some(
490 expr_collector
491 .alloc_type_ref_desugared(TypeRef::ImplTrait(ThinVec::from_iter([ty_bound]))),
492 )
493 } else {
494 return_type
495 };
496 let (store, source_map) = expr_collector.store.finish();
497 (
498 store,
499 source_map,
500 generics,
501 params.into_boxed_slice(),
502 return_type,
503 has_self_param,
504 has_variadic,
505 )
506}
507
508pub struct ExprCollector<'db> {
509 db: &'db dyn SourceDatabase,
510 cfg_options: &'db CfgOptions,
511 expander: Expander<'db>,
512 def_map: &'db DefMap,
513 local_def_map: &'db LocalDefMap,
514 module: ModuleId,
515 lowering_mode: LoweringMode,
516 lang_items: OnceCell<&'db LangItems>,
517 pub store: ExpressionStoreBuilder,
518 pub named_lifetime_store: NamedLifetimeStore,
519
520 outer_impl_trait: bool,
523
524 is_lowering_coroutine: bool,
525
526 for_type_binder: Option<ThinVec<Name>>,
527
528 current_block_legacy_macro_defs_count: FxHashMap<Name, usize>,
531
532 current_try_block: Option<TryBlock>,
533
534 label_ribs: Vec<LabelRib>,
535 unowned_bindings: Vec<BindingId>,
536
537 awaitable_context: Option<Awaitable>,
538 krate: base_db::Crate,
539
540 name_generator_index: usize,
541}
542
543#[derive(Clone, Debug)]
544struct LabelRib {
545 kind: RibKind,
546}
547
548impl LabelRib {
549 fn new(kind: RibKind) -> Self {
550 LabelRib { kind }
551 }
552}
553
554#[derive(Clone, Debug, PartialEq, Eq)]
555enum RibKind {
556 Normal(Name, LabelId, HygieneId),
557 Closure,
558 Constant,
559 MacroDef(Box<MacroDefId>),
560}
561
562impl RibKind {
563 fn is_label_barrier(&self) -> bool {
565 match self {
566 RibKind::Normal(..) | RibKind::MacroDef(_) => false,
567 RibKind::Closure | RibKind::Constant => true,
568 }
569 }
570}
571
572#[derive(PartialEq, Eq, Debug, Copy, Clone)]
573enum Awaitable {
574 Yes,
575 No(&'static str),
576}
577
578enum TryBlock {
579 Homogeneous { label: LabelId },
581 Heterogeneous { label: LabelId },
583}
584
585#[derive(Debug, Default)]
586struct BindingList {
587 map: FxHashMap<(Name, HygieneId), BindingId>,
588 is_used: FxHashMap<BindingId, bool>,
589 reject_new: bool,
590}
591
592impl BindingList {
593 fn find(
594 &mut self,
595 ec: &mut ExprCollector<'_>,
596 name: Name,
597 hygiene: HygieneId,
598 mode: BindingAnnotation,
599 ) -> BindingId {
600 let id = *self
601 .map
602 .entry((name, hygiene))
603 .or_insert_with_key(|(name, hygiene)| ec.alloc_binding(name.clone(), mode, *hygiene));
604 if ec.store.bindings[id].mode != mode {
605 ec.store.bindings[id].problems = Some(BindingProblems::BoundInconsistently);
606 }
607 self.check_is_used(ec, id);
608 id
609 }
610
611 fn check_is_used(&mut self, ec: &mut ExprCollector<'_>, id: BindingId) {
612 match self.is_used.get(&id) {
613 None => {
614 if self.reject_new {
615 ec.store.bindings[id].problems = Some(BindingProblems::NotBoundAcrossAll);
616 }
617 }
618 Some(true) => {
619 ec.store.bindings[id].problems = Some(BindingProblems::BoundMoreThanOnce);
620 }
621 Some(false) => {}
622 }
623 self.is_used.insert(id, true);
624 }
625}
626
627#[derive(Debug, Default)]
628pub struct NamedLifetimeStore {
629 lifetime_bound_scope: Option<LifetimeBoundScope>,
630 lifetimes_in_where_clause: FxIndexSet<Name>,
631 lifetimes_constrained_by_input: FxIndexSet<Name>,
632 lifetimes_in_output: FxIndexSet<Name>,
633}
634
635#[derive(Debug)]
636enum LifetimeBoundScope {
637 Argument,
638 Return,
639 WhereClause,
640 ImplTrait { is_argument_scope: bool },
641}
642
643impl NamedLifetimeStore {
644 pub(crate) fn push_named_lifetime(&mut self, lifetime: Name) {
647 match self.lifetime_bound_scope {
648 Some(LifetimeBoundScope::Argument) => {
649 self.lifetimes_constrained_by_input.insert(lifetime);
650 }
651 Some(LifetimeBoundScope::Return) => {
652 self.lifetimes_in_output.insert(lifetime);
653 }
654 Some(LifetimeBoundScope::WhereClause) => {
655 self.lifetimes_in_where_clause.insert(lifetime);
656 }
657 Some(LifetimeBoundScope::ImplTrait { is_argument_scope }) => {
658 if is_argument_scope {
659 self.lifetimes_in_where_clause.insert(lifetime);
660 } else {
661 self.lifetimes_in_output.insert(lifetime);
662 }
663 }
664 None => (),
665 };
666 }
667}
668
669impl<'db> ExprCollector<'db> {
670 pub fn new(
671 db: &dyn SourceDatabase,
672 module: ModuleId,
673 current_file_id: HirFileId,
674 lowering_mode: LoweringMode,
675 ) -> ExprCollector<'_> {
676 let (def_map, local_def_map) = module.local_def_map(db);
677 let expander = Expander::new(db, current_file_id, def_map);
678 let krate = module.krate(db);
679 let mut result = ExprCollector {
680 db,
681 cfg_options: krate.cfg_options(db),
682 module,
683 lowering_mode,
684 def_map,
685 local_def_map,
686 lang_items: OnceCell::new(),
687 store: ExpressionStoreBuilder::default(),
688 expander,
689 current_try_block: None,
690 is_lowering_coroutine: false,
691 label_ribs: Vec::new(),
692 unowned_bindings: Vec::new(),
693 awaitable_context: None,
694 current_block_legacy_macro_defs_count: FxHashMap::default(),
695 outer_impl_trait: false,
696 krate,
697 name_generator_index: 0,
698 named_lifetime_store: NamedLifetimeStore::default(),
699 for_type_binder: None,
700 };
701 result.store.inference_roots = Some(SmallVec::new());
702 result
703 }
704
705 fn generate_new_name(&mut self) -> Name {
706 let index = self.name_generator_index;
707 self.name_generator_index += 1;
708 Name::generate_new_name(index)
709 }
710
711 #[inline]
712 pub(crate) fn lang_items(&self) -> &'db LangItems {
713 self.lang_items.get_or_init(|| crate::lang_item::lang_items(self.db, self.def_map.krate()))
714 }
715
716 #[inline]
717 pub(crate) fn span_map(&self) -> SpanMap<'_> {
718 self.expander.span_map()
719 }
720
721 pub(in crate::expr_store) fn lower_lifetime_ref(
722 &mut self,
723 lifetime: ast::Lifetime,
724 ) -> LifetimeRefId {
725 let lifetime_ref = match lifetime.text() {
727 "" | "'" => LifetimeRef::Error,
728 "'static" => LifetimeRef::Static,
729 "'_" => LifetimeRef::Placeholder,
730 text => LifetimeRef::Named(Name::new_lifetime(text)),
731 };
732 self.alloc_lifetime_ref(lifetime_ref, AstPtr::new(&lifetime))
733 }
734
735 pub(in crate::expr_store) fn lower_lifetime_ref_opt(
736 &mut self,
737 lifetime: Option<ast::Lifetime>,
738 ) -> LifetimeRefId {
739 match lifetime {
740 Some(lifetime) => self.lower_lifetime_ref(lifetime),
741 None => self.alloc_lifetime_ref_desugared(LifetimeRef::Placeholder),
742 }
743 }
744
745 pub(in crate::expr_store) fn lower_type_ref(
747 &mut self,
748 node: ast::Type,
749 impl_trait_lower_fn: ImplTraitLowerFn<'_>,
750 ) -> TypeRefId {
751 let ty = match &node {
752 ast::Type::ParenType(inner) => {
753 return self.lower_type_ref_opt(inner.ty(), impl_trait_lower_fn);
754 }
755 ast::Type::TupleType(inner) => TypeRef::Tuple(ThinVec::from_iter(Vec::from_iter(
756 inner.fields().map(|it| self.lower_type_ref(it, impl_trait_lower_fn)),
757 ))),
758 ast::Type::NeverType(..) => TypeRef::Never,
759 ast::Type::PathType(inner) => inner
760 .path()
761 .and_then(|it| self.lower_path(it, impl_trait_lower_fn))
762 .map(TypeRef::Path)
763 .unwrap_or(TypeRef::Error),
764 ast::Type::PtrType(inner) => {
765 let inner_ty = self.lower_type_ref_opt(inner.ty(), impl_trait_lower_fn);
766 let mutability = Mutability::from_mutable(inner.mut_token().is_some());
767 TypeRef::RawPtr(inner_ty, mutability)
768 }
769 ast::Type::ArrayType(inner) => {
770 let len = self.lower_const_arg_opt(inner.const_arg());
771 TypeRef::Array(ArrayType {
772 ty: self.lower_type_ref_opt(inner.ty(), impl_trait_lower_fn),
773 len,
774 })
775 }
776 ast::Type::SliceType(inner) => {
777 TypeRef::Slice(self.lower_type_ref_opt(inner.ty(), impl_trait_lower_fn))
778 }
779 ast::Type::RefType(inner) => {
780 let inner_ty = self.lower_type_ref_opt(inner.ty(), impl_trait_lower_fn);
781 let lifetime = inner.lifetime().map(|lt| self.lower_lifetime_ref(lt));
782 let mutability = Mutability::from_mutable(inner.mut_token().is_some());
783 TypeRef::Reference(Box::new(RefType { ty: inner_ty, lifetime, mutability }))
784 }
785 ast::Type::InferType(_inner) => TypeRef::Placeholder,
786 ast::Type::FnPtrType(inner) => {
787 let ret_ty = inner
788 .ret_type()
789 .and_then(|rt| rt.ty())
790 .map(|it| self.lower_type_ref(it, impl_trait_lower_fn))
791 .unwrap_or_else(|| self.alloc_type_ref_desugared(TypeRef::unit()));
792 let mut is_varargs = false;
793 let mut params = if let Some(pl) = inner.param_list() {
794 if let Some(param) = pl.params().last() {
795 is_varargs = param.dotdotdot_token().is_some();
796 }
797
798 pl.params()
799 .filter(|it| it.dotdotdot_token().is_none())
800 .map(|it| {
801 let type_ref = self.lower_type_ref_opt(it.ty(), impl_trait_lower_fn);
802 let name = match it.pat() {
803 Some(ast::Pat::IdentPat(it)) => Some(
804 it.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing),
805 ),
806 _ => None,
807 };
808 (name, type_ref)
809 })
810 .collect()
811 } else {
812 Vec::with_capacity(1)
813 };
814 fn lower_abi(abi: ast::Abi) -> ExternAbi {
815 abi.abi_string()
816 .and_then(|abi| abi.text_without_quotes().parse().ok())
817 .unwrap_or(ExternAbi::FALLBACK)
818 }
819
820 let abi = inner.abi().map(lower_abi).unwrap_or(ExternAbi::Rust);
821 params.push((None, ret_ty));
822
823 let binder = self.for_type_binder.take().map(|b| b.into());
824 TypeRef::Fn(Box::new(FnType {
825 is_varargs,
826 is_unsafe: inner.unsafe_token().is_some(),
827 abi,
828 params: params.into_boxed_slice(),
829 binder,
830 }))
831 }
832 ast::Type::ForType(inner) => {
834 let binder = self.lower_for_binder_opt(inner.for_binder());
835 let old_for_binder = self.for_type_binder.replace(binder);
836 let ty = self.lower_type_ref_opt(inner.ty(), impl_trait_lower_fn);
837 self.for_type_binder = old_for_binder;
838 return ty;
839 }
840 ast::Type::ImplTraitType(inner) => {
841 if self.outer_impl_trait {
842 TypeRef::Error
844 } else {
845 return self.with_outer_impl_trait_scope(true, |this| {
846 let is_argument_scope = this.is_argument_lt_bound_scope();
847 let type_bounds = this.with_lifetime_bound_scope(
848 LifetimeBoundScope::ImplTrait { is_argument_scope },
849 |this| {
850 this.type_bounds_from_ast(
851 inner.type_bound_list(),
852 impl_trait_lower_fn,
853 )
854 },
855 );
856 impl_trait_lower_fn(this, AstPtr::new(&node), type_bounds)
857 });
858 }
859 }
860 ast::Type::DynTraitType(inner) => TypeRef::DynTrait(
861 self.type_bounds_from_ast(inner.type_bound_list(), impl_trait_lower_fn),
862 ),
863 ast::Type::PatternType(inner) => TypeRef::PatternType(
864 self.lower_type_ref_opt(inner.ty(), impl_trait_lower_fn),
865 self.collect_ty_pat_opt(inner.pat()),
866 ),
867 ast::Type::MacroType(mt) => match mt.macro_call() {
868 Some(mcall) => {
869 let macro_ptr = AstPtr::new(&mcall);
870 let src = self.expander.in_file(AstPtr::new(&node));
871 let id = self.collect_macro_call(mcall, macro_ptr, true, |this, expansion| {
872 this.lower_type_ref_opt(expansion, impl_trait_lower_fn)
873 });
874 self.store.types_map.insert(src, id);
875 return id;
876 }
877 None => TypeRef::Error,
878 },
879 };
880 self.alloc_type_ref(ty, AstPtr::new(&node))
881 }
882
883 pub(crate) fn lower_type_ref_disallow_impl_trait(&mut self, node: ast::Type) -> TypeRefId {
884 self.lower_type_ref(node, &mut Self::impl_trait_error_allocator)
885 }
886
887 pub(crate) fn lower_type_ref_opt(
888 &mut self,
889 node: Option<ast::Type>,
890 impl_trait_lower_fn: ImplTraitLowerFn<'_>,
891 ) -> TypeRefId {
892 match node {
893 Some(node) => self.lower_type_ref(node, impl_trait_lower_fn),
894 None => self.alloc_error_type(),
895 }
896 }
897
898 pub(crate) fn lower_type_ref_opt_disallow_impl_trait(
899 &mut self,
900 node: Option<ast::Type>,
901 ) -> TypeRefId {
902 self.lower_type_ref_opt(node, &mut Self::impl_trait_error_allocator)
903 }
904
905 fn alloc_type_ref(&mut self, type_ref: TypeRef, node: TypePtr) -> TypeRefId {
906 let id = self.store.types.alloc(type_ref);
907 let ptr = self.expander.in_file(node);
908 self.store.types_map_back.insert(id, ptr);
909 self.store.types_map.insert(ptr, id);
910 id
911 }
912
913 fn alloc_lifetime_ref(
914 &mut self,
915 lifetime_ref: LifetimeRef,
916 node: LifetimePtr,
917 ) -> LifetimeRefId {
918 if let LifetimeRef::Named(name) = &lifetime_ref {
919 self.named_lifetime_store.push_named_lifetime(name.clone());
920 }
921
922 let id = self.store.lifetimes.alloc(lifetime_ref);
923 let ptr = self.expander.in_file(node);
924 self.store.lifetime_map_back.insert(id, ptr);
925 self.store.lifetime_map.insert(ptr, id);
926 id
927 }
928
929 fn alloc_type_ref_desugared(&mut self, type_ref: TypeRef) -> TypeRefId {
930 self.store.types.alloc(type_ref)
931 }
932
933 fn alloc_lifetime_ref_desugared(&mut self, lifetime_ref: LifetimeRef) -> LifetimeRefId {
934 self.store.lifetimes.alloc(lifetime_ref)
935 }
936
937 fn alloc_error_type(&mut self) -> TypeRefId {
938 self.store.types.alloc(TypeRef::Error)
939 }
940
941 pub fn lower_path(
942 &mut self,
943 ast: ast::Path,
944 impl_trait_lower_fn: ImplTraitLowerFn<'_>,
945 ) -> Option<Path> {
946 super::lower::path::lower_path(self, ast, impl_trait_lower_fn)
947 }
948
949 fn with_outer_impl_trait_scope<R>(
950 &mut self,
951 impl_trait: bool,
952 f: impl FnOnce(&mut Self) -> R,
953 ) -> R {
954 let old = mem::replace(&mut self.outer_impl_trait, impl_trait);
955 let result = f(self);
956 self.outer_impl_trait = old;
957 result
958 }
959
960 pub fn impl_trait_error_allocator(
961 ec: &mut ExprCollector<'_>,
962 ptr: TypePtr,
963 _: ThinVec<TypeBound>,
964 ) -> TypeRefId {
965 ec.alloc_type_ref(TypeRef::Error, ptr)
966 }
967
968 fn impl_trait_allocator(
969 ec: &mut ExprCollector<'_>,
970 ptr: TypePtr,
971 bounds: ThinVec<TypeBound>,
972 ) -> TypeRefId {
973 ec.alloc_type_ref(TypeRef::ImplTrait(bounds), ptr)
974 }
975
976 fn alloc_path(&mut self, path: Path, node: TypePtr) -> PathId {
977 PathId::from_type_ref_unchecked(self.alloc_type_ref(TypeRef::Path(path), node))
978 }
979
980 pub(in crate::expr_store) fn lower_generic_args_from_fn_path(
983 &mut self,
984 args: Option<ast::ParenthesizedArgList>,
985 ret_type: Option<ast::RetType>,
986 impl_trait_lower_fn: ImplTraitLowerFn<'_>,
987 ) -> Option<GenericArgs> {
988 let params = args?;
989 let mut param_types = Vec::new();
990 for param in params.type_args() {
991 let type_ref = self.lower_type_ref_opt(param.ty(), impl_trait_lower_fn);
992 param_types.push(type_ref);
993 }
994 let args = Box::new([GenericArg::Type(
995 self.alloc_type_ref_desugared(TypeRef::Tuple(ThinVec::from_iter(param_types))),
996 )]);
997 let bindings = if let Some(ret_type) = ret_type {
998 let type_ref = self.lower_type_ref_opt(ret_type.ty(), impl_trait_lower_fn);
999 Box::new([AssociatedTypeBinding {
1000 name: Name::new_symbol_root(sym::Output),
1001 args: None,
1002 type_ref: Some(type_ref),
1003 bounds: Box::default(),
1004 }])
1005 } else {
1006 let type_ref = self.alloc_type_ref_desugared(TypeRef::unit());
1008 Box::new([AssociatedTypeBinding {
1009 name: Name::new_symbol_root(sym::Output),
1010 args: None,
1011 type_ref: Some(type_ref),
1012 bounds: Box::default(),
1013 }])
1014 };
1015 Some(GenericArgs {
1016 args,
1017 has_self_type: false,
1018 bindings,
1019 parenthesized: GenericArgsParentheses::ParenSugar,
1020 })
1021 }
1022
1023 pub(super) fn lower_generic_args(
1024 &mut self,
1025 node: ast::GenericArgList,
1026 impl_trait_lower_fn: ImplTraitLowerFn<'_>,
1027 ) -> Option<GenericArgs> {
1028 let mut args = Vec::new();
1030 let mut bindings = Vec::new();
1031 for generic_arg in node.generic_args() {
1032 match generic_arg {
1033 ast::GenericArg::TypeArg(type_arg) => {
1034 let type_ref = self.lower_type_ref_opt(type_arg.ty(), impl_trait_lower_fn);
1035 args.push(GenericArg::Type(type_ref));
1036 }
1037 ast::GenericArg::AssocTypeArg(assoc_type_arg) => {
1038 if assoc_type_arg.param_list().is_some() {
1040 continue;
1042 }
1043 if let Some(name_ref) = assoc_type_arg.name_ref() {
1044 self.with_outer_impl_trait_scope(false, |this| {
1046 let name = name_ref.as_name();
1047 let args = assoc_type_arg
1048 .generic_arg_list()
1049 .and_then(|args| this.lower_generic_args(args, impl_trait_lower_fn))
1050 .or_else(|| {
1051 assoc_type_arg
1052 .return_type_syntax()
1053 .map(|_| GenericArgs::return_type_notation())
1054 });
1055 let type_ref = assoc_type_arg
1056 .ty()
1057 .map(|it| this.lower_type_ref(it, impl_trait_lower_fn));
1058 let bounds = if let Some(l) = assoc_type_arg.type_bound_list() {
1059 l.bounds()
1060 .map(|it| this.lower_type_bound(it, impl_trait_lower_fn))
1061 .collect()
1062 } else {
1063 Box::default()
1064 };
1065 bindings.push(AssociatedTypeBinding { name, args, type_ref, bounds });
1066 });
1067 }
1068 }
1069 ast::GenericArg::LifetimeArg(lifetime_arg) => {
1070 if let Some(lifetime) = lifetime_arg.lifetime() {
1071 let lifetime_ref = self.lower_lifetime_ref(lifetime);
1072 args.push(GenericArg::Lifetime(lifetime_ref))
1073 }
1074 }
1075 ast::GenericArg::ConstArg(arg) => {
1076 let arg = self.lower_const_arg(arg);
1077 args.push(GenericArg::Const(arg))
1078 }
1079 }
1080 }
1081
1082 if args.is_empty() && bindings.is_empty() {
1083 return None;
1084 }
1085 Some(GenericArgs {
1086 args: args.into_boxed_slice(),
1087 has_self_type: false,
1088 bindings: bindings.into_boxed_slice(),
1089 parenthesized: GenericArgsParentheses::No,
1090 })
1091 }
1092
1093 fn lower_coroutine_body_with_moved_arguments(
1098 &mut self,
1099 self_param: &mut Option<Param<BindingId>>,
1100 params: &mut [Param<PatId>],
1101 body: ExprId,
1102 kind: CoroutineKind,
1103 coroutine_source: CoroutineSource,
1104 ) -> ExprId {
1105 let mut statements =
1132 Vec::with_capacity(usize::from(self_param.is_some()) + (params.len() * 2));
1133
1134 if let Some(self_param) = self_param {
1135 let Binding { ref name, mode, hygiene, .. } = self.store.bindings[self_param.formal];
1136 let name = name.clone();
1137 let child_binding_id = self.alloc_binding(name.clone(), mode, hygiene);
1138 let child_pat_id =
1139 self.alloc_pat_desugared(Pat::Bind { id: child_binding_id, subpat: None });
1140 self.add_definition_to_binding(child_binding_id, child_pat_id);
1141 let expr = self.alloc_expr_desugared(Expr::Path(name.into()));
1142 if !hygiene.is_root() {
1143 self.store.ident_hygiene.insert(expr.into(), hygiene);
1144 }
1145 statements.push(Statement::Let {
1146 pat: child_pat_id,
1147 type_ref: None,
1148 initializer: Some(expr),
1149 else_branch: None,
1150 });
1151 self_param.user_written = child_binding_id;
1152 }
1153
1154 for param in params {
1155 let (name, hygiene, is_simple_parameter) = match self.store.pats[param.formal] {
1156 Pat::Bind { id, subpat: None, .. }
1159 if matches!(
1160 self.store.bindings[id].mode,
1161 BindingAnnotation::Unannotated | BindingAnnotation::Mutable
1162 ) =>
1163 {
1164 let binding = &self.store.bindings[id];
1165 (binding.name.clone(), binding.hygiene, true)
1166 }
1167 Pat::Bind { id, .. } => {
1168 let binding = &self.store.bindings[id];
1170 (binding.name.clone(), binding.hygiene, false)
1171 }
1172 _ => (self.generate_new_name(), HygieneId::ROOT, false),
1173 };
1174 let pat_syntax = self.store.pat_map_back.get(param.formal).copied();
1175 if !is_simple_parameter {
1176 let child_binding_id =
1178 self.alloc_binding(name.clone(), BindingAnnotation::Mutable, hygiene);
1179 let child_pat_id =
1180 self.alloc_pat_desugared(Pat::Bind { id: child_binding_id, subpat: None });
1181 self.add_definition_to_binding(child_binding_id, child_pat_id);
1182 if let Some(pat_syntax) = pat_syntax {
1183 self.store.pat_map_back.insert(child_pat_id, pat_syntax);
1184 }
1185 let expr = self.alloc_expr_desugared(Expr::Path(name.clone().into()));
1186 if !hygiene.is_root() {
1187 self.store.ident_hygiene.insert(expr.into(), hygiene);
1188 }
1189 statements.push(Statement::Let {
1190 pat: child_pat_id,
1191 type_ref: None,
1192 initializer: Some(expr),
1193 else_branch: None,
1194 });
1195 }
1196 let expr = self.alloc_expr_desugared(Expr::Path(name.clone().into()));
1197 if !hygiene.is_root() {
1198 self.store.ident_hygiene.insert(expr.into(), hygiene);
1199 }
1200 statements.push(Statement::Let {
1201 pat: param.formal,
1202 type_ref: None,
1203 initializer: Some(expr),
1204 else_branch: None,
1205 });
1206
1207 let parent_binding_id = self.alloc_binding(name, BindingAnnotation::Mutable, hygiene);
1208 let parent_pat_id =
1209 self.alloc_pat_desugared(Pat::Bind { id: parent_binding_id, subpat: None });
1210 self.add_definition_to_binding(parent_binding_id, parent_pat_id);
1211 if let Some(pat_syntax) = pat_syntax {
1212 self.store.pat_map_back.insert(parent_pat_id, pat_syntax);
1213 }
1214 *param = Param { formal: parent_pat_id, user_written: param.formal };
1215 }
1216
1217 let coroutine = self.desugared_coroutine_expr(
1218 kind,
1219 coroutine_source,
1220 CaptureBy::Ref,
1225 None,
1226 statements.into_boxed_slice(),
1227 Some(body),
1228 );
1229 self.alloc_expr_desugared(coroutine)
1231 }
1232
1233 fn desugared_coroutine_expr(
1234 &mut self,
1235 kind: CoroutineKind,
1236 source: CoroutineSource,
1237 capture_by: CaptureBy,
1238 id: Option<BlockId>,
1239 statements: Box<[Statement]>,
1240 tail: Option<ExprId>,
1241 ) -> Expr {
1242 let block = self.alloc_expr_desugared(Expr::Block {
1243 label: None,
1244 id,
1245 statements,
1246 tail,
1247 unsafe_: Unsafe::No,
1248 });
1249 Expr::Closure {
1250 args: Box::default(),
1251 arg_types: Box::default(),
1252 ret_type: None,
1253 body: block,
1254 closure_kind: ClosureKind::Coroutine { kind, source },
1255 capture_by,
1256 }
1257 }
1258
1259 fn collect(
1260 &mut self,
1261 self_param: &mut Option<Param<BindingId>>,
1262 params: &mut [Param<PatId>],
1263 expr: Option<ast::Expr>,
1264 awaitable: Awaitable,
1265 is_async_fn: bool,
1266 is_gen_fn: bool,
1267 ) -> ExprId {
1268 self.awaitable_context.replace(awaitable);
1269 self.with_label_rib(RibKind::Closure, |this| {
1270 let body = this.collect_expr_opt(expr);
1271 if is_async_fn || is_gen_fn {
1272 let kind = match (is_async_fn, is_gen_fn) {
1273 (true, true) => CoroutineKind::AsyncGen,
1274 (true, false) => CoroutineKind::Async,
1275 (false, true) => CoroutineKind::Gen,
1276 (false, false) => unreachable!(),
1277 };
1278 let coroutine = this.lower_coroutine_body_with_moved_arguments(
1279 self_param,
1280 params,
1281 body,
1282 kind,
1283 CoroutineSource::Fn,
1284 );
1285 this.associate_unowned_bindings_with(0, coroutine);
1287 params
1290 .iter()
1291 .filter_map(|param| {
1292 if let Pat::Bind { id, .. } = this.store.pats[param.formal] {
1293 Some(id)
1294 } else {
1295 never!(
1296 "`lower_coroutine_body_with_moved_arguments()` should make sure \
1297 the coroutine closure only have simple bind args"
1298 );
1299 None
1300 }
1301 })
1302 .chain(self_param.map(|param| param.formal))
1303 .for_each(|param| {
1304 this.store.binding_owners.remove(¶m);
1306 });
1307 coroutine
1308 } else {
1309 body
1310 }
1311 })
1312 }
1313
1314 fn type_bounds_from_ast(
1315 &mut self,
1316 type_bounds_opt: Option<ast::TypeBoundList>,
1317 impl_trait_lower_fn: ImplTraitLowerFn<'_>,
1318 ) -> ThinVec<TypeBound> {
1319 if let Some(type_bounds) = type_bounds_opt {
1320 ThinVec::from_iter(Vec::from_iter(
1321 type_bounds.bounds().map(|it| self.lower_type_bound(it, impl_trait_lower_fn)),
1322 ))
1323 } else {
1324 ThinVec::from_iter([])
1325 }
1326 }
1327
1328 fn lower_path_type(
1329 &mut self,
1330 path_type: &ast::PathType,
1331 impl_trait_lower_fn: ImplTraitLowerFn<'_>,
1332 ) -> Option<Path> {
1333 let path = self.lower_path(path_type.path()?, impl_trait_lower_fn)?;
1334 Some(path)
1335 }
1336
1337 fn lower_type_bound(
1338 &mut self,
1339 node: ast::TypeBound,
1340 impl_trait_lower_fn: ImplTraitLowerFn<'_>,
1341 ) -> TypeBound {
1342 let Some(kind) = node.kind() else { return TypeBound::Error };
1343 match kind {
1344 ast::TypeBoundKind::PathType(binder, path_type) => {
1345 let binder = self.lower_for_binder_opt(binder);
1346 let m = match node.question_mark_token() {
1347 Some(_) => TraitBoundModifier::Maybe,
1348 None => TraitBoundModifier::None,
1349 };
1350 self.lower_path_type(&path_type, impl_trait_lower_fn)
1351 .map(|p| {
1352 let path = self.alloc_path(p, AstPtr::new(&path_type).upcast());
1353 if binder.is_empty() {
1354 TypeBound::Path(path, m)
1355 } else {
1356 TypeBound::ForLifetime(binder, path)
1357 }
1358 })
1359 .unwrap_or(TypeBound::Error)
1360 }
1361 ast::TypeBoundKind::Use(gal) => TypeBound::Use(
1362 gal.use_bound_generic_args()
1363 .map(|p| match p {
1364 ast::UseBoundGenericArg::Lifetime(l) => {
1365 UseArgRef::Lifetime(self.lower_lifetime_ref(l))
1366 }
1367 ast::UseBoundGenericArg::NameRef(n) => UseArgRef::Name(n.as_name()),
1368 })
1369 .collect(),
1370 ),
1371 ast::TypeBoundKind::Lifetime(lifetime) => {
1372 TypeBound::Lifetime(self.lower_lifetime_ref(lifetime))
1373 }
1374 }
1375 }
1376
1377 fn lower_for_binder_opt(&mut self, binder: Option<ForBinder>) -> ThinVec<Name> {
1378 binder.map(|b| self.lower_for_binder(b)).unwrap_or_default()
1379 }
1380
1381 fn lower_for_binder(&mut self, binder: ForBinder) -> ThinVec<Name> {
1382 match binder.generic_param_list() {
1383 Some(gpl) => gpl
1384 .lifetime_params()
1385 .flat_map(|lp| lp.lifetime().map(|lt| Name::new_lifetime(lt.text())))
1386 .collect(),
1387 None => ThinVec::default(),
1388 }
1389 }
1390
1391 fn lower_const_arg_opt(&mut self, arg: Option<ast::ConstArg>) -> ConstRef {
1392 ConstRef {
1393 expr: self.with_fresh_binding_expr_root(|this| {
1394 this.collect_expr_opt(arg.and_then(|arg| arg.expr()))
1395 }),
1396 }
1397 }
1398
1399 pub fn lower_const_arg(&mut self, arg: ast::ConstArg) -> ConstRef {
1400 ConstRef {
1401 expr: self.with_fresh_binding_expr_root(|this| this.collect_expr_opt(arg.expr())),
1402 }
1403 }
1404
1405 fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
1406 self.maybe_collect_expr(expr).unwrap_or_else(|| self.missing_expr())
1407 }
1408
1409 pub(in crate::expr_store) fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
1410 match expr {
1411 Some(expr) => self.collect_expr(expr),
1412 None => self.missing_expr(),
1413 }
1414 }
1415
1416 fn maybe_collect_expr(&mut self, expr: ast::Expr) -> Option<ExprId> {
1418 if !self.check_cfg(&expr) {
1419 return None;
1420 }
1421 let syntax_ptr = AstPtr::new(&expr);
1422
1423 Some(match expr {
1425 ast::Expr::IfExpr(e) => {
1426 let then_branch = self.collect_block_opt(e.then_branch());
1427
1428 let else_branch = e.else_branch().map(|b| match b {
1429 ast::ElseBranch::Block(it) => self.collect_block(it),
1430 ast::ElseBranch::IfExpr(elif) => {
1431 let expr: ast::Expr = ast::Expr::cast(elif.syntax().clone()).unwrap();
1432 self.collect_expr(expr)
1433 }
1434 });
1435
1436 let condition = self.collect_expr_opt(e.condition());
1437
1438 self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
1439 }
1440 ast::Expr::LetExpr(e) => {
1441 let pat = self.collect_pat_top(e.pat());
1442 let expr = self.collect_expr_opt(e.expr());
1443 self.alloc_expr(Expr::Let { pat, expr }, syntax_ptr)
1444 }
1445 ast::Expr::BlockExpr(e) => match e.modifier() {
1446 Some(ast::BlockModifier::Try { try_token: _, bikeshed_token: _, result_type }) => {
1447 self.desugar_try_block(e, result_type)
1448 }
1449 Some(ast::BlockModifier::Unsafe(_)) => {
1450 self.collect_block_(e, |_, id, statements, tail| Expr::Block {
1451 id,
1452 statements,
1453 tail,
1454 label: None,
1455 unsafe_: Unsafe::Yes,
1456 })
1457 }
1458 Some(ast::BlockModifier::Label(label)) => {
1459 let label_hygiene = self.hygiene_id_for(label.syntax().text_range());
1460 let label_id = self.collect_label(label);
1461 self.with_labeled_rib(label_id, label_hygiene, |this| {
1462 this.collect_block_(e, |_, id, statements, tail| Expr::Block {
1463 id,
1464 statements,
1465 tail,
1466 label: Some(label_id),
1467 unsafe_: Unsafe::No,
1468 })
1469 })
1470 }
1471 Some(ast::BlockModifier::Async(_)) => {
1472 let capture_by =
1473 if e.move_token().is_some() { CaptureBy::Value } else { CaptureBy::Ref };
1474 self.with_label_rib(RibKind::Closure, |this| {
1475 this.with_binding_owner(|this| {
1476 this.with_awaitable_block(Awaitable::Yes, |this| {
1477 this.collect_block_(e, |this, id, statements, tail| {
1478 this.desugared_coroutine_expr(
1479 CoroutineKind::Async,
1480 CoroutineSource::Block,
1481 capture_by,
1482 id,
1483 statements,
1484 tail,
1485 )
1486 })
1487 })
1488 })
1489 })
1490 }
1491 Some(ast::BlockModifier::Gen(_)) => {
1492 let capture_by =
1493 if e.move_token().is_some() { CaptureBy::Value } else { CaptureBy::Ref };
1494 self.with_label_rib(RibKind::Closure, |this| {
1495 this.with_binding_owner(|this| {
1496 this.with_awaitable_block(Awaitable::No("non-async gen block"), |this| {
1497 this.collect_block_(e, |this, id, statements, tail| {
1498 this.desugared_coroutine_expr(
1499 CoroutineKind::Gen,
1500 CoroutineSource::Block,
1501 capture_by,
1502 id,
1503 statements,
1504 tail,
1505 )
1506 })
1507 })
1508 })
1509 })
1510 }
1511 Some(ast::BlockModifier::AsyncGen(_)) => {
1512 let capture_by =
1513 if e.move_token().is_some() { CaptureBy::Value } else { CaptureBy::Ref };
1514 self.with_label_rib(RibKind::Closure, |this| {
1515 this.with_binding_owner(|this| {
1516 this.with_awaitable_block(Awaitable::Yes, |this| {
1517 this.collect_block_(e, |this, id, statements, tail| {
1518 this.desugared_coroutine_expr(
1519 CoroutineKind::AsyncGen,
1520 CoroutineSource::Block,
1521 capture_by,
1522 id,
1523 statements,
1524 tail,
1525 )
1526 })
1527 })
1528 })
1529 })
1530 }
1531 Some(ast::BlockModifier::Const(_)) => {
1532 self.with_label_rib(RibKind::Constant, |this| {
1533 this.with_awaitable_block(Awaitable::No("constant block"), |this| {
1534 this.with_binding_owner(|this| {
1535 let inner_expr = this.collect_block(e);
1536 this.alloc_expr(Expr::Const(inner_expr), syntax_ptr)
1537 })
1538 })
1539 })
1540 }
1541 None => self.collect_block(e),
1542 },
1543 ast::Expr::LoopExpr(e) => {
1544 let label = e.label().map(|label| {
1545 (self.hygiene_id_for(label.syntax().text_range()), self.collect_label(label))
1546 });
1547 let body = self.collect_labelled_block_opt(label, e.loop_body());
1548 self.alloc_expr(Expr::Loop { body, label: label.map(|it| it.1), source: LoopSource::Loop }, syntax_ptr)
1549 }
1550 ast::Expr::WhileExpr(e) => self.collect_while_loop(syntax_ptr, e),
1551 ast::Expr::ForExpr(e) => self.collect_for_loop(syntax_ptr, e),
1552 ast::Expr::CallExpr(e) => {
1553 let callee = self.collect_expr_opt(e.expr());
1554 let args = if let Some(arg_list) = e.arg_list() {
1555 arg_list.args().filter_map(|e| self.maybe_collect_expr(e)).collect()
1556 } else {
1557 Box::default()
1558 };
1559 self.alloc_expr(Expr::Call { callee, args }, syntax_ptr)
1560 }
1561 ast::Expr::MethodCallExpr(e) => {
1562 let receiver = self.collect_expr_opt(e.receiver());
1563 let args = if let Some(arg_list) = e.arg_list() {
1564 arg_list.args().filter_map(|e| self.maybe_collect_expr(e)).collect()
1565 } else {
1566 Box::default()
1567 };
1568 let method_name = e.name_ref().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
1569 let generic_args = e
1570 .generic_arg_list()
1571 .and_then(|it| {
1572 self.lower_generic_args(it, &mut Self::impl_trait_error_allocator)
1573 })
1574 .map(Box::new);
1575 self.alloc_expr(
1576 Expr::MethodCall { receiver, method_name, args, generic_args },
1577 syntax_ptr,
1578 )
1579 }
1580 ast::Expr::MatchExpr(e) => {
1581 let expr = self.collect_expr_opt(e.expr());
1582 let arms = if let Some(match_arm_list) = e.match_arm_list() {
1583 match_arm_list
1584 .arms()
1585 .filter_map(|arm| {
1586 if self.check_cfg(&arm) {
1587 Some(MatchArm {
1588 pat: self.collect_pat_top(arm.pat()),
1589 expr: self.collect_expr_opt(arm.expr()),
1590 guard: arm
1591 .guard()
1592 .map(|guard| self.collect_expr_opt(guard.condition())),
1593 })
1594 } else {
1595 None
1596 }
1597 })
1598 .collect()
1599 } else {
1600 Box::default()
1601 };
1602 self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
1603 }
1604 ast::Expr::PathExpr(e) => {
1605 let (path, hygiene) = self
1606 .collect_expr_path(e)
1607 .map(|(path, hygiene)| (Expr::Path(path), hygiene))
1608 .unwrap_or((Expr::Missing, HygieneId::ROOT));
1609 let expr_id = self.alloc_expr(path, syntax_ptr);
1610 if !hygiene.is_root() {
1611 self.store.ident_hygiene.insert(expr_id.into(), hygiene);
1612 }
1613 expr_id
1614 }
1615 ast::Expr::ContinueExpr(e) => {
1616 let label = self.resolve_label(e.lifetime()).unwrap_or_else(|e| {
1617 self.store.diagnostics.push(e);
1618 None
1619 });
1620 self.alloc_expr(Expr::Continue { label }, syntax_ptr)
1621 }
1622 ast::Expr::BreakExpr(e) => {
1623 let label = self.resolve_label(e.lifetime()).unwrap_or_else(|e| {
1624 self.store.diagnostics.push(e);
1625 None
1626 });
1627 let expr = e.expr().map(|e| self.collect_expr(e));
1628 self.alloc_expr(Expr::Break { expr, label }, syntax_ptr)
1629 }
1630 ast::Expr::ParenExpr(e) => {
1631 let inner = self.collect_expr_opt(e.expr());
1632 let src = self.expander.in_file(syntax_ptr);
1634 self.store.expr_map.insert(src, inner.into());
1635 inner
1636 }
1637 ast::Expr::ReturnExpr(e) => {
1638 let expr = e.expr().map(|e| self.collect_expr(e));
1639 self.alloc_expr(Expr::Return { expr }, syntax_ptr)
1640 }
1641 ast::Expr::BecomeExpr(e) => {
1642 let expr =
1643 e.expr().map(|e| self.collect_expr(e)).unwrap_or_else(|| self.missing_expr());
1644 self.alloc_expr(Expr::Become { expr }, syntax_ptr)
1645 }
1646 ast::Expr::YieldExpr(e) => {
1647 self.is_lowering_coroutine = true;
1648 let mut expr = e.expr().map(|e| self.collect_expr(e));
1649 if matches!(self.awaitable_context, Some(Awaitable::Yes)) {
1650 let yielded = expr.unwrap_or_else(|| self.alloc_expr_desugared_with_ptr(Expr::Tuple { exprs: Box::new([]) }, syntax_ptr));
1652 let async_gen_ready = self.alloc_expr_desugared(self.lang_path_expr(self.lang_items().AsyncGenReady));
1653 expr = Some(self.alloc_expr_desugared_with_ptr(Expr::Call { callee: async_gen_ready, args: Box::new([yielded]) }, syntax_ptr))
1654 }
1655 self.alloc_expr(Expr::Yield { expr }, syntax_ptr)
1656 }
1657 ast::Expr::YeetExpr(e) => {
1658 let expr = e.expr().map(|e| self.collect_expr(e));
1659 self.alloc_expr(Expr::Yeet { expr }, syntax_ptr)
1660 }
1661 ast::Expr::RecordExpr(e) => {
1662 let path = e
1663 .path()
1664 .and_then(|path| self.lower_path(path, &mut Self::impl_trait_error_allocator));
1665 let Some(path) = path else {
1666 return Some(self.missing_expr());
1667 };
1668 let record_lit = if let Some(nfl) = e.record_expr_field_list() {
1669 let fields = nfl
1670 .fields()
1671 .filter_map(|field| {
1672 if !self.check_cfg(&field) {
1673 return None;
1674 }
1675
1676 let name = field.field_name()?.as_name();
1677
1678 let expr = match field.expr() {
1679 Some(e) => self.collect_expr(e),
1680 None => self.missing_expr(),
1681 };
1682 let src = self.expander.in_file(AstPtr::new(&field));
1683 self.store.field_map_back.insert(expr, src);
1684 Some(RecordLitField { name, expr })
1685 })
1686 .collect();
1687 let spread_expr = nfl.spread().map(|s| self.collect_expr(s));
1688 let has_spread_syntax = nfl.dotdot_token().is_some();
1689 let spread = match (spread_expr, has_spread_syntax) {
1690 (None, false) => RecordSpread::None,
1691 (None, true) => RecordSpread::FieldDefaults,
1692 (Some(expr), _) => RecordSpread::Expr(expr),
1693 };
1694 Expr::RecordLit { path, fields, spread }
1695 } else {
1696 Expr::RecordLit { path, fields: ThinVec::default(), spread: RecordSpread::None }
1697 };
1698
1699 self.alloc_expr(record_lit, syntax_ptr)
1700 }
1701 ast::Expr::FieldExpr(e) => {
1702 let expr = self.collect_expr_opt(e.expr());
1703 let name = match e.field_access() {
1704 Some(kind) => kind.as_name(),
1705 _ => Name::missing(),
1706 };
1707 self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
1708 }
1709 ast::Expr::AwaitExpr(e) => {
1710 let expr = self.collect_expr_opt(e.expr());
1711 if let Awaitable::No(location) = self.is_lowering_awaitable_block() {
1712 self.store.diagnostics.push(ExpressionStoreDiagnostics::AwaitOutsideOfAsync {
1713 node: self.expander.in_file(AstPtr::new(&e)),
1714 location: location.to_string(),
1715 });
1716 }
1717 self.alloc_expr(Expr::Await { expr }, syntax_ptr)
1718 }
1719 ast::Expr::TryExpr(e) => self.collect_try_operator(syntax_ptr, e),
1720 ast::Expr::CastExpr(e) => {
1721 let expr = self.collect_expr_opt(e.expr());
1722 let type_ref = self.lower_type_ref_opt_disallow_impl_trait(e.ty());
1723 self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
1724 }
1725 ast::Expr::RefExpr(e) => {
1726 let expr = self.collect_expr_opt(e.expr());
1727 let raw_tok = e.raw_token().is_some();
1728 let mutability = if raw_tok {
1729 if e.mut_token().is_some() { Mutability::Mut } else { Mutability::Shared }
1730 } else {
1731 Mutability::from_mutable(e.mut_token().is_some())
1732 };
1733 let rawness = Rawness::from_raw(raw_tok);
1734 self.alloc_expr(Expr::Ref { expr, rawness, mutability }, syntax_ptr)
1735 }
1736 ast::Expr::PrefixExpr(e) => {
1737 let expr = self.collect_expr_opt(e.expr());
1738 match e.op_kind() {
1739 Some(op) => self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr),
1740 None => self.alloc_expr(Expr::Missing, syntax_ptr),
1741 }
1742 }
1743 ast::Expr::ClosureExpr(e) => self.with_label_rib(RibKind::Closure, |this| {
1744 let mut is_coroutine_closure = false;
1745 let closure = this.with_binding_owner_and_return(|this| {
1746 let mut args = Vec::new();
1747 let mut arg_types = Vec::new();
1748 if let Some(pl) = e.param_list() {
1750 let num_params = pl.params().count();
1751 args.reserve_exact(num_params);
1752 arg_types.reserve_exact(num_params);
1753 for param in pl.params() {
1754 if !this.check_cfg(¶m) {
1755 continue;
1756 }
1757
1758 let pat = this.collect_pat_top(param.pat());
1759 let type_ref =
1760 param.ty().map(|it| this.lower_type_ref_disallow_impl_trait(it));
1761 args.push(pat);
1762 arg_types.push(type_ref);
1763 }
1764 }
1765 let ret_type = e
1766 .ret_type()
1767 .and_then(|r| r.ty())
1768 .map(|it| this.lower_type_ref_disallow_impl_trait(it));
1769
1770 let prev_is_lowering_coroutine = mem::take(&mut this.is_lowering_coroutine);
1771 let prev_try_block = this.current_try_block.take();
1772
1773 let awaitable = if e.async_token().is_some() {
1774 Awaitable::Yes
1775 } else {
1776 Awaitable::No("non-async closure")
1777 };
1778 let mut body = this
1779 .with_awaitable_block(awaitable, |this| this.collect_expr_opt(e.body()));
1780 let kind = {
1781 if e.async_token().is_some() && e.gen_token().is_some() {
1782 Some(CoroutineKind::AsyncGen)
1783 } else if e.async_token().is_some() {
1784 Some(CoroutineKind::Async)
1785 } else if e.gen_token().is_some() {
1786 Some(CoroutineKind::Gen)
1787 } else {
1788 None
1789 }
1790 };
1791
1792 let closure_kind = if let Some(kind) = kind {
1793 let mut args_with_user_written = args.iter().copied().map(Param::new).collect::<Vec<_>>();
1796 body = this.lower_coroutine_body_with_moved_arguments(
1797 &mut None,
1798 &mut args_with_user_written,
1799 body,
1800 kind,
1801 CoroutineSource::Closure,
1802 );
1803 args.iter_mut().set_from(args_with_user_written.iter().map(|arg| arg.formal));
1804 is_coroutine_closure = true;
1805
1806 ClosureKind::CoroutineClosure(kind)
1807 } else if this.is_lowering_coroutine {
1808 let movability = if e.static_token().is_some() {
1809 Movability::Static
1810 } else {
1811 Movability::Movable
1812 };
1813 ClosureKind::OldCoroutine(movability)
1814 } else {
1815 ClosureKind::Closure
1816 };
1817 let capture_by =
1818 if e.move_token().is_some() { CaptureBy::Value } else { CaptureBy::Ref };
1819 this.is_lowering_coroutine = prev_is_lowering_coroutine;
1820 this.current_try_block = prev_try_block;
1821 let closure = this.alloc_expr(
1822 Expr::Closure {
1823 args: args.into(),
1824 arg_types: arg_types.into(),
1825 ret_type,
1826 body,
1827 closure_kind,
1828 capture_by,
1829 },
1830 syntax_ptr,
1831 );
1832
1833 (if is_coroutine_closure { body } else { closure }, closure)
1834 });
1835
1836 if is_coroutine_closure {
1837 let Expr::Closure { args, .. } = &this.store.exprs[closure] else {
1838 unreachable!()
1839 };
1840 for &arg in args {
1841 let Pat::Bind { id, .. } = this.store.pats[arg] else {
1842 never!("`lower_coroutine_body_with_moved_arguments()` should make sure the coroutine closure only have simple bind args");
1843 continue;
1844 };
1845 this.store.binding_owners.insert(id, closure);
1846 }
1847 }
1848
1849 closure
1850 }),
1851 ast::Expr::BinExpr(e) => {
1852 let op = e.op_kind();
1853 if let Some(ast::BinaryOp::Assignment { op: None }) = op {
1854 let target = self.collect_expr_as_pat_opt(e.lhs());
1855 let value = self.collect_expr_opt(e.rhs());
1856 self.alloc_expr(Expr::Assignment { target, value }, syntax_ptr)
1857 } else {
1858 let lhs = self.collect_expr_opt(e.lhs());
1859 let rhs = self.collect_expr_opt(e.rhs());
1860 self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr)
1861 }
1862 }
1863 ast::Expr::TupleExpr(e) => {
1864 let mut exprs: Vec<_> = e.fields().filter_map(|expr| self.maybe_collect_expr(expr)).collect();
1865 if comma_follows_token(e.l_paren_token()) {
1868 exprs.insert(0, self.missing_expr());
1869 }
1870
1871 self.alloc_expr(Expr::Tuple { exprs: exprs.into_boxed_slice() }, syntax_ptr)
1872 }
1873 ast::Expr::ArrayExpr(e) => {
1874 let kind = e.kind();
1875
1876 match kind {
1877 ArrayExprKind::ElementList(e) => {
1878 let elements = e
1879 .filter_map(|expr| self.maybe_collect_expr(expr))
1880 .collect();
1881 self.alloc_expr(Expr::Array(Array::ElementList { elements }), syntax_ptr)
1882 }
1883 ArrayExprKind::Repeat { initializer, repeat } => {
1884 let initializer = self.collect_expr_opt(initializer);
1885 let repeat = self.with_label_rib(RibKind::Constant, |this| {
1886 if let Some(repeat) = repeat {
1887 this.with_binding_owner(|this| this.collect_expr(repeat))
1888 } else {
1889 this.missing_expr()
1890 }
1891 });
1892 self.alloc_expr(
1893 Expr::Array(Array::Repeat { initializer, repeat }),
1894 syntax_ptr,
1895 )
1896 }
1897 }
1898 }
1899
1900 ast::Expr::Literal(e) => self.alloc_expr(Expr::Literal(e.kind().into()), syntax_ptr),
1901 ast::Expr::IndexExpr(e) => {
1902 let base = self.collect_expr_opt(e.base());
1903 let index = self.collect_expr_opt(e.index());
1904 self.alloc_expr(Expr::Index { base, index }, syntax_ptr)
1905 }
1906 ast::Expr::RangeExpr(e) => self.collect_range_expr(e, syntax_ptr),
1907 ast::Expr::MacroExpr(e) => {
1908 let e = e.macro_call()?;
1909 let macro_ptr = AstPtr::new(&e);
1910 let id = self.collect_macro_call(e, macro_ptr, true, |this, expansion| {
1911 expansion.map(|it| this.maybe_collect_expr(it))
1912 });
1913 match id {
1914 Some(Some(id)) => {
1915 let src = self.expander.in_file(syntax_ptr);
1918 self.store.expr_map.insert(src, id.into());
1919 id
1920 }
1921 Some(None) => return None,
1923 None => self.alloc_expr(Expr::Missing, syntax_ptr),
1924 }
1925 }
1926 ast::Expr::UnderscoreExpr(_) => self.alloc_expr(Expr::Underscore, syntax_ptr),
1927 ast::Expr::AsmExpr(e) => self.lower_inline_asm(e, syntax_ptr),
1928 ast::Expr::OffsetOfExpr(e) => {
1929 let container = self.lower_type_ref_opt_disallow_impl_trait(e.ty());
1930 let fields = e.fields().map(|it| it.as_name()).collect();
1931 self.alloc_expr(Expr::OffsetOf(OffsetOf { container, fields }), syntax_ptr)
1932 }
1933 ast::Expr::FormatArgsExpr(f) => self.collect_format_args(f, syntax_ptr),
1934 ast::Expr::IncludeBytesExpr(_) => self.alloc_expr(Expr::IncludeBytes, syntax_ptr),
1935 ast::Expr::CfgPredExpr(e) => {
1936 let enabled = Expr::Literal(Literal::Bool(self.check_cfg_pred(e.cfg_predicate())));
1937 self.alloc_expr(enabled, syntax_ptr)
1938 },
1939 })
1940 }
1941
1942 fn collect_range_expr(&mut self, e: ast::RangeExpr, syntax_ptr: AstPtr<ast::Expr>) -> ExprId {
1943 let lhs = e.start().map(|lhs| self.collect_expr(lhs));
1944 let rhs = e.end().map(|rhs| self.collect_expr(rhs));
1945 let kind = e.op_kind().unwrap_or(ast::RangeOp::Exclusive);
1946 let new_range = self.features().new_range;
1947 let lang_items = self.lang_items();
1948 let lang_item = match (lhs, rhs, kind) {
1949 (None, None, _) => lang_items.RangeFull,
1950 (Some(..), None, ast::RangeOp::Exclusive) => {
1951 if new_range {
1952 lang_items.RangeFromCopy
1953 } else {
1954 lang_items.RangeFrom
1955 }
1956 }
1957 (None, Some(..), ast::RangeOp::Exclusive) => lang_items.RangeTo,
1958 (Some(..), Some(..), ast::RangeOp::Exclusive) => {
1959 if new_range {
1960 lang_items.RangeCopy
1961 } else {
1962 lang_items.Range
1963 }
1964 }
1965 (None, Some(..), ast::RangeOp::Inclusive) => {
1966 if new_range {
1967 lang_items.RangeToInclusiveCopy
1968 } else {
1969 lang_items.RangeToInclusive
1970 }
1971 }
1972 (Some(lhs), Some(rhs), ast::RangeOp::Inclusive) => {
1973 if new_range {
1974 lang_items.RangeInclusiveCopy
1975 } else {
1976 return self.collect_inclusive_range(syntax_ptr, lang_items, lhs, rhs);
1977 }
1978 }
1979 (Some(..), None, ast::RangeOp::Inclusive) => {
1980 if new_range {
1981 lang_items.RangeFromCopy
1982 } else {
1983 lang_items.RangeFrom
1984 }
1985 }
1986 };
1987 let Some(struct_path) = self.lang_path(lang_item) else {
1988 return self.alloc_expr(Expr::Missing, syntax_ptr);
1989 };
1990 let lhs = lhs.map(|lhs| (lhs, sym::start));
1991 let rhs = rhs.map(|rhs| {
1992 (
1993 rhs,
1994 if lang_item == lang_items.RangeInclusiveCopy
1995 || lang_item == lang_items.RangeToInclusiveCopy
1996 {
1997 sym::last
1998 } else {
1999 sym::end
2000 },
2001 )
2002 });
2003 let fields = std::iter::chain(lhs, rhs)
2004 .map(|(expr, name)| RecordLitField { name: Name::new_symbol_root(name), expr })
2005 .collect();
2006 self.alloc_expr(
2007 Expr::RecordLit { path: struct_path, fields, spread: RecordSpread::None },
2008 syntax_ptr,
2009 )
2010 }
2011
2012 fn collect_inclusive_range(
2013 &mut self,
2014 syntax_ptr: AstPtr<ast::Expr>,
2015 lang_items: &LangItems,
2016 lhs: ExprId,
2017 rhs: ExprId,
2018 ) -> ExprId {
2019 let fn_path = self.alloc_expr_desugared(self.lang_path_expr(lang_items.RangeInclusiveNew));
2020 self.alloc_expr(Expr::Call { callee: fn_path, args: Box::new([lhs, rhs]) }, syntax_ptr)
2021 }
2022
2023 fn collect_expr_path(&mut self, e: ast::PathExpr) -> Option<(Path, HygieneId)> {
2024 e.path().and_then(|path| {
2025 let path = self.lower_path(path, &mut Self::impl_trait_error_allocator)?;
2026 let may_be_variable = matches!(&path, Path::BarePath(mod_path) if mod_path.len() <= 1);
2028 let hygiene = if may_be_variable {
2029 self.hygiene_id_for(e.syntax().text_range())
2030 } else {
2031 HygieneId::ROOT
2032 };
2033 Some((path, hygiene))
2034 })
2035 }
2036
2037 fn path_is_destructuring_assignment(&self, path: &ModPath) -> bool {
2039 let (resolution, unresolved_idx, _) = self.def_map.resolve_path_locally(
2046 self.local_def_map,
2047 self.db,
2048 self.module,
2049 path,
2050 BuiltinShadowMode::Other,
2051 );
2052 match unresolved_idx {
2053 Some(_) => {
2054 resolution.take_types().is_some()
2057 }
2058 None => match resolution.take_values() {
2059 Some(ModuleDefId::EnumVariantId(_))
2061 | Some(ModuleDefId::AdtId(_))
2062 | Some(ModuleDefId::ConstId(_)) => true,
2063 _ => false,
2064 },
2065 }
2066 }
2067
2068 fn collect_expr_as_pat_opt(&mut self, expr: Option<ast::Expr>) -> PatId {
2069 match expr {
2070 Some(expr) => self.collect_expr_as_pat(expr),
2071 _ => self.missing_pat(),
2072 }
2073 }
2074
2075 fn collect_expr_as_pat(&mut self, expr: ast::Expr) -> PatId {
2076 self.maybe_collect_expr_as_pat(&expr).unwrap_or_else(|| {
2077 let src = self.expander.in_file(AstPtr::new(&expr).wrap_left());
2078 let expr = self.collect_expr(expr);
2079 let id = self.store.pats.alloc(Pat::Expr(expr));
2081 self.store.pat_map_back.insert(id, src);
2082 id
2083 })
2084 }
2085
2086 fn maybe_collect_expr_as_pat(&mut self, expr: &ast::Expr) -> Option<PatId> {
2087 if !self.check_cfg(expr) {
2088 return None;
2089 }
2090 let syntax_ptr = AstPtr::new(expr);
2091
2092 let result = match expr {
2093 ast::Expr::UnderscoreExpr(_) => self.alloc_pat_from_expr(Pat::Wild, syntax_ptr),
2094 ast::Expr::ParenExpr(e) => {
2095 if let Some(ast::Expr::RangeExpr(range)) = e.expr()
2097 && range.is_range_full()
2098 {
2099 return Some(self.alloc_pat_from_expr(
2100 Pat::Tuple { args: Box::default(), ellipsis: Some(0) },
2101 syntax_ptr,
2102 ));
2103 }
2104 return e.expr().and_then(|expr| self.maybe_collect_expr_as_pat(&expr));
2105 }
2106 ast::Expr::TupleExpr(e) => {
2107 let (ellipsis, args) = collect_tuple(self, e.fields());
2108 self.alloc_pat_from_expr(Pat::Tuple { args, ellipsis }, syntax_ptr)
2109 }
2110 ast::Expr::ArrayExpr(e) => {
2111 if e.semicolon_token().is_some() {
2112 return None;
2113 }
2114
2115 let mut elements = e.exprs();
2116 let mut rest_ptr = None;
2117 let prefix = elements
2118 .by_ref()
2119 .map_while(|elem| match collect_possibly_rest(self, elem.clone()) {
2120 Either::Left(elem) => Some(elem),
2121 Either::Right(()) => {
2122 rest_ptr = Some(AstPtr::new(&elem));
2123 None
2124 }
2125 })
2126 .collect();
2127 let suffix = elements.map(|elem| self.collect_expr_as_pat(elem)).collect();
2128 let slice = rest_ptr.map(|ptr| self.alloc_pat_from_expr(Pat::Rest, ptr));
2129 self.alloc_pat_from_expr(Pat::Slice { prefix, slice, suffix }, syntax_ptr)
2130 }
2131 ast::Expr::CallExpr(e) => {
2132 let path = collect_path(self, e.expr()?)?;
2133 let path = path
2134 .path()
2135 .and_then(|path| self.lower_path(path, &mut Self::impl_trait_error_allocator));
2136 let Some(path) = path else {
2137 return Some(self.missing_pat());
2138 };
2139 let (ellipsis, args) = collect_tuple(self, e.arg_list()?.args());
2140 self.alloc_pat_from_expr(Pat::TupleStruct { path, args, ellipsis }, syntax_ptr)
2141 }
2142 ast::Expr::PathExpr(e) => {
2143 let (path, hygiene) = self.collect_expr_path(e.clone())?;
2144 let mod_path = path.mod_path().expect("should not lower to lang path");
2145 if self.path_is_destructuring_assignment(mod_path) {
2146 let pat_id = self.alloc_pat_from_expr(Pat::Path(path), syntax_ptr);
2147 if !hygiene.is_root() {
2148 self.store.ident_hygiene.insert(pat_id.into(), hygiene);
2149 }
2150 pat_id
2151 } else {
2152 return None;
2153 }
2154 }
2155 ast::Expr::MacroExpr(e) => {
2156 let e = e.macro_call()?;
2157 let macro_ptr = AstPtr::new(&e);
2158 let src = self.expander.in_file(AstPtr::new(expr));
2159 let id = self.collect_macro_call(e, macro_ptr, true, |this, expansion| {
2160 this.collect_expr_as_pat_opt(expansion)
2161 });
2162 self.store.expr_map.insert(src, id.into());
2163 id
2164 }
2165 ast::Expr::RecordExpr(e) => {
2166 let path = e
2167 .path()
2168 .and_then(|path| self.lower_path(path, &mut Self::impl_trait_error_allocator));
2169 let Some(path) = path else {
2170 return Some(self.missing_pat());
2171 };
2172 let record_field_list = e.record_expr_field_list()?;
2173 let ellipsis = record_field_list.dotdot_token().is_some();
2174 if let Some(spread) = record_field_list.spread() {
2175 self.store.diagnostics.push(
2176 ExpressionStoreDiagnostics::FruInDestructuringAssignment {
2177 node: self.expander.in_file(AstPtr::new(&spread)),
2178 },
2179 );
2180 }
2181 let args = record_field_list
2182 .fields()
2183 .filter_map(|f| {
2184 if !self.check_cfg(&f) {
2185 return None;
2186 }
2187 let field_expr = f.expr()?;
2188 let pat = self.collect_expr_as_pat(field_expr);
2189 let name = f.field_name()?.as_name();
2190 let src = self.expander.in_file(AstPtr::new(&f).wrap_left());
2191 self.store.pat_field_map_back.insert(pat, src);
2192 Some(RecordFieldPat { name, pat })
2193 })
2194 .collect();
2195 self.alloc_pat_from_expr(Pat::Record { path, args, ellipsis }, syntax_ptr)
2196 }
2197 _ => return None,
2198 };
2199 return Some(result);
2200
2201 fn collect_path(this: &mut ExprCollector<'_>, expr: ast::Expr) -> Option<ast::PathExpr> {
2202 match expr {
2203 ast::Expr::PathExpr(e) => Some(e),
2204 ast::Expr::MacroExpr(mac) => {
2205 let call = mac.macro_call()?;
2206 {
2207 let macro_ptr = AstPtr::new(&call);
2208 this.collect_macro_call(call, macro_ptr, true, |this, expanded_path| {
2209 collect_path(this, expanded_path?)
2210 })
2211 }
2212 }
2213 _ => None,
2214 }
2215 }
2216
2217 fn collect_possibly_rest(
2218 this: &mut ExprCollector<'_>,
2219 expr: ast::Expr,
2220 ) -> Either<PatId, ()> {
2221 match &expr {
2222 ast::Expr::RangeExpr(e) if e.is_range_full() => Either::Right(()),
2223 ast::Expr::MacroExpr(mac) => match mac.macro_call() {
2224 Some(call) => {
2225 let macro_ptr = AstPtr::new(&call);
2226 let pat = this.collect_macro_call(
2227 call,
2228 macro_ptr,
2229 true,
2230 |this, expanded_expr| match expanded_expr {
2231 Some(expanded_pat) => collect_possibly_rest(this, expanded_pat),
2232 None => Either::Left(this.missing_pat()),
2233 },
2234 );
2235 if let Either::Left(pat) = pat {
2236 let src = this.expander.in_file(AstPtr::new(&expr).wrap_left());
2237 this.store.pat_map_back.insert(pat, src);
2238 }
2239 pat
2240 }
2241 None => {
2242 let ptr = AstPtr::new(&expr);
2243 Either::Left(this.alloc_pat_from_expr(Pat::Missing, ptr))
2244 }
2245 },
2246 _ => Either::Left(this.collect_expr_as_pat(expr)),
2247 }
2248 }
2249
2250 fn collect_tuple(
2251 this: &mut ExprCollector<'_>,
2252 fields: ast::AstChildren<ast::Expr>,
2253 ) -> (Option<u32>, Box<[la_arena::Idx<Pat>]>) {
2254 let mut ellipsis = None;
2255 let args = fields
2256 .enumerate()
2257 .filter_map(|(idx, elem)| {
2258 match collect_possibly_rest(this, elem) {
2259 Either::Left(pat) => Some(pat),
2260 Either::Right(()) => {
2261 if ellipsis.is_none() {
2262 ellipsis = Some(idx as u32);
2263 }
2264 None
2266 }
2267 }
2268 })
2269 .collect();
2270 (ellipsis, args)
2271 }
2272 }
2273
2274 fn with_binding_owner_and_return(
2276 &mut self,
2277 create_expr: impl FnOnce(&mut Self) -> (ExprId, ExprId),
2278 ) -> ExprId {
2279 let prev_unowned_bindings_len = self.unowned_bindings.len();
2280 let (bindings_owner, expr_to_return) = create_expr(self);
2281 self.associate_unowned_bindings_with(prev_unowned_bindings_len, bindings_owner);
2282 expr_to_return
2283 }
2284
2285 fn associate_unowned_bindings_with(
2286 &mut self,
2287 prev_unowned_bindings_len: usize,
2288 bindings_owner: ExprId,
2289 ) {
2290 for binding in self.unowned_bindings.drain(prev_unowned_bindings_len..) {
2291 self.store.binding_owners.insert(binding, bindings_owner);
2292 }
2293 }
2294
2295 fn with_binding_owner(&mut self, create_expr: impl FnOnce(&mut Self) -> ExprId) -> ExprId {
2296 self.with_binding_owner_and_return(move |this| {
2297 let expr = create_expr(this);
2298 (expr, expr)
2299 })
2300 }
2301
2302 fn desugar_try_block(&mut self, e: BlockExpr, result_type: Option<ast::Type>) -> ExprId {
2306 let try_from_output = self.lang_path(self.lang_items().TryTraitFromOutput);
2307 let label = self.generate_new_name();
2308 let label = self.alloc_label_desugared(Label { name: label }, AstPtr::new(&e).wrap_right());
2309 let try_block_info = match result_type {
2310 Some(_) => TryBlock::Heterogeneous { label },
2311 None => TryBlock::Homogeneous { label },
2312 };
2313 let old_try_block = self.current_try_block.replace(try_block_info);
2314
2315 let ptr = AstPtr::new(&e).upcast();
2316 let (btail, expr_id) = self.with_labeled_rib(label, HygieneId::ROOT, |this| {
2317 let mut btail = None;
2318 let block = this.collect_block_(e, |_, id, statements, tail| {
2319 btail = tail;
2320 Expr::Block { id, statements, tail, label: Some(label), unsafe_: Unsafe::No }
2321 });
2322 (btail, block)
2323 });
2324
2325 let callee = self
2326 .alloc_expr_desugared_with_ptr(try_from_output.map_or(Expr::Missing, Expr::Path), ptr);
2327 let next_tail = match btail {
2328 Some(tail) => self
2329 .alloc_expr_desugared_with_ptr(Expr::Call { callee, args: Box::new([tail]) }, ptr),
2330 None => {
2331 let unit =
2332 self.alloc_expr_desugared_with_ptr(Expr::Tuple { exprs: Box::new([]) }, ptr);
2333 self.alloc_expr_desugared_with_ptr(
2334 Expr::Call { callee, args: Box::new([unit]) },
2335 ptr,
2336 )
2337 }
2338 };
2339 let Expr::Block { tail, .. } = &mut self.store.exprs[expr_id] else {
2340 unreachable!("block was lowered to non-block");
2341 };
2342 *tail = Some(next_tail);
2343 self.current_try_block = old_try_block;
2344 match result_type {
2345 Some(ty) => {
2346 let name = self.generate_new_name();
2348 let type_ref = self.lower_type_ref_disallow_impl_trait(ty);
2349 let binding = self.alloc_binding(
2350 name.clone(),
2351 BindingAnnotation::Unannotated,
2352 HygieneId::ROOT,
2353 );
2354 let pat = self.alloc_pat_desugared(Pat::Bind { id: binding, subpat: None });
2355 self.add_definition_to_binding(binding, pat);
2356 let tail_expr =
2357 self.alloc_expr_desugared_with_ptr(Expr::Path(Path::from(name)), ptr);
2358 self.alloc_expr_desugared_with_ptr(
2359 Expr::Block {
2360 id: None,
2361 statements: Box::new([Statement::Let {
2362 pat,
2363 type_ref: Some(type_ref),
2364 initializer: Some(expr_id),
2365 else_branch: None,
2366 }]),
2367 tail: Some(tail_expr),
2368 label: None,
2369 unsafe_: Unsafe::No,
2370 },
2371 ptr,
2372 )
2373 }
2374 None => expr_id,
2375 }
2376 }
2377
2378 fn collect_while_loop(&mut self, syntax_ptr: AstPtr<ast::Expr>, e: ast::WhileExpr) -> ExprId {
2395 let label = e.label().map(|label| {
2396 (self.hygiene_id_for(label.syntax().text_range()), self.collect_label(label))
2397 });
2398 let body = self.collect_labelled_block_opt(label, e.loop_body());
2399
2400 let condition = match label {
2414 Some((label_hygiene, label)) => self.with_labeled_rib(label, label_hygiene, |this| {
2415 this.collect_expr_opt(e.condition())
2416 }),
2417 None => self.collect_expr_opt(e.condition()),
2418 };
2419
2420 let break_expr = self.alloc_expr(Expr::Break { expr: None, label: None }, syntax_ptr);
2421 let if_expr = self.alloc_expr(
2422 Expr::If { condition, then_branch: body, else_branch: Some(break_expr) },
2423 syntax_ptr,
2424 );
2425 self.alloc_expr(
2426 Expr::Loop { body: if_expr, label: label.map(|it| it.1), source: LoopSource::While },
2427 syntax_ptr,
2428 )
2429 }
2430
2431 fn collect_for_loop(&mut self, syntax_ptr: AstPtr<ast::Expr>, e: ast::ForExpr) -> ExprId {
2445 let lang_items = self.lang_items();
2446 let (Some(into_iter_fn), Some(iter_next_fn), Some(option_some), Some(option_none)) = (
2447 self.lang_path(lang_items.IntoIterIntoIter),
2448 self.lang_path(lang_items.IteratorNext),
2449 self.lang_path(lang_items.OptionSome),
2450 self.lang_path(lang_items.OptionNone),
2451 ) else {
2452 return self.missing_expr();
2453 };
2454 let iterable = e.iterable();
2455 let syntax_ptr_iterable = iterable.as_ref().map_or(syntax_ptr, AstPtr::new);
2456 let loop_body = e.loop_body().map(|it| it.into());
2457 let head = self.collect_expr_opt(iterable);
2458 let into_iter_fn_expr =
2459 self.alloc_expr_desugared_with_ptr(Expr::Path(into_iter_fn), syntax_ptr_iterable);
2460 let iterator = self.alloc_expr_desugared_with_ptr(
2461 Expr::Call { callee: into_iter_fn_expr, args: Box::new([head]) },
2462 syntax_ptr_iterable,
2463 );
2464 let none_arm = MatchArm {
2465 pat: self.alloc_pat_desugared(Pat::Path(option_none)),
2466 guard: None,
2467 expr: self
2468 .alloc_expr_desugared_with_ptr(Expr::Break { expr: None, label: None }, syntax_ptr),
2469 };
2470 let some_pat = Pat::TupleStruct {
2471 path: option_some,
2472 args: Box::new([self.collect_pat_top(e.pat())]),
2473 ellipsis: None,
2474 };
2475 let label = e.label().map(|label| {
2476 (self.hygiene_id_for(label.syntax().text_range()), self.collect_label(label))
2477 });
2478 let some_arm = MatchArm {
2479 pat: self.alloc_pat_desugared(some_pat),
2480 guard: None,
2481 expr: self.with_opt_labeled_rib(label, |this| this.collect_expr_opt(loop_body)),
2482 };
2483 let iter_name = self.generate_new_name();
2484 let iter_expr = self
2485 .alloc_expr_desugared_with_ptr(Expr::Path(Path::from(iter_name.clone())), syntax_ptr);
2486 let iter_expr_mut = self.alloc_expr_desugared_with_ptr(
2487 Expr::Ref { expr: iter_expr, rawness: Rawness::Ref, mutability: Mutability::Mut },
2488 syntax_ptr,
2489 );
2490 let iter_next_fn_expr =
2491 self.alloc_expr_desugared_with_ptr(Expr::Path(iter_next_fn), syntax_ptr);
2492 let iter_next_expr = self.alloc_expr_desugared_with_ptr(
2493 Expr::Call { callee: iter_next_fn_expr, args: Box::new([iter_expr_mut]) },
2494 syntax_ptr,
2495 );
2496 let loop_inner = self.alloc_expr_desugared_with_ptr(
2497 Expr::Match { expr: iter_next_expr, arms: Box::new([none_arm, some_arm]) },
2498 syntax_ptr,
2499 );
2500 let loop_inner = self.alloc_expr_desugared_with_ptr(
2501 Expr::Block {
2502 id: None,
2503 statements: Box::default(),
2504 tail: Some(loop_inner),
2505 label: None,
2506 unsafe_: Unsafe::No,
2507 },
2508 syntax_ptr,
2509 );
2510 let loop_outer = self.alloc_expr_desugared_with_ptr(
2511 Expr::Loop {
2512 body: loop_inner,
2513 label: label.map(|it| it.1),
2514 source: LoopSource::ForLoop,
2515 },
2516 syntax_ptr,
2517 );
2518 let iter_binding =
2519 self.alloc_binding(iter_name, BindingAnnotation::Mutable, HygieneId::ROOT);
2520 let iter_pat = self.alloc_pat_desugared(Pat::Bind { id: iter_binding, subpat: None });
2521 self.add_definition_to_binding(iter_binding, iter_pat);
2522 self.alloc_expr(
2523 Expr::Match {
2524 expr: iterator,
2525 arms: Box::new([MatchArm { pat: iter_pat, guard: None, expr: loop_outer }]),
2526 },
2527 syntax_ptr,
2528 )
2529 }
2530
2531 fn collect_try_operator(&mut self, syntax_ptr: AstPtr<ast::Expr>, e: ast::TryExpr) -> ExprId {
2545 let lang_items = self.lang_items();
2546 let (Some(try_branch), Some(cf_continue), Some(cf_break)) = (
2547 self.lang_path(lang_items.TryTraitBranch),
2548 self.lang_path(lang_items.ControlFlowContinue),
2549 self.lang_path(lang_items.ControlFlowBreak),
2550 ) else {
2551 return self.missing_expr();
2552 };
2553 let operand = self.collect_expr_opt(e.expr());
2554 let try_branch = self.alloc_expr(Expr::Path(try_branch), syntax_ptr);
2555 let expr = self
2556 .alloc_expr(Expr::Call { callee: try_branch, args: Box::new([operand]) }, syntax_ptr);
2557 let continue_name = self.generate_new_name();
2558 let continue_binding = self.alloc_binding(
2559 continue_name.clone(),
2560 BindingAnnotation::Unannotated,
2561 HygieneId::ROOT,
2562 );
2563 let continue_bpat =
2564 self.alloc_pat_desugared(Pat::Bind { id: continue_binding, subpat: None });
2565 self.add_definition_to_binding(continue_binding, continue_bpat);
2566 let continue_arm = MatchArm {
2567 pat: self.alloc_pat_desugared(Pat::TupleStruct {
2568 path: cf_continue,
2569 args: Box::new([continue_bpat]),
2570 ellipsis: None,
2571 }),
2572 guard: None,
2573 expr: self.alloc_expr(Expr::Path(Path::from(continue_name)), syntax_ptr),
2574 };
2575 let break_name = self.generate_new_name();
2576 let break_binding =
2577 self.alloc_binding(break_name.clone(), BindingAnnotation::Unannotated, HygieneId::ROOT);
2578 let break_bpat = self.alloc_pat_desugared(Pat::Bind { id: break_binding, subpat: None });
2579 self.add_definition_to_binding(break_binding, break_bpat);
2580 let break_arm = MatchArm {
2581 pat: self.alloc_pat_desugared(Pat::TupleStruct {
2582 path: cf_break,
2583 args: Box::new([break_bpat]),
2584 ellipsis: None,
2585 }),
2586 guard: None,
2587 expr: {
2588 let it = self.alloc_expr(Expr::Path(Path::from(break_name)), syntax_ptr);
2589 let convert_fn = match self.current_try_block {
2590 Some(TryBlock::Homogeneous { .. }) => {
2591 self.lang_path(lang_items.ResidualIntoTryType)
2592 }
2593 Some(TryBlock::Heterogeneous { .. }) | None => {
2594 self.lang_path(lang_items.TryTraitFromResidual)
2595 }
2596 };
2597 let callee =
2598 self.alloc_expr(convert_fn.map_or(Expr::Missing, Expr::Path), syntax_ptr);
2599 let result =
2600 self.alloc_expr(Expr::Call { callee, args: Box::new([it]) }, syntax_ptr);
2601 self.alloc_expr(
2602 match self.current_try_block {
2603 Some(
2604 TryBlock::Heterogeneous { label } | TryBlock::Homogeneous { label },
2605 ) => Expr::Break { expr: Some(result), label: Some(label) },
2606 None => Expr::Return { expr: Some(result) },
2607 },
2608 syntax_ptr,
2609 )
2610 },
2611 };
2612 let arms = Box::new([continue_arm, break_arm]);
2613 self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
2614 }
2615
2616 fn collect_macro_call<T, U>(
2617 &mut self,
2618 mcall: ast::MacroCall,
2619 syntax_ptr: AstPtr<ast::MacroCall>,
2620 record_diagnostics: bool,
2621 collector: impl FnOnce(&mut Self, Option<T>) -> U,
2622 ) -> U
2623 where
2624 T: ast::AstNode,
2625 {
2626 let macro_call_ptr = self.expander.in_file(syntax_ptr);
2627
2628 let block_call = self.def_map.modules[self.module].scope.macro_invoc(
2629 self.expander.in_file(self.expander.ast_id_map().ast_id_for_ptr(syntax_ptr)),
2630 );
2631 let res = match block_call {
2632 Some(call) => Ok(self.expander.enter_expand_id(self.db, call)),
2634 None => {
2635 let resolver = |path: &_| {
2636 self.def_map
2637 .resolve_path(
2638 self.local_def_map,
2639 self.db,
2640 self.module,
2641 path,
2642 crate::item_scope::BuiltinShadowMode::Other,
2643 Some(MacroSubNs::Bang),
2644 )
2645 .0
2646 .take_macros()
2647 };
2648 self.expander.enter_expand(
2649 self.db,
2650 mcall,
2651 self.krate,
2652 resolver,
2653 &mut |ptr, call| {
2654 _ = self.store.expansions.insert(ptr.map(|(it, _)| it), call);
2655 },
2656 )
2657 }
2658 };
2659
2660 let res = match res {
2661 Ok(res) => res,
2662 Err(UnresolvedMacro { path }) => {
2663 if record_diagnostics {
2664 self.store.diagnostics.push(ExpressionStoreDiagnostics::UnresolvedMacroCall {
2665 node: self.expander.in_file(syntax_ptr),
2666 path,
2667 });
2668 }
2669 return collector(self, None);
2670 }
2671 };
2672 match res.value {
2675 Some((mark, expansion)) => {
2676 if let Some(macro_file) = self.expander.current_file_id().macro_file() {
2679 self.store.expansions.insert(macro_call_ptr, macro_file);
2680 }
2681
2682 let id = collector(self, expansion.map(|it| it.tree()));
2683 self.expander.exit(mark);
2684 id
2685 }
2686 None => collector(self, None),
2687 }
2688 }
2689
2690 fn collect_macro_as_stmt(
2691 &mut self,
2692 statements: &mut Vec<Statement>,
2693 mac: ast::MacroExpr,
2694 ) -> Option<ExprId> {
2695 if !self.check_cfg(&ast::Expr::MacroExpr(mac.clone())) {
2696 return None;
2697 }
2698
2699 let mac_call = mac.macro_call()?;
2700 let syntax_ptr = AstPtr::new(&ast::Expr::from(mac));
2701 let macro_ptr = AstPtr::new(&mac_call);
2702 let expansion = self.collect_macro_call(
2703 mac_call,
2704 macro_ptr,
2705 false,
2706 |this, expansion: Option<ast::MacroStmts>| match expansion {
2707 Some(expansion) => {
2708 expansion.statements().for_each(|stmt| this.collect_stmt(statements, stmt));
2709 expansion.expr().and_then(|expr| match expr {
2710 ast::Expr::MacroExpr(mac) => this.collect_macro_as_stmt(statements, mac),
2711 expr => this.maybe_collect_expr(expr),
2712 })
2713 }
2714 None => None,
2715 },
2716 );
2717 expansion.inspect(|&tail| {
2718 let src = self.expander.in_file(syntax_ptr);
2721 self.store.expr_map.insert(src, tail.into());
2722 })
2723 }
2724
2725 fn collect_stmt(&mut self, statements: &mut Vec<Statement>, s: ast::Stmt) {
2726 match s {
2727 ast::Stmt::LetStmt(stmt) => {
2728 if !self.check_cfg(&stmt) {
2729 return;
2730 }
2731 let pat = self.collect_pat_top(stmt.pat());
2732 let type_ref = stmt.ty().map(|it| self.lower_type_ref_disallow_impl_trait(it));
2733 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
2734 let else_branch = stmt
2735 .let_else()
2736 .and_then(|let_else| let_else.block_expr())
2737 .map(|block| self.collect_block(block));
2738 statements.push(Statement::Let { pat, type_ref, initializer, else_branch });
2739 }
2740 ast::Stmt::ExprStmt(stmt) => {
2741 let expr = stmt.expr();
2742 let has_semi = stmt.semicolon_token().is_some();
2743 if let Some(ast::Expr::MacroExpr(mac)) = expr {
2745 if let Some(expr) = self.collect_macro_as_stmt(statements, mac) {
2746 statements.push(Statement::Expr { expr, has_semi })
2747 }
2748 } else if let Some(expr) = expr.and_then(|expr| self.maybe_collect_expr(expr)) {
2749 statements.push(Statement::Expr { expr, has_semi });
2750 }
2751 }
2752 ast::Stmt::Item(ast::Item::MacroDef(macro_)) => {
2753 if !self.check_cfg(¯o_) {
2754 return;
2755 }
2756 let Some(name) = macro_.name() else {
2757 statements.push(Statement::Item(Item::Other));
2758 return;
2759 };
2760 let name = name.as_name();
2761 let macro_id =
2762 self.def_map.modules[self.def_map.root].scope.get(&name).take_macros();
2763 self.collect_macro_def(statements, macro_id);
2764 }
2765 ast::Stmt::Item(ast::Item::MacroRules(macro_)) => {
2766 if !self.check_cfg(¯o_) {
2767 return;
2768 }
2769 let Some(name) = macro_.name() else {
2770 statements.push(Statement::Item(Item::Other));
2771 return;
2772 };
2773 let name = name.as_name();
2774 let macro_defs_count =
2775 self.current_block_legacy_macro_defs_count.entry(name.clone()).or_insert(0);
2776 let macro_id = self.def_map.modules[self.def_map.root]
2777 .scope
2778 .get_legacy_macro(&name)
2779 .and_then(|it| it.get(*macro_defs_count))
2780 .copied();
2781 *macro_defs_count += 1;
2782 self.collect_macro_def(statements, macro_id);
2783 }
2784 ast::Stmt::Item(_item) => statements.push(Statement::Item(Item::Other)),
2785 }
2786 }
2787
2788 fn collect_macro_def(&mut self, statements: &mut Vec<Statement>, macro_id: Option<MacroId>) {
2789 let Some(macro_id) = macro_id else {
2790 never!("def map should have macro definition, but it doesn't");
2791 statements.push(Statement::Item(Item::Other));
2792 return;
2793 };
2794 let macro_id = macro_id.definition(self.db);
2795 statements.push(Statement::Item(Item::MacroDef(Box::new(macro_id))));
2796 self.label_ribs.push(LabelRib::new(RibKind::MacroDef(Box::new(macro_id))));
2797 }
2798
2799 fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId {
2800 self.collect_block_(block, |_, id, statements, tail| Expr::Block {
2801 id,
2802 statements,
2803 tail,
2804 label: None,
2805 unsafe_: Unsafe::No,
2806 })
2807 }
2808
2809 fn collect_block_(
2810 &mut self,
2811 block: ast::BlockExpr,
2812 mk_block: impl FnOnce(&mut Self, Option<BlockId>, Box<[Statement]>, Option<ExprId>) -> Expr,
2813 ) -> ExprId {
2814 let block_id = (|| {
2815 let token = self.lowering_mode.allow_tracked_structs()?;
2816 let file_local_id = self.expander.ast_id_map().ast_id_for_block(&block)?;
2817 let ast_id = self.expander.in_file(file_local_id);
2818 Some(unsafe { BlockIdLt::new(self.db, ast_id, self.module, token).to_static() })
2819 })();
2820
2821 let (module, def_map) =
2822 match block_id.map(|block_id| (block_def_map(self.db, block_id), block_id)) {
2823 Some((def_map, block_id)) => {
2824 self.store.block_scopes.push(block_id);
2825 (def_map.root_module_id(), def_map)
2826 }
2827 None => (self.module, self.def_map),
2828 };
2829 let prev_def_map = mem::replace(&mut self.def_map, def_map);
2830 let prev_local_module = mem::replace(&mut self.module, module);
2831 let prev_legacy_macros_count = mem::take(&mut self.current_block_legacy_macro_defs_count);
2832
2833 let mut statements = Vec::new();
2834 block.statements().for_each(|s| self.collect_stmt(&mut statements, s));
2835 let tail = block.tail_expr().and_then(|e| match e {
2836 ast::Expr::MacroExpr(mac) => self.collect_macro_as_stmt(&mut statements, mac),
2837 expr => self.maybe_collect_expr(expr),
2838 });
2839 let tail = tail.or_else(|| {
2840 let stmt = statements.pop()?;
2841 if let Statement::Expr { expr, has_semi: false } = stmt {
2842 return Some(expr);
2843 }
2844 statements.push(stmt);
2845 None
2846 });
2847
2848 let syntax_node_ptr = AstPtr::new(&block.into());
2849 let expr = mk_block(self, block_id, statements.into_boxed_slice(), tail);
2850 let expr_id = self.alloc_expr(expr, syntax_node_ptr);
2851
2852 self.def_map = prev_def_map;
2853 self.module = prev_local_module;
2854 self.current_block_legacy_macro_defs_count = prev_legacy_macros_count;
2855 expr_id
2856 }
2857
2858 fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
2859 match expr {
2860 Some(block) => self.collect_block(block),
2861 None => self.missing_expr(),
2862 }
2863 }
2864
2865 fn collect_labelled_block_opt(
2866 &mut self,
2867 label: Option<(HygieneId, LabelId)>,
2868 expr: Option<ast::BlockExpr>,
2869 ) -> ExprId {
2870 match label {
2871 Some((hygiene, label)) => {
2872 self.with_labeled_rib(label, hygiene, |this| this.collect_block_opt(expr))
2873 }
2874 None => self.collect_block_opt(expr),
2875 }
2876 }
2877
2878 fn collect_param_as_ident(&mut self, pat: ast::Pat) -> PatId {
2879 match &pat {
2885 ast::Pat::IdentPat(bp) if bp.is_simple_ident() => {
2886 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
2887 let hygiene = bp
2888 .name()
2889 .map(|name| self.hygiene_id_for(name.syntax().text_range()))
2890 .unwrap_or(HygieneId::ROOT);
2891 let binding = self.alloc_binding(name, BindingAnnotation::Unannotated, hygiene);
2892 let pat =
2893 self.alloc_pat(Pat::Bind { id: binding, subpat: None }, AstPtr::new(&pat));
2894 self.add_definition_to_binding(binding, pat);
2895 pat
2896 }
2897 ast::Pat::WildcardPat(_) => self.alloc_pat(Pat::Wild, AstPtr::new(&pat)),
2898 ast::Pat::MacroPat(mac) => self
2899 .collect_macro_pat_with(mac.clone(), |this, pat| this.collect_param_as_ident(pat)),
2900 _ => {
2901 self.store.diagnostics.push(ExpressionStoreDiagnostics::PatternArgInExternFn {
2902 node: self.expander.in_file(AstPtr::new(&pat)),
2903 });
2904 self.missing_pat()
2905 }
2906 }
2907 }
2908
2909 fn collect_pat_top(&mut self, pat: Option<ast::Pat>) -> PatId {
2912 match pat {
2913 Some(pat) => self.collect_pat(pat, &mut BindingList::default()),
2914 None => self.missing_pat(),
2915 }
2916 }
2917
2918 fn collect_pat(&mut self, pat: ast::Pat, binding_list: &mut BindingList) -> PatId {
2919 let pattern = match &pat {
2920 ast::Pat::IdentPat(bp) => {
2921 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
2922 let hygiene = bp
2923 .name()
2924 .map(|name| self.hygiene_id_for(name.syntax().text_range()))
2925 .unwrap_or(HygieneId::ROOT);
2926
2927 let annotation =
2928 BindingAnnotation::new(bp.mut_token().is_some(), bp.ref_token().is_some());
2929 let subpat = bp.pat().map(|subpat| self.collect_pat(subpat, binding_list));
2930
2931 let is_simple_ident_pat =
2932 annotation == BindingAnnotation::Unannotated && subpat.is_none();
2933 let (binding, pattern) = if is_simple_ident_pat {
2934 let (resolved, _) = self.def_map.resolve_path(
2937 self.local_def_map,
2938 self.db,
2939 self.module,
2940 &name.clone().into(),
2941 BuiltinShadowMode::Other,
2942 None,
2943 );
2944 match resolved.take_values() {
2948 Some(ModuleDefId::ConstId(_)) => (None, Pat::Path(name.into())),
2949 Some(ModuleDefId::EnumVariantId(_)) => (None, Pat::Path(name.into())),
2950 Some(ModuleDefId::AdtId(AdtId::StructId(_))) => {
2951 (None, Pat::Path(name.into()))
2952 }
2953 _ => {
2955 let id = binding_list.find(self, name, hygiene, annotation);
2956 (Some(id), Pat::Bind { id, subpat })
2957 }
2958 }
2959 } else {
2960 let id = binding_list.find(self, name, hygiene, annotation);
2961 (Some(id), Pat::Bind { id, subpat })
2962 };
2963
2964 let ptr = AstPtr::new(&pat);
2965 let pat = self.alloc_pat(pattern, ptr);
2966 if let Some(binding_id) = binding {
2967 self.add_definition_to_binding(binding_id, pat);
2968 }
2969 return pat;
2970 }
2971 ast::Pat::TupleStructPat(p) => {
2972 let path = p
2973 .path()
2974 .and_then(|path| self.lower_path(path, &mut Self::impl_trait_error_allocator));
2975 let Some(path) = path else {
2976 return self.missing_pat();
2977 };
2978 let (args, ellipsis) = self.collect_tuple_pat(
2979 p.fields(),
2980 comma_follows_token(p.l_paren_token()),
2981 binding_list,
2982 );
2983 Pat::TupleStruct { path, args, ellipsis }
2984 }
2985 ast::Pat::RefPat(p) => {
2986 let pat = self.collect_pat_opt(p.pat(), binding_list);
2987 let mutability = Mutability::from_mutable(p.mut_token().is_some());
2988 Pat::Ref { pat, mutability }
2989 }
2990 ast::Pat::PathPat(p) => {
2991 let path = p
2992 .path()
2993 .and_then(|path| self.lower_path(path, &mut Self::impl_trait_error_allocator));
2994 path.map(Pat::Path).unwrap_or(Pat::Missing)
2995 }
2996 ast::Pat::OrPat(p) => 'b: {
2997 let prev_is_used = mem::take(&mut binding_list.is_used);
2998 let prev_reject_new = mem::take(&mut binding_list.reject_new);
2999 let mut pats = Vec::with_capacity(p.pats().count());
3000 let mut it = p.pats();
3001 let Some(first) = it.next() else {
3002 break 'b Pat::Or(Box::new([]));
3003 };
3004 pats.push(self.collect_pat(first, binding_list));
3005 binding_list.reject_new = true;
3006 for rest in it {
3007 for it in binding_list.is_used.values_mut() {
3008 *it = false;
3009 }
3010 pats.push(self.collect_pat(rest, binding_list));
3011 for (&id, &is_used) in binding_list.is_used.iter() {
3012 if !is_used {
3013 self.store.bindings[id].problems =
3014 Some(BindingProblems::NotBoundAcrossAll);
3015 }
3016 }
3017 }
3018 binding_list.reject_new = prev_reject_new;
3019 let current_is_used = mem::replace(&mut binding_list.is_used, prev_is_used);
3020 for (id, _) in current_is_used.into_iter() {
3021 binding_list.check_is_used(self, id);
3022 }
3023 if let &[pat] = &*pats {
3024 return pat;
3026 }
3027 Pat::Or(pats.into())
3028 }
3029 ast::Pat::ParenPat(p) => return self.collect_pat_opt(p.pat(), binding_list),
3030 ast::Pat::TuplePat(p) => {
3031 let (args, ellipsis) = self.collect_tuple_pat(
3032 p.fields(),
3033 comma_follows_token(p.l_paren_token()),
3034 binding_list,
3035 );
3036 Pat::Tuple { args, ellipsis }
3037 }
3038 ast::Pat::WildcardPat(_) => Pat::Wild,
3039 ast::Pat::RecordPat(p) => {
3040 let path = p
3041 .path()
3042 .and_then(|path| self.lower_path(path, &mut Self::impl_trait_error_allocator));
3043 let Some(path) = path else {
3044 return self.missing_pat();
3045 };
3046 let record_pat_field_list =
3047 &p.record_pat_field_list().expect("every struct should have a field list");
3048 let args = record_pat_field_list
3049 .fields()
3050 .filter_map(|f| {
3051 if !self.check_cfg(&f) {
3052 return None;
3053 }
3054 let ast_pat = f.pat()?;
3055 let pat = self.collect_pat(ast_pat, binding_list);
3056 let name = f.field_name()?.as_name();
3057 let src = self.expander.in_file(AstPtr::new(&f).wrap_right());
3058 self.store.pat_field_map_back.insert(pat, src);
3059 Some(RecordFieldPat { name, pat })
3060 })
3061 .collect();
3062
3063 let ellipsis = record_pat_field_list.rest_pat().is_some();
3064
3065 Pat::Record { path, args, ellipsis }
3066 }
3067 ast::Pat::SlicePat(p) => {
3068 let SlicePatComponents { prefix, slice, suffix } = p.components();
3069
3070 Pat::Slice {
3071 prefix: prefix.into_iter().map(|p| self.collect_pat(p, binding_list)).collect(),
3072 slice: slice.map(|p| self.collect_pat(p, binding_list)),
3073 suffix: suffix.into_iter().map(|p| self.collect_pat(p, binding_list)).collect(),
3074 }
3075 }
3076 ast::Pat::LiteralPat(lit) => 'b: {
3077 let Some((hir_lit, ast_lit)) = pat_literal_to_hir(lit) else {
3078 break 'b Pat::Missing;
3079 };
3080 let expr = Expr::Literal(hir_lit);
3081 let expr_ptr = AstPtr::new(&ast::Expr::Literal(ast_lit));
3082 let expr_id = self.alloc_expr(expr, expr_ptr);
3083 Pat::Lit(expr_id)
3084 }
3085 ast::Pat::RestPat(_) => Pat::Rest,
3086 ast::Pat::BoxPat(boxpat) => {
3087 let inner = self.collect_pat_opt(boxpat.pat(), binding_list);
3088 Pat::Box { inner }
3089 }
3090 ast::Pat::DerefPat(inner) => {
3091 let inner = self.collect_pat_opt(inner.pat(), binding_list);
3092 Pat::Deref { inner }
3093 }
3094 ast::Pat::NotNull(_) => Pat::NotNull,
3095 ast::Pat::ConstBlockPat(_) => Pat::Missing,
3096 ast::Pat::CfgPredPat(p) => {
3097 let enabled = Expr::Literal(Literal::Bool(self.check_cfg_pred(p.cfg_predicate())));
3098 let expr_id = self.alloc_expr_from_pat(enabled, AstPtr::new(&pat));
3099 Pat::Lit(expr_id)
3100 }
3101 ast::Pat::MacroPat(mac) => {
3102 return self.collect_macro_pat_with(mac.clone(), |this, expanded_pat| {
3103 this.collect_pat(expanded_pat, binding_list)
3104 });
3105 }
3106 ast::Pat::RangePat(p) => {
3107 let mut range_part_lower = |p: Option<ast::Pat>| -> Option<ExprId> {
3108 p.and_then(|it| {
3109 let ptr = PatPtr::new(&it);
3110 match &it {
3111 ast::Pat::LiteralPat(it) => Some(self.alloc_expr_from_pat(
3112 Expr::Literal(pat_literal_to_hir(it)?.0),
3113 ptr,
3114 )),
3115 ast::Pat::IdentPat(ident) if ident.is_simple_ident() => ident
3116 .name()
3117 .map(|name| name.as_name())
3118 .map(Path::from)
3119 .map(|path| self.alloc_expr_from_pat(Expr::Path(path), ptr)),
3120 ast::Pat::PathPat(p) => p
3121 .path()
3122 .and_then(|path| {
3123 self.lower_path(path, &mut Self::impl_trait_error_allocator)
3124 })
3125 .map(|parsed| self.alloc_expr_from_pat(Expr::Path(parsed), ptr)),
3126 _ => None,
3129 }
3130 })
3131 };
3132 let start = range_part_lower(p.start());
3133 let end = range_part_lower(p.end());
3134 match p.op_kind() {
3135 Some(range_type) => Pat::Range { start, end, range_type },
3136 None => Pat::Missing,
3137 }
3138 }
3139 };
3140 let ptr = AstPtr::new(&pat);
3141 self.alloc_pat(pattern, ptr)
3142 }
3143
3144 fn collect_macro_pat_with(
3145 &mut self,
3146 mac: ast::MacroPat,
3147 callback: impl FnOnce(&mut Self, ast::Pat) -> PatId,
3148 ) -> PatId {
3149 match mac.macro_call() {
3150 Some(call) => {
3151 let macro_ptr = AstPtr::new(&call);
3152 let src = self.expander.in_file(AstPtr::new(&mac.into()));
3153 let pat = self.collect_macro_call(call, macro_ptr, true, |this, expanded_pat| {
3154 match expanded_pat {
3155 Some(pat) => callback(this, pat),
3156 None => this.missing_pat(),
3157 }
3158 });
3159 self.store.pat_map.insert(src, pat.into());
3160 pat
3161 }
3162 None => self.missing_pat(),
3163 }
3164 }
3165
3166 fn collect_pat_opt(&mut self, pat: Option<ast::Pat>, binding_list: &mut BindingList) -> PatId {
3167 match pat {
3168 Some(pat) => self.collect_pat(pat, binding_list),
3169 None => self.missing_pat(),
3170 }
3171 }
3172
3173 fn collect_tuple_pat(
3174 &mut self,
3175 args: AstChildren<ast::Pat>,
3176 has_leading_comma: bool,
3177 binding_list: &mut BindingList,
3178 ) -> (Box<[PatId]>, Option<u32>) {
3179 let args: Vec<_> = args.map(|p| self.collect_pat_possibly_rest(p, binding_list)).collect();
3180 let ellipsis = args.iter().position(|p| p.is_right()).map(|it| it as u32);
3183
3184 let mut args: Vec<_> = args.into_iter().filter_map(Either::left).collect();
3186 if has_leading_comma {
3189 args.insert(0, self.missing_pat());
3190 }
3191
3192 (args.into_boxed_slice(), ellipsis)
3193 }
3194
3195 fn collect_pat_possibly_rest(
3198 &mut self,
3199 pat: ast::Pat,
3200 binding_list: &mut BindingList,
3201 ) -> Either<PatId, ()> {
3202 match &pat {
3203 ast::Pat::RestPat(_) => Either::Right(()),
3204 ast::Pat::MacroPat(mac) => match mac.macro_call() {
3205 Some(call) => {
3206 let macro_ptr = AstPtr::new(&call);
3207 let src = self.expander.in_file(AstPtr::new(&pat));
3208 let pat =
3209 self.collect_macro_call(call, macro_ptr, true, |this, expanded_pat| {
3210 if let Some(expanded_pat) = expanded_pat {
3211 this.collect_pat_possibly_rest(expanded_pat, binding_list)
3212 } else {
3213 Either::Left(this.missing_pat())
3214 }
3215 });
3216 if let Some(pat) = pat.left() {
3217 self.store.pat_map.insert(src, pat.into());
3218 }
3219 pat
3220 }
3221 None => {
3222 let ptr = AstPtr::new(&pat);
3223 Either::Left(self.alloc_pat(Pat::Missing, ptr))
3224 }
3225 },
3226 _ => Either::Left(self.collect_pat(pat, binding_list)),
3227 }
3228 }
3229
3230 fn collect_ty_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
3231 match pat {
3232 Some(pat) => self.collect_ty_pat(pat),
3233 None => self.missing_pat(),
3234 }
3235 }
3236
3237 fn collect_ty_pat(&mut self, pat: ast::Pat) -> PatId {
3238 let ptr = AstPtr::new(&pat);
3239 match pat {
3240 ast::Pat::NotNull(_) => self.alloc_pat(Pat::NotNull, ptr),
3241 ast::Pat::OrPat(pat) => {
3242 let pat = pat.pats().map(|pat| self.collect_ty_pat(pat)).collect();
3243 self.alloc_pat(Pat::Or(pat), ptr)
3244 }
3245 ast::Pat::RangePat(range_pat) => {
3246 let start = range_pat
3247 .start()
3248 .map(|pat| {
3249 self.with_fresh_binding_expr_root(|this| this.lower_ty_pat_range_side(pat))
3250 })
3251 .unwrap_or_else(|| self.lower_ty_pat_range_end(self.lang_items().RangeMin));
3252 let end = range_pat
3253 .end()
3254 .map(|pat| match range_pat.op_kind() {
3255 Some(ast::RangeOp::Inclusive) | None => self
3256 .with_fresh_binding_expr_root(|this| this.lower_ty_pat_range_side(pat)),
3257 Some(ast::RangeOp::Exclusive) => self.lower_excluded_range_end(pat),
3258 })
3259 .unwrap_or_else(|| self.lower_ty_pat_range_end(self.lang_items().RangeMax));
3260 self.alloc_pat(
3261 Pat::Range {
3262 start: Some(start),
3263 end: Some(end),
3264 range_type: ast::RangeOp::Inclusive,
3265 },
3266 ptr,
3267 )
3268 }
3269 ast::Pat::MacroPat(pat) => {
3270 self.collect_macro_pat_with(pat, |this, pat| this.collect_ty_pat(pat))
3271 }
3272 _ => {
3273 self.alloc_pat(Pat::Missing, ptr)
3275 }
3276 }
3277 }
3278
3279 fn lower_ty_pat_range_side(&mut self, pat: ast::Pat) -> ExprId {
3280 let ptr = AstPtr::new(&pat);
3281 match &pat {
3282 ast::Pat::LiteralPat(it) => {
3283 let Some((literal, _)) = pat_literal_to_hir(it) else { return self.missing_expr() };
3284 self.alloc_expr_from_pat(Expr::Literal(literal), ptr)
3285 }
3286 ast::Pat::PathPat(it) => {
3287 let path = it
3288 .path()
3289 .and_then(|path| self.lower_path(path, &mut Self::impl_trait_error_allocator));
3290 self.alloc_expr_from_pat(path.map(Expr::Path).unwrap_or(Expr::Missing), ptr)
3291 }
3292 ast::Pat::IdentPat(it) if it.is_simple_ident() => {
3293 let name = it.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
3294 self.alloc_expr_from_pat(Expr::Path(name.into()), ptr)
3295 }
3296 _ => self.missing_expr(), }
3298 }
3299
3300 fn lower_ty_pat_range_end(&mut self, lang_item: Option<ConstId>) -> ExprId {
3304 self.with_fresh_binding_expr_root(|this| {
3305 this.alloc_expr_desugared(
3306 this.lang_path(lang_item).map(Expr::Path).unwrap_or(Expr::Missing),
3307 )
3308 })
3309 }
3310
3311 fn lower_excluded_range_end(&mut self, pat: ast::Pat) -> ExprId {
3314 self.with_fresh_binding_expr_root(|this| {
3315 let excluded_end = this.lower_ty_pat_range_side(pat);
3316 let range_sub_path =
3317 this.lang_path(this.lang_items().RangeSub).map(Expr::Path).unwrap_or(Expr::Missing);
3318 let range_sub_path = this.alloc_expr_desugared(range_sub_path);
3319 this.alloc_expr_desugared(Expr::Call {
3320 callee: range_sub_path,
3321 args: Box::new([excluded_end]),
3322 })
3323 })
3324 }
3325
3326 fn check_cfg(&mut self, owner: &dyn ast::HasAttrs) -> bool {
3331 let enabled = self.expander.is_cfg_enabled(owner, self.cfg_options);
3332 match enabled {
3333 Ok(()) => true,
3334 Err(cfg) => {
3335 self.store.diagnostics.push(ExpressionStoreDiagnostics::InactiveCode {
3336 node: self.expander.in_file(SyntaxNodePtr::new(owner.syntax())),
3337 cfg,
3338 opts: self.cfg_options.clone(),
3339 });
3340 false
3341 }
3342 }
3343 }
3344
3345 fn check_cfg_pred(&self, pred: Option<ast::CfgPredicate>) -> bool {
3347 let expr = pred.map_or(cfg::CfgExpr::Invalid, cfg::CfgExpr::parse_from_ast);
3348 self.cfg_options.check(&expr) != Some(false)
3349 }
3350
3351 fn add_definition_to_binding(&mut self, binding_id: BindingId, pat_id: PatId) {
3352 self.store.binding_definitions.entry(binding_id).or_default().push(pat_id);
3353 }
3354
3355 fn collect_label(&mut self, ast_label: ast::Label) -> LabelId {
3358 let label = Label {
3359 name: ast_label
3360 .lifetime()
3361 .as_ref()
3362 .map_or_else(Name::missing, |lt| Name::new_lifetime(lt.text())),
3363 };
3364 self.alloc_label(label, AstPtr::new(&ast_label))
3365 }
3366
3367 fn resolve_label(
3368 &self,
3369 lifetime: Option<ast::Lifetime>,
3370 ) -> Result<Option<LabelId>, ExpressionStoreDiagnostics> {
3371 let Some(lifetime) = lifetime else { return Ok(None) };
3372 let mut hygiene_id =
3373 self.expander.hygiene_for_range(self.db, lifetime.syntax().text_range());
3374 let mut hygiene_info = if hygiene_id.is_root() {
3375 None
3376 } else {
3377 hygiene_id.syntax_context().outer_expn(self.db).map(|expansion| {
3378 let expansion = hir_expand::MacroCallId::from(expansion).loc(self.db);
3379 (hygiene_id.syntax_context().parent(self.db), expansion.def)
3380 })
3381 };
3382 let name = Name::new_lifetime(lifetime.text());
3383
3384 for (rib_idx, rib) in self.label_ribs.iter().enumerate().rev() {
3385 match &rib.kind {
3386 RibKind::Normal(label_name, id, label_hygiene)
3387 if *label_name == name && *label_hygiene == hygiene_id =>
3388 {
3389 return if self.is_label_valid_from_rib(rib_idx) {
3390 Ok(Some(*id))
3391 } else {
3392 Err(ExpressionStoreDiagnostics::UnreachableLabel {
3393 name,
3394 node: self.expander.in_file(AstPtr::new(&lifetime)),
3395 })
3396 };
3397 }
3398 RibKind::MacroDef(macro_id) => {
3399 if let Some((parent_ctx, label_macro_id)) = hygiene_info
3400 && label_macro_id == **macro_id
3401 {
3402 hygiene_id = HygieneId::new(parent_ctx.opaque_and_semiopaque(self.db));
3407 hygiene_info = parent_ctx.outer_expn(self.db).map(|expansion| {
3408 let expansion = hir_expand::MacroCallId::from(expansion).loc(self.db);
3409 (parent_ctx.parent(self.db), expansion.def)
3410 });
3411 }
3412 }
3413 _ => {}
3414 }
3415 }
3416
3417 Err(ExpressionStoreDiagnostics::UndeclaredLabel {
3418 name,
3419 node: self.expander.in_file(AstPtr::new(&lifetime)),
3420 })
3421 }
3422
3423 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
3424 !self.label_ribs[rib_index + 1..].iter().any(|rib| rib.kind.is_label_barrier())
3425 }
3426
3427 fn pop_label_rib(&mut self) {
3428 while let Some(LabelRib { kind: RibKind::MacroDef(_) }) = self.label_ribs.pop() {
3430 }
3432 }
3433
3434 fn with_label_rib<T>(&mut self, kind: RibKind, f: impl FnOnce(&mut Self) -> T) -> T {
3435 self.label_ribs.push(LabelRib::new(kind));
3436 let res = f(self);
3437 self.pop_label_rib();
3438 res
3439 }
3440
3441 fn with_labeled_rib<T>(
3442 &mut self,
3443 label: LabelId,
3444 hygiene: HygieneId,
3445 f: impl FnOnce(&mut Self) -> T,
3446 ) -> T {
3447 self.label_ribs.push(LabelRib::new(RibKind::Normal(
3448 self.store.labels[label].name.clone(),
3449 label,
3450 hygiene,
3451 )));
3452 let res = f(self);
3453 self.pop_label_rib();
3454 res
3455 }
3456
3457 fn with_opt_labeled_rib<T>(
3458 &mut self,
3459 label: Option<(HygieneId, LabelId)>,
3460 f: impl FnOnce(&mut Self) -> T,
3461 ) -> T {
3462 match label {
3463 None => f(self),
3464 Some((hygiene, label)) => self.with_labeled_rib(label, hygiene, f),
3465 }
3466 }
3467 fn expand_macros_to_string(&mut self, expr: ast::Expr) -> Option<(ast::String, bool)> {
3473 let m = match expr {
3474 ast::Expr::MacroExpr(m) => m,
3475 ast::Expr::Literal(l) => {
3476 return match l.kind() {
3477 ast::LiteralKind::String(s) => Some((s, true)),
3478 _ => None,
3479 };
3480 }
3481 _ => return None,
3482 };
3483 let e = m.macro_call()?;
3484 let macro_ptr = AstPtr::new(&e);
3485 let (exp, _) = self.collect_macro_call(e, macro_ptr, true, |this, expansion| {
3486 expansion.and_then(|it| this.expand_macros_to_string(it))
3487 })?;
3488 Some((exp, false))
3489 }
3490
3491 fn lang_path(&self, lang: Option<impl Into<LangItemTarget>>) -> Option<Path> {
3492 Some(Path::LangItem(lang?.into(), None))
3493 }
3494
3495 fn lang_path_expr(&self, lang: Option<impl Into<LangItemTarget>>) -> Expr {
3496 self.lang_path(lang).map_or(Expr::Missing, Expr::Path)
3497 }
3498
3499 fn ty_rel_lang_path(
3500 &self,
3501 lang: Option<impl Into<LangItemTarget>>,
3502 relative_name: Symbol,
3503 ) -> Option<Path> {
3504 Some(Path::LangItem(lang?.into(), Some(Name::new_symbol_root(relative_name))))
3505 }
3506
3507 fn ty_rel_lang_path_expr(
3508 &self,
3509 lang: Option<impl Into<LangItemTarget>>,
3510 relative_name: Symbol,
3511 ) -> Expr {
3512 self.ty_rel_lang_path(lang, relative_name).map_or(Expr::Missing, Expr::Path)
3513 }
3514}
3515
3516fn pat_literal_to_hir(lit: &ast::LiteralPat) -> Option<(Literal, ast::Literal)> {
3517 let ast_lit = lit.literal()?;
3518 let mut hir_lit: Literal = ast_lit.kind().into();
3519 if lit.minus_token().is_some() {
3520 hir_lit = hir_lit.negate()?;
3521 }
3522 Some((hir_lit, ast_lit))
3523}
3524
3525impl<'db> ExprCollector<'db> {
3526 fn features(&self) -> &'db UnstableFeatures {
3527 self.def_map.features()
3528 }
3529
3530 fn with_fresh_binding_expr_root(&mut self, f: impl FnOnce(&mut Self) -> ExprId) -> ExprId {
3531 self.with_expr_root(|this| this.with_binding_owner(f))
3532 }
3533
3534 fn with_expr_root(&mut self, f: impl FnOnce(&mut Self) -> ExprId) -> ExprId {
3535 let inference_roots = self.store.inference_roots.take();
3536 let root = f(self);
3537 self.store.inference_roots = inference_roots;
3538
3539 if let Some(inference_roots) = &mut self.store.inference_roots {
3540 inference_roots.push(ExprRoot {
3541 root,
3542 exprs_end: end(&self.store.exprs),
3543 pats_end: end(&self.store.pats),
3544 bindings_end: end(&self.store.bindings),
3545 });
3546 }
3547
3548 return root;
3549
3550 fn end<T>(arena: &la_arena::Arena<T>) -> la_arena::Idx<T> {
3551 la_arena::Idx::from_raw(la_arena::RawIdx::from_u32(arena.len() as u32))
3552 }
3553 }
3554
3555 fn alloc_expr(&mut self, expr: Expr, ptr: ExprPtr) -> ExprId {
3556 let src = self.expander.in_file(ptr);
3557 let id = self.store.exprs.alloc(expr);
3558 self.store.expr_map_back.insert(id, src.map(AstPtr::wrap_left));
3559 self.store.expr_map.insert(src, id.into());
3560 id
3561 }
3562 fn alloc_expr_desugared(&mut self, expr: Expr) -> ExprId {
3565 self.store.exprs.alloc(expr)
3566 }
3567 fn alloc_expr_desugared_with_ptr(&mut self, expr: Expr, ptr: ExprPtr) -> ExprId {
3568 let src = self.expander.in_file(ptr);
3569 let id = self.store.exprs.alloc(expr);
3570 self.store.expr_map_back.insert(id, src.map(AstPtr::wrap_left));
3571 id
3574 }
3575 fn missing_expr(&mut self) -> ExprId {
3576 self.alloc_expr_desugared(Expr::Missing)
3577 }
3578
3579 fn alloc_binding(
3580 &mut self,
3581 name: Name,
3582 mode: BindingAnnotation,
3583 hygiene: HygieneId,
3584 ) -> BindingId {
3585 let binding = self.store.bindings.alloc(Binding { name, mode, problems: None, hygiene });
3586 self.unowned_bindings.push(binding);
3587 binding
3588 }
3589
3590 fn alloc_pat_from_expr(&mut self, pat: Pat, ptr: ExprPtr) -> PatId {
3591 let src = self.expander.in_file(ptr);
3592 let id = self.store.pats.alloc(pat);
3593 self.store.expr_map.insert(src, id.into());
3594 self.store.pat_map_back.insert(id, src.map(AstPtr::wrap_left));
3595 id
3596 }
3597
3598 fn alloc_expr_from_pat(&mut self, expr: Expr, ptr: PatPtr) -> ExprId {
3599 let src = self.expander.in_file(ptr);
3600 let id = self.store.exprs.alloc(expr);
3601 self.store.pat_map.insert(src, id.into());
3602 self.store.expr_map_back.insert(id, src.map(AstPtr::wrap_right));
3603 id
3604 }
3605
3606 fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId {
3607 let src = self.expander.in_file(ptr);
3608 let id = self.store.pats.alloc(pat);
3609 self.store.pat_map_back.insert(id, src.map(AstPtr::wrap_right));
3610 self.store.pat_map.insert(src, id.into());
3611 id
3612 }
3613 fn alloc_pat_desugared(&mut self, pat: Pat) -> PatId {
3615 self.store.pats.alloc(pat)
3616 }
3617 fn missing_pat(&mut self) -> PatId {
3618 self.store.pats.alloc(Pat::Missing)
3619 }
3620
3621 fn alloc_label(&mut self, label: Label, ptr: AstPtr<ast::Label>) -> LabelId {
3622 self.alloc_label_desugared(label, ptr.wrap_left())
3623 }
3624
3625 fn alloc_label_desugared(&mut self, label: Label, ptr: LabelPtr) -> LabelId {
3626 let src = self.expander.in_file(ptr);
3627 let id = self.store.labels.alloc(label);
3628 self.store.label_map_back.insert(id, src);
3629 self.store.label_map.insert(src, id);
3630 id
3631 }
3632
3633 fn is_lowering_awaitable_block(&self) -> &Awaitable {
3634 self.awaitable_context.as_ref().unwrap_or(&Awaitable::No("unknown"))
3635 }
3636
3637 fn with_awaitable_block<T>(
3638 &mut self,
3639 awaitable: Awaitable,
3640 f: impl FnOnce(&mut Self) -> T,
3641 ) -> T {
3642 let orig = self.awaitable_context.replace(awaitable);
3643 let res = f(self);
3644 self.awaitable_context = orig;
3645 res
3646 }
3647
3648 fn hygiene_id_for(&self, range: TextRange) -> HygieneId {
3649 self.expander.hygiene_for_range(self.db, range)
3650 }
3651
3652 fn with_lifetime_bound_scope<T>(
3653 &mut self,
3654 bound_scope: LifetimeBoundScope,
3655 f: impl FnOnce(&mut Self) -> T,
3656 ) -> T {
3657 let old = self.named_lifetime_store.lifetime_bound_scope.replace(bound_scope);
3658 let res = f(self);
3659 self.named_lifetime_store.lifetime_bound_scope = old;
3660 res
3661 }
3662
3663 fn for_path_type_projection<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
3664 if self.is_argument_lt_bound_scope() {
3665 let old = self.named_lifetime_store.lifetime_bound_scope.take();
3666 let res = f(self);
3667 self.named_lifetime_store.lifetime_bound_scope = old;
3668 res
3669 } else {
3670 f(self)
3671 }
3672 }
3673
3674 fn push_named_target_lifetime(&mut self, id: LifetimeRefId) {
3675 if let LifetimeRef::Named(name) = &self.store.lifetimes[id] {
3676 self.named_lifetime_store.push_named_lifetime(name.clone());
3677 }
3678 }
3679
3680 fn is_argument_lt_bound_scope(&mut self) -> bool {
3681 matches!(self.named_lifetime_store.lifetime_bound_scope, Some(LifetimeBoundScope::Argument))
3682 }
3683
3684 fn get_constrained_lifetimes_if_type_alias<'a>(
3685 &mut self,
3686 mod_path: &'a ModPath,
3687 generic_args: Option<&'a GenericArgs>,
3688 ) -> Option<impl Iterator<Item = LifetimeRefId> + use<'a, 'db>> {
3689 let generic_args = generic_args?;
3690 let r_path = self.def_map.resolve_path(
3691 self.local_def_map,
3692 self.db,
3693 self.module,
3694 mod_path,
3695 BuiltinShadowMode::Module,
3696 None,
3697 );
3698 let ModuleDefId::TypeAliasId(id) = r_path.0.take_types()? else { return None };
3699
3700 let constrained_lt_indices = get_constrained_lifetimes(self.db, id);
3701 let res = constrained_lt_indices.iter().filter_map(|&idx| {
3702 generic_args
3703 .args
3704 .iter()
3705 .filter_map(|arg| match arg {
3706 &GenericArg::Lifetime(lt_ref) => Some(lt_ref),
3707 GenericArg::Type(_) | GenericArg::Const(_) => None,
3708 })
3709 .nth(idx as usize)
3710 });
3711 return Some(res);
3712
3713 #[salsa::tracked(returns(deref), cycle_result = get_constrained_lifetimes_cycle_result)]
3714 fn get_constrained_lifetimes(
3715 db: &dyn SourceDatabase,
3716 type_alias_id: TypeAliasId,
3717 ) -> Box<[u32]> {
3718 let TypeAliasSignature { generic_params, store, ty, .. } =
3719 TypeAliasSignature::of(db, type_alias_id);
3720 let &Some(ty) = ty else { return Default::default() };
3721
3722 let mut visitor = Visitor {
3723 store,
3724 generic_params,
3725 parent: type_alias_id,
3726 constrained_lt_indices: Vec::new(),
3727 };
3728 store.visit_type_ref_children(ty, &mut visitor);
3729
3730 return visitor.constrained_lt_indices.into_boxed_slice();
3731
3732 struct Visitor<'a> {
3733 store: &'a ExpressionStore,
3734 generic_params: &'a GenericParams,
3735 parent: TypeAliasId,
3736 constrained_lt_indices: Vec<u32>,
3737 }
3738
3739 impl StoreVisitor for Visitor<'_> {
3740 fn on_lifetime(&mut self, lifetime: LifetimeRefId) {
3741 if let LifetimeRef::Named(lifetime_name) = &self.store[lifetime]
3742 && let Some(param_id) = self
3743 .generic_params
3744 .find_lifetime_by_name(lifetime_name, self.parent.into())
3745 {
3746 self.constrained_lt_indices.push(param_id.local_id.into_raw().into_u32());
3747 }
3748 }
3749
3750 fn on_generic_args(&mut self, args: &GenericArgs) {
3751 if !args.has_self_type {
3752 crate::expr_store::visit_generic_args(self, args);
3753 }
3754 }
3755 }
3756 }
3757
3758 fn get_constrained_lifetimes_cycle_result(
3759 _db: &dyn SourceDatabase,
3760 _: salsa::Id,
3761 _id: TypeAliasId,
3762 ) -> Box<[u32]> {
3763 Default::default()
3764 }
3765 }
3766}
3767
3768fn comma_follows_token(t: Option<syntax::SyntaxToken>) -> bool {
3769 (|| syntax::algo::skip_trivia_token(t?.next_token()?, syntax::Direction::Next))()
3770 .is_some_and(|it| it.kind() == syntax::T![,])
3771}
3772
3773pub fn hir_assoc_type_binding_to_ast(
3775 segment_args: &ast::GenericArgList,
3776 binding_idx: u32,
3777) -> Option<ast::AssocTypeArg> {
3778 segment_args
3779 .generic_args()
3780 .filter_map(|arg| match arg {
3781 ast::GenericArg::AssocTypeArg(it) => Some(it),
3782 _ => None,
3783 })
3784 .filter(|binding| binding.param_list().is_none() && binding.name_ref().is_some())
3785 .nth(binding_idx as usize)
3786}
3787
3788pub fn hir_generic_arg_to_ast(
3790 args: &ast::GenericArgList,
3791 arg_idx: u32,
3792 has_self_arg: bool,
3793) -> Option<ast::GenericArg> {
3794 args.generic_args()
3795 .filter(|arg| match arg {
3796 ast::GenericArg::AssocTypeArg(_) => false,
3797 ast::GenericArg::LifetimeArg(arg) => arg.lifetime().is_some(),
3798 ast::GenericArg::ConstArg(_) | ast::GenericArg::TypeArg(_) => true,
3799 })
3800 .nth(arg_idx as usize - has_self_arg as usize)
3801}