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, LabelSource, PatPtr, SyntheticSyntax},
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: AstPtr<ast::Expr>) -> ExprId {
154 let src = self.expander.to_source(ptr);
155 let id = self.make_expr(expr, Ok(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.make_expr(expr, Err(SyntheticSyntax))
164 fn missing_expr(&mut self) -> ExprId {
165 self.alloc_expr_desugared(Expr::Missing)
167 fn make_expr(&mut self, expr: Expr, src: Result<ExprSource, SyntheticSyntax>) -> 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, Ok(src.clone()));
176 self.source_map.pat_map.insert(src, id);
179 fn missing_pat(&mut self) -> PatId {
180 self.make_pat(Pat::Missing, Err(SyntheticSyntax))
182 fn make_pat(&mut self, pat: Pat, src: Result<PatSource, SyntheticSyntax>) -> 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: AstPtr<ast::Label>) -> 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::MacroStmts(e) => {
554 let statements = e.statements().filter_map(|s| self.collect_stmt(s)).collect();
555 let tail = e.expr().map(|e| self.collect_expr(e));
557 self.alloc_expr(Expr::MacroStmts { tail, statements }, syntax_ptr)
559 ast::Expr::UnderscoreExpr(_) => self.alloc_expr(Expr::Underscore, syntax_ptr),
563 fn collect_macro_call<F, T, U>(
565 mcall: ast::MacroCall,
566 syntax_ptr: AstPtr<ast::MacroCall>,
567 record_diagnostics: bool,
571 F: FnOnce(&mut Self, Option<T>) -> U,
574 // File containing the macro call. Expansion errors will be attached here.
575 let outer_file = self.expander.current_file_id;
577 let macro_call_ptr = self.expander.to_source(AstPtr::new(&mcall));
578 let res = self.expander.enter_expand(self.db, mcall);
580 let res = match res {
582 Err(UnresolvedMacro { path }) => {
583 if record_diagnostics {
584 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall {
585 node: InFile::new(outer_file, syntax_ptr),
589 return collector(self, None);
593 if record_diagnostics {
595 Some(ExpandError::UnresolvedProcMacro(krate)) => {
596 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedProcMacro {
597 node: InFile::new(outer_file, syntax_ptr),
602 self.source_map.diagnostics.push(BodyDiagnostic::MacroError {
603 node: InFile::new(outer_file, syntax_ptr),
604 message: err.to_string(),
612 Some((mark, expansion)) => {
613 self.source_map.expansions.insert(macro_call_ptr, self.expander.current_file_id);
614 let prev_ast_id_map = mem::replace(
615 &mut self.ast_id_map,
616 self.db.ast_id_map(self.expander.current_file_id),
619 let id = collector(self, Some(expansion));
620 self.ast_id_map = prev_ast_id_map;
621 self.expander.exit(self.db, mark);
624 None => collector(self, None),
628 fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
630 Some(expr) => self.collect_expr(expr),
631 None => self.missing_expr(),
635 fn collect_stmt(&mut self, s: ast::Stmt) -> Option<Statement> {
637 ast::Stmt::LetStmt(stmt) => {
638 if self.check_cfg(&stmt).is_none() {
641 let pat = self.collect_pat_opt(stmt.pat());
643 stmt.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
644 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
645 let else_branch = stmt
647 .and_then(|let_else| let_else.block_expr())
648 .map(|block| self.collect_block(block));
649 Some(Statement::Let { pat, type_ref, initializer, else_branch })
651 ast::Stmt::ExprStmt(stmt) => {
652 let expr = stmt.expr();
653 if let Some(expr) = &expr {
654 if self.check_cfg(expr).is_none() {
658 let has_semi = stmt.semicolon_token().is_some();
659 // Note that macro could be expanded to multiple statements
660 if let Some(expr @ ast::Expr::MacroExpr(mac)) = &expr {
661 let mac_call = mac.macro_call()?;
662 let syntax_ptr = AstPtr::new(expr);
663 let macro_ptr = AstPtr::new(&mac_call);
664 let stmt = self.collect_macro_call(
668 |this, expansion: Option<ast::MacroStmts>| match expansion {
670 let statements = expansion
672 .filter_map(|stmt| this.collect_stmt(stmt))
674 let tail = expansion.expr().map(|expr| this.collect_expr(expr));
676 let mac_stmts = this.alloc_expr(
677 Expr::MacroStmts { tail, statements },
678 AstPtr::new(&ast::Expr::MacroStmts(expansion)),
687 let expr = match stmt {
689 // Make the macro-call point to its expanded expression so we can query
690 // semantics on syntax pointers to the macro
691 let src = self.expander.to_source(syntax_ptr);
692 self.source_map.expr_map.insert(src, expr);
695 None => self.alloc_expr(Expr::Missing, syntax_ptr),
697 Some(Statement::Expr { expr, has_semi })
699 let expr = self.collect_expr_opt(expr);
700 Some(Statement::Expr { expr, has_semi })
703 ast::Stmt::Item(_item) => None,
707 fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId {
708 let file_local_id = self.ast_id_map.ast_id(&block);
709 let ast_id = AstId::new(self.expander.current_file_id, file_local_id);
711 BlockLoc { ast_id, module: self.expander.def_map.module_id(self.expander.module) };
712 let block_id = self.db.intern_block(block_loc);
714 let (module, def_map) = match self.db.block_def_map(block_id) {
716 self.body.block_scopes.push(block_id);
717 (def_map.root(), def_map)
719 None => (self.expander.module, self.expander.def_map.clone()),
721 let prev_def_map = mem::replace(&mut self.expander.def_map, def_map);
722 let prev_local_module = mem::replace(&mut self.expander.module, module);
724 let mut statements: Vec<_> =
725 block.statements().filter_map(|s| self.collect_stmt(s)).collect();
726 let tail = block.tail_expr().and_then(|e| self.maybe_collect_expr(e));
727 let tail = tail.or_else(|| {
728 let stmt = statements.pop()?;
729 if let Statement::Expr { expr, has_semi: false } = stmt {
732 statements.push(stmt);
736 let syntax_node_ptr = AstPtr::new(&block.into());
737 let expr_id = self.alloc_expr(
740 statements: statements.into_boxed_slice(),
747 self.expander.def_map = prev_def_map;
748 self.expander.module = prev_local_module;
752 fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
754 Some(block) => self.collect_block(block),
755 None => self.missing_expr(),
759 fn collect_label(&mut self, ast_label: ast::Label) -> LabelId {
761 name: ast_label.lifetime().as_ref().map_or_else(Name::missing, Name::new_lifetime),
763 self.alloc_label(label, AstPtr::new(&ast_label))
766 fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
767 let pat_id = self.collect_pat_(pat);
768 for (_, pats) in self.name_to_pat_grouping.drain() {
769 let pats = Arc::<[_]>::from(pats);
770 self.body.or_pats.extend(pats.iter().map(|&pat| (pat, pats.clone())));
772 self.is_lowering_inside_or_pat = false;
776 fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
778 Some(pat) => self.collect_pat(pat),
779 None => self.missing_pat(),
783 fn collect_pat_(&mut self, pat: ast::Pat) -> PatId {
784 let pattern = match &pat {
785 ast::Pat::IdentPat(bp) => {
786 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
788 let key = self.is_lowering_inside_or_pat.then(|| name.clone());
790 BindingAnnotation::new(bp.mut_token().is_some(), bp.ref_token().is_some());
791 let subpat = bp.pat().map(|subpat| self.collect_pat_(subpat));
792 let pattern = if annotation == BindingAnnotation::Unannotated && subpat.is_none() {
793 // This could also be a single-segment path pattern. To
794 // decide that, we need to try resolving the name.
795 let (resolved, _) = self.expander.def_map.resolve_path(
797 self.expander.module,
798 &name.clone().into(),
799 BuiltinShadowMode::Other,
801 match resolved.take_values() {
802 Some(ModuleDefId::ConstId(_)) => Pat::Path(name.into()),
803 Some(ModuleDefId::EnumVariantId(_)) => {
804 // this is only really valid for unit variants, but
805 // shadowing other enum variants with a pattern is
807 Pat::Path(name.into())
809 Some(ModuleDefId::AdtId(AdtId::StructId(s)))
810 if self.db.struct_data(s).variant_data.kind() != StructKind::Record =>
812 // Funnily enough, record structs *can* be shadowed
813 // by pattern bindings (but unit or tuple structs
815 Pat::Path(name.into())
817 // shadowing statics is an error as well, so we just ignore that case here
818 _ => Pat::Bind { name, mode: annotation, subpat },
821 Pat::Bind { name, mode: annotation, subpat }
824 let ptr = AstPtr::new(&pat);
825 let pat = self.alloc_pat(pattern, Either::Left(ptr));
826 if let Some(key) = key {
827 self.name_to_pat_grouping.entry(key).or_default().push(pat);
831 ast::Pat::TupleStructPat(p) => {
833 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
834 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
835 Pat::TupleStruct { path, args, ellipsis }
837 ast::Pat::RefPat(p) => {
838 let pat = self.collect_pat_opt(p.pat());
839 let mutability = Mutability::from_mutable(p.mut_token().is_some());
840 Pat::Ref { pat, mutability }
842 ast::Pat::PathPat(p) => {
844 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
845 path.map(Pat::Path).unwrap_or(Pat::Missing)
847 ast::Pat::OrPat(p) => {
848 self.is_lowering_inside_or_pat = true;
849 let pats = p.pats().map(|p| self.collect_pat_(p)).collect();
852 ast::Pat::ParenPat(p) => return self.collect_pat_opt_(p.pat()),
853 ast::Pat::TuplePat(p) => {
854 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
855 Pat::Tuple { args, ellipsis }
857 ast::Pat::WildcardPat(_) => Pat::Wild,
858 ast::Pat::RecordPat(p) => {
860 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
862 .record_pat_field_list()
863 .expect("every struct should have a field list")
866 let ast_pat = f.pat()?;
867 let pat = self.collect_pat_(ast_pat);
868 let name = f.field_name()?.as_name();
869 Some(RecordFieldPat { name, pat })
874 .record_pat_field_list()
875 .expect("every struct should have a field list")
879 Pat::Record { path, args, ellipsis }
881 ast::Pat::SlicePat(p) => {
882 let SlicePatComponents { prefix, slice, suffix } = p.components();
884 // FIXME properly handle `RestPat`
886 prefix: prefix.into_iter().map(|p| self.collect_pat_(p)).collect(),
887 slice: slice.map(|p| self.collect_pat_(p)),
888 suffix: suffix.into_iter().map(|p| self.collect_pat_(p)).collect(),
891 ast::Pat::LiteralPat(lit) => {
892 if let Some(ast_lit) = lit.literal() {
893 let expr = Expr::Literal(ast_lit.kind().into());
894 let expr_ptr = AstPtr::new(&ast::Expr::Literal(ast_lit));
895 let expr_id = self.alloc_expr(expr, expr_ptr);
901 ast::Pat::RestPat(_) => {
902 // `RestPat` requires special handling and should not be mapped
903 // to a Pat. Here we are using `Pat::Missing` as a fallback for
904 // when `RestPat` is mapped to `Pat`, which can easily happen
905 // when the source code being analyzed has a malformed pattern
906 // which includes `..` in a place where it isn't valid.
910 ast::Pat::BoxPat(boxpat) => {
911 let inner = self.collect_pat_opt_(boxpat.pat());
914 ast::Pat::ConstBlockPat(const_block_pat) => {
915 if let Some(expr) = const_block_pat.block_expr() {
916 let expr_id = self.collect_block(expr);
917 Pat::ConstBlock(expr_id)
922 ast::Pat::MacroPat(mac) => match mac.macro_call() {
924 let macro_ptr = AstPtr::new(&call);
925 let src = self.expander.to_source(Either::Left(AstPtr::new(&pat)));
927 self.collect_macro_call(call, macro_ptr, true, |this, expanded_pat| {
928 this.collect_pat_opt_(expanded_pat)
930 self.source_map.pat_map.insert(src, pat);
933 None => Pat::Missing,
936 ast::Pat::RangePat(_) => Pat::Missing,
938 let ptr = AstPtr::new(&pat);
939 self.alloc_pat(pattern, Either::Left(ptr))
942 fn collect_pat_opt_(&mut self, pat: Option<ast::Pat>) -> PatId {
944 Some(pat) => self.collect_pat_(pat),
945 None => self.missing_pat(),
949 fn collect_tuple_pat(&mut self, args: AstChildren<ast::Pat>) -> (Box<[PatId]>, Option<usize>) {
950 // Find the location of the `..`, if there is one. Note that we do not
951 // consider the possibility of there being multiple `..` here.
952 let ellipsis = args.clone().position(|p| matches!(p, ast::Pat::RestPat(_)));
953 // We want to skip the `..` pattern here, since we account for it above.
955 .filter(|p| !matches!(p, ast::Pat::RestPat(_)))
956 .map(|p| self.collect_pat_(p))
962 /// Returns `None` (and emits diagnostics) when `owner` if `#[cfg]`d out, and `Some(())` when
964 fn check_cfg(&mut self, owner: &dyn ast::HasAttrs) -> Option<()> {
965 match self.expander.parse_attrs(self.db, owner).cfg() {
967 if self.expander.cfg_options().check(&cfg) != Some(false) {
971 self.source_map.diagnostics.push(BodyDiagnostic::InactiveCode {
973 self.expander.current_file_id,
974 SyntaxNodePtr::new(owner.syntax()),
977 opts: self.expander.cfg_options().clone(),
987 impl From<ast::LiteralKind> for Literal {
988 fn from(ast_lit_kind: ast::LiteralKind) -> Self {
990 // FIXME: these should have actual values filled in, but unsure on perf impact
991 LiteralKind::IntNumber(lit) => {
992 if let builtin @ Some(_) = lit.suffix().and_then(BuiltinFloat::from_suffix) {
994 FloatTypeWrapper::new(lit.float_value().unwrap_or(Default::default())),
997 } else if let builtin @ Some(_) = lit.suffix().and_then(BuiltinInt::from_suffix) {
998 Literal::Int(lit.value().unwrap_or(0) as i128, builtin)
1000 let builtin = lit.suffix().and_then(BuiltinUint::from_suffix);
1001 Literal::Uint(lit.value().unwrap_or(0), builtin)
1004 LiteralKind::FloatNumber(lit) => {
1005 let ty = lit.suffix().and_then(BuiltinFloat::from_suffix);
1006 Literal::Float(FloatTypeWrapper::new(lit.value().unwrap_or(Default::default())), ty)
1008 LiteralKind::ByteString(bs) => {
1009 let text = bs.value().map(Box::from).unwrap_or_else(Default::default);
1010 Literal::ByteString(text)
1012 LiteralKind::String(s) => {
1013 let text = s.value().map(Box::from).unwrap_or_else(Default::default);
1014 Literal::String(text)
1016 LiteralKind::Byte(b) => {
1017 Literal::Uint(b.value().unwrap_or_default() as u128, Some(BuiltinUint::U8))
1019 LiteralKind::Char(c) => Literal::Char(c.value().unwrap_or_default()),
1020 LiteralKind::Bool(val) => Literal::Bool(val),