1 //! Transforms `ast::Expr` into an equivalent `hir_def::expr::Expr`
4 use std::{mem, sync::Arc};
10 name::{name, AsName, Name},
11 AstId, ExpandError, HirFileId, InFile,
14 use once_cell::unsync::OnceCell;
16 use rustc_hash::FxHashMap;
19 self, ArrayExprKind, AstChildren, HasArgList, HasLoopBody, HasName, LiteralKind,
22 AstNode, AstPtr, SyntaxNodePtr,
27 body::{Body, BodySourceMap, Expander, ExprPtr, LabelPtr, LabelSource, PatPtr},
28 body::{BodyDiagnostic, ExprSource, PatSource},
29 builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint},
32 dummy_expr_id, Array, BindingAnnotation, Expr, ExprId, FloatTypeWrapper, Label, LabelId,
33 Literal, MatchArm, Pat, PatId, RecordFieldPat, RecordLitField, Statement,
36 item_scope::BuiltinShadowMode,
37 path::{GenericArgs, Path},
38 type_ref::{Mutability, Rawness, TypeRef},
39 AdtId, BlockLoc, ModuleDefId, UnresolvedMacro,
42 pub struct LowerCtx<'a> {
43 pub db: &'a dyn DefDatabase,
45 ast_id_map: Option<(HirFileId, OnceCell<Arc<AstIdMap>>)>,
48 impl<'a> LowerCtx<'a> {
49 pub fn new(db: &'a dyn DefDatabase, file_id: HirFileId) -> Self {
52 hygiene: Hygiene::new(db.upcast(), file_id),
53 ast_id_map: Some((file_id, OnceCell::new())),
57 pub fn with_hygiene(db: &'a dyn DefDatabase, hygiene: &Hygiene) -> Self {
58 LowerCtx { db, hygiene: hygiene.clone(), ast_id_map: None }
61 pub(crate) fn hygiene(&self) -> &Hygiene {
65 pub(crate) fn lower_path(&self, ast: ast::Path) -> Option<Path> {
66 Path::from_src(ast, self)
69 pub(crate) fn ast_id<N: AstNode>(&self, db: &dyn DefDatabase, item: &N) -> Option<AstId<N>> {
70 let &(file_id, ref ast_id_map) = self.ast_id_map.as_ref()?;
71 let ast_id_map = ast_id_map.get_or_init(|| db.ast_id_map(file_id));
72 Some(InFile::new(file_id, ast_id_map.ast_id(item)))
79 params: Option<ast::ParamList>,
80 body: Option<ast::Expr>,
81 ) -> (Body, BodySourceMap) {
84 source_map: BodySourceMap::default(),
85 ast_id_map: db.ast_id_map(expander.current_file_id),
87 exprs: Arena::default(),
88 pats: Arena::default(),
89 labels: Arena::default(),
91 body_expr: dummy_expr_id(),
92 block_scopes: Vec::new(),
94 or_pats: Default::default(),
97 name_to_pat_grouping: Default::default(),
98 is_lowering_inside_or_pat: false,
99 is_lowering_assignee_expr: false,
101 .collect(params, body)
104 struct ExprCollector<'a> {
105 db: &'a dyn DefDatabase,
107 ast_id_map: Arc<AstIdMap>,
109 source_map: BodySourceMap,
110 // a poor-mans union-find?
111 name_to_pat_grouping: FxHashMap<Name, Vec<PatId>>,
112 is_lowering_inside_or_pat: bool,
113 is_lowering_assignee_expr: bool,
116 impl ExprCollector<'_> {
119 param_list: Option<ast::ParamList>,
120 body: Option<ast::Expr>,
121 ) -> (Body, BodySourceMap) {
122 if let Some(param_list) = param_list {
123 if let Some(self_param) = param_list.self_param() {
124 let ptr = AstPtr::new(&self_param);
125 let param_pat = self.alloc_pat(
128 mode: BindingAnnotation::new(
129 self_param.mut_token().is_some() && self_param.amp_token().is_none(),
136 self.body.params.push(param_pat);
139 for pat in param_list.params().filter_map(|param| param.pat()) {
140 let param_pat = self.collect_pat(pat);
141 self.body.params.push(param_pat);
145 self.body.body_expr = self.collect_expr_opt(body);
146 (self.body, self.source_map)
149 fn ctx(&self) -> LowerCtx<'_> {
150 LowerCtx::new(self.db, self.expander.current_file_id)
153 fn alloc_expr(&mut self, expr: Expr, ptr: ExprPtr) -> ExprId {
154 let src = self.expander.to_source(ptr);
155 let id = self.make_expr(expr, src.clone());
156 self.source_map.expr_map.insert(src, id);
159 // desugared exprs don't have ptr, that's wrong and should be fixed
161 fn alloc_expr_desugared(&mut self, expr: Expr) -> ExprId {
162 self.body.exprs.alloc(expr)
164 fn missing_expr(&mut self) -> ExprId {
165 self.alloc_expr_desugared(Expr::Missing)
167 fn make_expr(&mut self, expr: Expr, src: ExprSource) -> ExprId {
168 let id = self.body.exprs.alloc(expr);
169 self.source_map.expr_map_back.insert(id, src);
173 fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId {
174 let src = self.expander.to_source(ptr);
175 let id = self.make_pat(pat, src.clone());
176 self.source_map.pat_map.insert(src, id);
179 fn missing_pat(&mut self) -> PatId {
180 self.body.pats.alloc(Pat::Missing)
182 fn make_pat(&mut self, pat: Pat, src: PatSource) -> PatId {
183 let id = self.body.pats.alloc(pat);
184 self.source_map.pat_map_back.insert(id, src);
188 fn alloc_label(&mut self, label: Label, ptr: LabelPtr) -> LabelId {
189 let src = self.expander.to_source(ptr);
190 let id = self.make_label(label, src.clone());
191 self.source_map.label_map.insert(src, id);
194 fn make_label(&mut self, label: Label, src: LabelSource) -> LabelId {
195 let id = self.body.labels.alloc(label);
196 self.source_map.label_map_back.insert(id, src);
200 fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
201 self.maybe_collect_expr(expr).unwrap_or_else(|| self.missing_expr())
204 /// Returns `None` if and only if the expression is `#[cfg]`d out.
205 fn maybe_collect_expr(&mut self, expr: ast::Expr) -> Option<ExprId> {
206 let syntax_ptr = AstPtr::new(&expr);
207 self.check_cfg(&expr)?;
210 ast::Expr::IfExpr(e) => {
211 let then_branch = self.collect_block_opt(e.then_branch());
213 let else_branch = e.else_branch().map(|b| match b {
214 ast::ElseBranch::Block(it) => self.collect_block(it),
215 ast::ElseBranch::IfExpr(elif) => {
216 let expr: ast::Expr = ast::Expr::cast(elif.syntax().clone()).unwrap();
217 self.collect_expr(expr)
221 let condition = self.collect_expr_opt(e.condition());
223 self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
225 ast::Expr::LetExpr(e) => {
226 let pat = self.collect_pat_opt(e.pat());
227 let expr = self.collect_expr_opt(e.expr());
228 self.alloc_expr(Expr::Let { pat, expr }, syntax_ptr)
230 ast::Expr::BlockExpr(e) => match e.modifier() {
231 Some(ast::BlockModifier::Try(_)) => {
232 let body = self.collect_block(e);
233 self.alloc_expr(Expr::TryBlock { body }, syntax_ptr)
235 Some(ast::BlockModifier::Unsafe(_)) => {
236 let body = self.collect_block(e);
237 self.alloc_expr(Expr::Unsafe { body }, syntax_ptr)
239 // FIXME: we need to record these effects somewhere...
240 Some(ast::BlockModifier::Label(label)) => {
241 let label = self.collect_label(label);
242 let res = self.collect_block(e);
243 match &mut self.body.exprs[res] {
244 Expr::Block { label: block_label, .. } => {
245 *block_label = Some(label);
251 Some(ast::BlockModifier::Async(_)) => {
252 let body = self.collect_block(e);
253 self.alloc_expr(Expr::Async { body }, syntax_ptr)
255 Some(ast::BlockModifier::Const(_)) => {
256 let body = self.collect_block(e);
257 self.alloc_expr(Expr::Const { body }, syntax_ptr)
259 None => self.collect_block(e),
261 ast::Expr::LoopExpr(e) => {
262 let label = e.label().map(|label| self.collect_label(label));
263 let body = self.collect_block_opt(e.loop_body());
264 self.alloc_expr(Expr::Loop { body, label }, syntax_ptr)
266 ast::Expr::WhileExpr(e) => {
267 let label = e.label().map(|label| self.collect_label(label));
268 let body = self.collect_block_opt(e.loop_body());
270 let condition = self.collect_expr_opt(e.condition());
272 self.alloc_expr(Expr::While { condition, body, label }, syntax_ptr)
274 ast::Expr::ForExpr(e) => {
275 let label = e.label().map(|label| self.collect_label(label));
276 let iterable = self.collect_expr_opt(e.iterable());
277 let pat = self.collect_pat_opt(e.pat());
278 let body = self.collect_block_opt(e.loop_body());
279 self.alloc_expr(Expr::For { iterable, pat, body, label }, syntax_ptr)
281 ast::Expr::CallExpr(e) => {
282 let callee = self.collect_expr_opt(e.expr());
283 let args = if let Some(arg_list) = e.arg_list() {
284 arg_list.args().filter_map(|e| self.maybe_collect_expr(e)).collect()
289 Expr::Call { callee, args, is_assignee_expr: self.is_lowering_assignee_expr },
293 ast::Expr::MethodCallExpr(e) => {
294 let receiver = self.collect_expr_opt(e.receiver());
295 let args = if let Some(arg_list) = e.arg_list() {
296 arg_list.args().filter_map(|e| self.maybe_collect_expr(e)).collect()
300 let method_name = e.name_ref().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
303 .and_then(|it| GenericArgs::from_ast(&self.ctx(), it))
306 Expr::MethodCall { receiver, method_name, args, generic_args },
310 ast::Expr::MatchExpr(e) => {
311 let expr = self.collect_expr_opt(e.expr());
312 let arms = if let Some(match_arm_list) = e.match_arm_list() {
316 self.check_cfg(&arm).map(|()| MatchArm {
317 pat: self.collect_pat_opt(arm.pat()),
318 expr: self.collect_expr_opt(arm.expr()),
321 .map(|guard| self.collect_expr_opt(guard.condition())),
328 self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
330 ast::Expr::PathExpr(e) => {
333 .and_then(|path| self.expander.parse_path(self.db, path))
335 .unwrap_or(Expr::Missing);
336 self.alloc_expr(path, syntax_ptr)
338 ast::Expr::ContinueExpr(e) => self.alloc_expr(
339 Expr::Continue { label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
342 ast::Expr::BreakExpr(e) => {
343 let expr = e.expr().map(|e| self.collect_expr(e));
345 Expr::Break { expr, label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
349 ast::Expr::ParenExpr(e) => {
350 let inner = self.collect_expr_opt(e.expr());
351 // make the paren expr point to the inner expression as well
352 let src = self.expander.to_source(syntax_ptr);
353 self.source_map.expr_map.insert(src, inner);
356 ast::Expr::ReturnExpr(e) => {
357 let expr = e.expr().map(|e| self.collect_expr(e));
358 self.alloc_expr(Expr::Return { expr }, syntax_ptr)
360 ast::Expr::YieldExpr(e) => {
361 let expr = e.expr().map(|e| self.collect_expr(e));
362 self.alloc_expr(Expr::Yield { expr }, syntax_ptr)
364 ast::Expr::RecordExpr(e) => {
366 e.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
367 let is_assignee_expr = self.is_lowering_assignee_expr;
368 let record_lit = if let Some(nfl) = e.record_expr_field_list() {
371 .filter_map(|field| {
372 self.check_cfg(&field)?;
374 let name = field.field_name()?.as_name();
376 let expr = match field.expr() {
377 Some(e) => self.collect_expr(e),
378 None => self.missing_expr(),
380 let src = self.expander.to_source(AstPtr::new(&field));
381 self.source_map.field_map.insert(src.clone(), expr);
382 self.source_map.field_map_back.insert(expr, src);
383 Some(RecordLitField { name, expr })
386 let spread = nfl.spread().map(|s| self.collect_expr(s));
387 let ellipsis = nfl.dotdot_token().is_some();
388 Expr::RecordLit { path, fields, spread, ellipsis, is_assignee_expr }
392 fields: Box::default(),
399 self.alloc_expr(record_lit, syntax_ptr)
401 ast::Expr::FieldExpr(e) => {
402 let expr = self.collect_expr_opt(e.expr());
403 let name = match e.field_access() {
404 Some(kind) => kind.as_name(),
405 _ => Name::missing(),
407 self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
409 ast::Expr::AwaitExpr(e) => {
410 let expr = self.collect_expr_opt(e.expr());
411 self.alloc_expr(Expr::Await { expr }, syntax_ptr)
413 ast::Expr::TryExpr(e) => {
414 let expr = self.collect_expr_opt(e.expr());
415 self.alloc_expr(Expr::Try { expr }, syntax_ptr)
417 ast::Expr::CastExpr(e) => {
418 let expr = self.collect_expr_opt(e.expr());
419 let type_ref = Interned::new(TypeRef::from_ast_opt(&self.ctx(), e.ty()));
420 self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
422 ast::Expr::RefExpr(e) => {
423 let expr = self.collect_expr_opt(e.expr());
424 let raw_tok = e.raw_token().is_some();
425 let mutability = if raw_tok {
426 if e.mut_token().is_some() {
428 } else if e.const_token().is_some() {
431 unreachable!("parser only remaps to raw_token() if matching mutability token follows")
434 Mutability::from_mutable(e.mut_token().is_some())
436 let rawness = Rawness::from_raw(raw_tok);
437 self.alloc_expr(Expr::Ref { expr, rawness, mutability }, syntax_ptr)
439 ast::Expr::PrefixExpr(e) => {
440 let expr = self.collect_expr_opt(e.expr());
442 Some(op) => self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr),
443 None => self.alloc_expr(Expr::Missing, syntax_ptr),
446 ast::Expr::ClosureExpr(e) => {
447 let mut args = Vec::new();
448 let mut arg_types = Vec::new();
449 if let Some(pl) = e.param_list() {
450 for param in pl.params() {
451 let pat = self.collect_pat_opt(param.pat());
453 param.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
455 arg_types.push(type_ref);
460 .and_then(|r| r.ty())
461 .map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
462 let body = self.collect_expr_opt(e.body());
466 arg_types: arg_types.into(),
473 ast::Expr::BinExpr(e) => {
474 let op = e.op_kind();
475 if let Some(ast::BinaryOp::Assignment { op: None }) = op {
476 self.is_lowering_assignee_expr = true;
478 let lhs = self.collect_expr_opt(e.lhs());
479 self.is_lowering_assignee_expr = false;
480 let rhs = self.collect_expr_opt(e.rhs());
481 self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr)
483 ast::Expr::TupleExpr(e) => {
484 let exprs = e.fields().map(|expr| self.collect_expr(expr)).collect();
486 Expr::Tuple { exprs, is_assignee_expr: self.is_lowering_assignee_expr },
490 ast::Expr::BoxExpr(e) => {
491 let expr = self.collect_expr_opt(e.expr());
492 self.alloc_expr(Expr::Box { expr }, syntax_ptr)
495 ast::Expr::ArrayExpr(e) => {
499 ArrayExprKind::ElementList(e) => {
500 let elements = e.map(|expr| self.collect_expr(expr)).collect();
502 Expr::Array(Array::ElementList {
504 is_assignee_expr: self.is_lowering_assignee_expr,
509 ArrayExprKind::Repeat { initializer, repeat } => {
510 let initializer = self.collect_expr_opt(initializer);
511 let repeat = self.collect_expr_opt(repeat);
513 Expr::Array(Array::Repeat { initializer, repeat }),
520 ast::Expr::Literal(e) => self.alloc_expr(Expr::Literal(e.kind().into()), syntax_ptr),
521 ast::Expr::IndexExpr(e) => {
522 let base = self.collect_expr_opt(e.base());
523 let index = self.collect_expr_opt(e.index());
524 self.alloc_expr(Expr::Index { base, index }, syntax_ptr)
526 ast::Expr::RangeExpr(e) => {
527 let lhs = e.start().map(|lhs| self.collect_expr(lhs));
528 let rhs = e.end().map(|rhs| self.collect_expr(rhs));
530 Some(range_type) => {
531 self.alloc_expr(Expr::Range { lhs, rhs, range_type }, syntax_ptr)
533 None => self.alloc_expr(Expr::Missing, syntax_ptr),
536 ast::Expr::MacroExpr(e) => {
537 let e = e.macro_call()?;
538 let macro_ptr = AstPtr::new(&e);
539 let id = self.collect_macro_call(e, macro_ptr, true, |this, expansion| {
540 expansion.map(|it| this.collect_expr(it))
544 // Make the macro-call point to its expanded expression so we can query
545 // semantics on syntax pointers to the macro
546 let src = self.expander.to_source(syntax_ptr);
547 self.source_map.expr_map.insert(src, id);
550 None => self.alloc_expr(Expr::Missing, syntax_ptr),
553 ast::Expr::UnderscoreExpr(_) => self.alloc_expr(Expr::Underscore, syntax_ptr),
557 fn collect_macro_call<F, T, U>(
559 mcall: ast::MacroCall,
560 syntax_ptr: AstPtr<ast::MacroCall>,
561 record_diagnostics: bool,
565 F: FnOnce(&mut Self, Option<T>) -> U,
568 // File containing the macro call. Expansion errors will be attached here.
569 let outer_file = self.expander.current_file_id;
571 let macro_call_ptr = self.expander.to_source(AstPtr::new(&mcall));
572 let res = self.expander.enter_expand(self.db, mcall);
574 let res = match res {
576 Err(UnresolvedMacro { path }) => {
577 if record_diagnostics {
578 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall {
579 node: InFile::new(outer_file, syntax_ptr),
583 return collector(self, None);
587 if record_diagnostics {
589 Some(ExpandError::UnresolvedProcMacro(krate)) => {
590 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedProcMacro {
591 node: InFile::new(outer_file, syntax_ptr),
596 self.source_map.diagnostics.push(BodyDiagnostic::MacroError {
597 node: InFile::new(outer_file, syntax_ptr),
598 message: err.to_string(),
606 Some((mark, expansion)) => {
607 self.source_map.expansions.insert(macro_call_ptr, self.expander.current_file_id);
608 let prev_ast_id_map = mem::replace(
609 &mut self.ast_id_map,
610 self.db.ast_id_map(self.expander.current_file_id),
613 let id = collector(self, Some(expansion));
614 self.ast_id_map = prev_ast_id_map;
615 self.expander.exit(self.db, mark);
618 None => collector(self, None),
622 fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
624 Some(expr) => self.collect_expr(expr),
625 None => self.missing_expr(),
629 fn collect_macro_as_stmt(
631 statements: &mut Vec<Statement>,
633 ) -> Option<ExprId> {
634 let mac_call = mac.macro_call()?;
635 let syntax_ptr = AstPtr::new(&ast::Expr::from(mac));
636 let macro_ptr = AstPtr::new(&mac_call);
637 let expansion = self.collect_macro_call(
641 |this, expansion: Option<ast::MacroStmts>| match expansion {
643 expansion.statements().for_each(|stmt| this.collect_stmt(statements, stmt));
644 expansion.expr().and_then(|expr| match expr {
645 ast::Expr::MacroExpr(mac) => this.collect_macro_as_stmt(statements, mac),
646 expr => Some(this.collect_expr(expr)),
654 // Make the macro-call point to its expanded expression so we can query
655 // semantics on syntax pointers to the macro
656 let src = self.expander.to_source(syntax_ptr);
657 self.source_map.expr_map.insert(src, tail);
664 fn collect_stmt(&mut self, statements: &mut Vec<Statement>, s: ast::Stmt) {
666 ast::Stmt::LetStmt(stmt) => {
667 if self.check_cfg(&stmt).is_none() {
670 let pat = self.collect_pat_opt(stmt.pat());
672 stmt.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
673 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
674 let else_branch = stmt
676 .and_then(|let_else| let_else.block_expr())
677 .map(|block| self.collect_block(block));
678 statements.push(Statement::Let { pat, type_ref, initializer, else_branch });
680 ast::Stmt::ExprStmt(stmt) => {
681 let expr = stmt.expr();
683 Some(expr) if self.check_cfg(expr).is_none() => return,
686 let has_semi = stmt.semicolon_token().is_some();
687 // Note that macro could be expanded to multiple statements
688 if let Some(ast::Expr::MacroExpr(mac)) = expr {
689 if let Some(expr) = self.collect_macro_as_stmt(statements, mac) {
690 statements.push(Statement::Expr { expr, has_semi })
693 let expr = self.collect_expr_opt(expr);
694 statements.push(Statement::Expr { expr, has_semi });
697 ast::Stmt::Item(_item) => (),
701 fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId {
702 let file_local_id = self.ast_id_map.ast_id(&block);
703 let ast_id = AstId::new(self.expander.current_file_id, file_local_id);
705 BlockLoc { ast_id, module: self.expander.def_map.module_id(self.expander.module) };
706 let block_id = self.db.intern_block(block_loc);
708 let (module, def_map) = match self.db.block_def_map(block_id) {
710 self.body.block_scopes.push(block_id);
711 (def_map.root(), def_map)
713 None => (self.expander.module, self.expander.def_map.clone()),
715 let prev_def_map = mem::replace(&mut self.expander.def_map, def_map);
716 let prev_local_module = mem::replace(&mut self.expander.module, module);
718 let mut statements = Vec::new();
719 block.statements().for_each(|s| self.collect_stmt(&mut statements, s));
720 let tail = block.tail_expr().and_then(|e| match e {
721 ast::Expr::MacroExpr(mac) => self.collect_macro_as_stmt(&mut statements, mac),
722 expr => self.maybe_collect_expr(expr),
724 let tail = tail.or_else(|| {
725 let stmt = statements.pop()?;
726 if let Statement::Expr { expr, has_semi: false } = stmt {
729 statements.push(stmt);
733 let syntax_node_ptr = AstPtr::new(&block.into());
734 let expr_id = self.alloc_expr(
737 statements: statements.into_boxed_slice(),
744 self.expander.def_map = prev_def_map;
745 self.expander.module = prev_local_module;
749 fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
751 Some(block) => self.collect_block(block),
752 None => self.missing_expr(),
756 fn collect_label(&mut self, ast_label: ast::Label) -> LabelId {
758 name: ast_label.lifetime().as_ref().map_or_else(Name::missing, Name::new_lifetime),
760 self.alloc_label(label, AstPtr::new(&ast_label))
763 fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
764 let pat_id = self.collect_pat_(pat);
765 for (_, pats) in self.name_to_pat_grouping.drain() {
766 let pats = Arc::<[_]>::from(pats);
767 self.body.or_pats.extend(pats.iter().map(|&pat| (pat, pats.clone())));
769 self.is_lowering_inside_or_pat = false;
773 fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
775 Some(pat) => self.collect_pat(pat),
776 None => self.missing_pat(),
780 fn collect_pat_(&mut self, pat: ast::Pat) -> PatId {
781 let pattern = match &pat {
782 ast::Pat::IdentPat(bp) => {
783 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
785 let key = self.is_lowering_inside_or_pat.then(|| name.clone());
787 BindingAnnotation::new(bp.mut_token().is_some(), bp.ref_token().is_some());
788 let subpat = bp.pat().map(|subpat| self.collect_pat_(subpat));
789 let pattern = if annotation == BindingAnnotation::Unannotated && subpat.is_none() {
790 // This could also be a single-segment path pattern. To
791 // decide that, we need to try resolving the name.
792 let (resolved, _) = self.expander.def_map.resolve_path(
794 self.expander.module,
795 &name.clone().into(),
796 BuiltinShadowMode::Other,
798 match resolved.take_values() {
799 Some(ModuleDefId::ConstId(_)) => Pat::Path(name.into()),
800 Some(ModuleDefId::EnumVariantId(_)) => {
801 // this is only really valid for unit variants, but
802 // shadowing other enum variants with a pattern is
804 Pat::Path(name.into())
806 Some(ModuleDefId::AdtId(AdtId::StructId(s)))
807 if self.db.struct_data(s).variant_data.kind() != StructKind::Record =>
809 // Funnily enough, record structs *can* be shadowed
810 // by pattern bindings (but unit or tuple structs
812 Pat::Path(name.into())
814 // shadowing statics is an error as well, so we just ignore that case here
815 _ => Pat::Bind { name, mode: annotation, subpat },
818 Pat::Bind { name, mode: annotation, subpat }
821 let ptr = AstPtr::new(&pat);
822 let pat = self.alloc_pat(pattern, Either::Left(ptr));
823 if let Some(key) = key {
824 self.name_to_pat_grouping.entry(key).or_default().push(pat);
828 ast::Pat::TupleStructPat(p) => {
830 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
831 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
832 Pat::TupleStruct { path, args, ellipsis }
834 ast::Pat::RefPat(p) => {
835 let pat = self.collect_pat_opt(p.pat());
836 let mutability = Mutability::from_mutable(p.mut_token().is_some());
837 Pat::Ref { pat, mutability }
839 ast::Pat::PathPat(p) => {
841 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
842 path.map(Pat::Path).unwrap_or(Pat::Missing)
844 ast::Pat::OrPat(p) => {
845 self.is_lowering_inside_or_pat = true;
846 let pats = p.pats().map(|p| self.collect_pat_(p)).collect();
849 ast::Pat::ParenPat(p) => return self.collect_pat_opt_(p.pat()),
850 ast::Pat::TuplePat(p) => {
851 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
852 Pat::Tuple { args, ellipsis }
854 ast::Pat::WildcardPat(_) => Pat::Wild,
855 ast::Pat::RecordPat(p) => {
857 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
859 .record_pat_field_list()
860 .expect("every struct should have a field list")
863 let ast_pat = f.pat()?;
864 let pat = self.collect_pat_(ast_pat);
865 let name = f.field_name()?.as_name();
866 Some(RecordFieldPat { name, pat })
871 .record_pat_field_list()
872 .expect("every struct should have a field list")
876 Pat::Record { path, args, ellipsis }
878 ast::Pat::SlicePat(p) => {
879 let SlicePatComponents { prefix, slice, suffix } = p.components();
881 // FIXME properly handle `RestPat`
883 prefix: prefix.into_iter().map(|p| self.collect_pat_(p)).collect(),
884 slice: slice.map(|p| self.collect_pat_(p)),
885 suffix: suffix.into_iter().map(|p| self.collect_pat_(p)).collect(),
888 ast::Pat::LiteralPat(lit) => {
889 if let Some(ast_lit) = lit.literal() {
890 let expr = Expr::Literal(ast_lit.kind().into());
891 let expr_ptr = AstPtr::new(&ast::Expr::Literal(ast_lit));
892 let expr_id = self.alloc_expr(expr, expr_ptr);
898 ast::Pat::RestPat(_) => {
899 // `RestPat` requires special handling and should not be mapped
900 // to a Pat. Here we are using `Pat::Missing` as a fallback for
901 // when `RestPat` is mapped to `Pat`, which can easily happen
902 // when the source code being analyzed has a malformed pattern
903 // which includes `..` in a place where it isn't valid.
907 ast::Pat::BoxPat(boxpat) => {
908 let inner = self.collect_pat_opt_(boxpat.pat());
911 ast::Pat::ConstBlockPat(const_block_pat) => {
912 if let Some(expr) = const_block_pat.block_expr() {
913 let expr_id = self.collect_block(expr);
914 Pat::ConstBlock(expr_id)
919 ast::Pat::MacroPat(mac) => match mac.macro_call() {
921 let macro_ptr = AstPtr::new(&call);
922 let src = self.expander.to_source(Either::Left(AstPtr::new(&pat)));
924 self.collect_macro_call(call, macro_ptr, true, |this, expanded_pat| {
925 this.collect_pat_opt_(expanded_pat)
927 self.source_map.pat_map.insert(src, pat);
930 None => Pat::Missing,
933 ast::Pat::RangePat(_) => Pat::Missing,
935 let ptr = AstPtr::new(&pat);
936 self.alloc_pat(pattern, Either::Left(ptr))
939 fn collect_pat_opt_(&mut self, pat: Option<ast::Pat>) -> PatId {
941 Some(pat) => self.collect_pat_(pat),
942 None => self.missing_pat(),
946 fn collect_tuple_pat(&mut self, args: AstChildren<ast::Pat>) -> (Box<[PatId]>, Option<usize>) {
947 // Find the location of the `..`, if there is one. Note that we do not
948 // consider the possibility of there being multiple `..` here.
949 let ellipsis = args.clone().position(|p| matches!(p, ast::Pat::RestPat(_)));
950 // We want to skip the `..` pattern here, since we account for it above.
952 .filter(|p| !matches!(p, ast::Pat::RestPat(_)))
953 .map(|p| self.collect_pat_(p))
959 /// Returns `None` (and emits diagnostics) when `owner` if `#[cfg]`d out, and `Some(())` when
961 fn check_cfg(&mut self, owner: &dyn ast::HasAttrs) -> Option<()> {
962 match self.expander.parse_attrs(self.db, owner).cfg() {
964 if self.expander.cfg_options().check(&cfg) != Some(false) {
968 self.source_map.diagnostics.push(BodyDiagnostic::InactiveCode {
970 self.expander.current_file_id,
971 SyntaxNodePtr::new(owner.syntax()),
974 opts: self.expander.cfg_options().clone(),
984 impl From<ast::LiteralKind> for Literal {
985 fn from(ast_lit_kind: ast::LiteralKind) -> Self {
987 // FIXME: these should have actual values filled in, but unsure on perf impact
988 LiteralKind::IntNumber(lit) => {
989 if let builtin @ Some(_) = lit.suffix().and_then(BuiltinFloat::from_suffix) {
991 FloatTypeWrapper::new(lit.float_value().unwrap_or(Default::default())),
994 } else if let builtin @ Some(_) = lit.suffix().and_then(BuiltinInt::from_suffix) {
995 Literal::Int(lit.value().unwrap_or(0) as i128, builtin)
997 let builtin = lit.suffix().and_then(BuiltinUint::from_suffix);
998 Literal::Uint(lit.value().unwrap_or(0), builtin)
1001 LiteralKind::FloatNumber(lit) => {
1002 let ty = lit.suffix().and_then(BuiltinFloat::from_suffix);
1003 Literal::Float(FloatTypeWrapper::new(lit.value().unwrap_or(Default::default())), ty)
1005 LiteralKind::ByteString(bs) => {
1006 let text = bs.value().map(Box::from).unwrap_or_else(Default::default);
1007 Literal::ByteString(text)
1009 LiteralKind::String(s) => {
1010 let text = s.value().map(Box::from).unwrap_or_else(Default::default);
1011 Literal::String(text)
1013 LiteralKind::Byte(b) => {
1014 Literal::Uint(b.value().unwrap_or_default() as u128, Some(BuiltinUint::U8))
1016 LiteralKind::Char(c) => Literal::Char(c.value().unwrap_or_default()),
1017 LiteralKind::Bool(val) => Literal::Bool(val),