1 //! Transforms `ast::Expr` into an equivalent `hir_def::expr::Expr`
4 use std::{mem, sync::Arc};
8 ast_id_map::{AstIdMap, FileAstId},
10 name::{name, AsName, Name},
11 ExpandError, HirFileId, InFile,
17 self, ArrayExprKind, AstChildren, HasArgList, HasLoopBody, HasName, LiteralKind,
20 AstNode, AstPtr, SyntaxNodePtr,
25 body::{Body, BodySourceMap, Expander, LabelSource, PatPtr, SyntheticSyntax},
26 body::{BodyDiagnostic, ExprSource, PatSource},
27 builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint},
30 dummy_expr_id, Array, BindingAnnotation, Expr, ExprId, Label, LabelId, Literal, MatchArm,
31 MatchGuard, Pat, PatId, RecordFieldPat, RecordLitField, Statement,
34 item_scope::BuiltinShadowMode,
35 path::{GenericArgs, Path},
36 type_ref::{Mutability, Rawness, TypeRef},
37 AdtId, BlockLoc, ModuleDefId, UnresolvedMacro,
40 pub struct LowerCtx<'a> {
41 pub db: &'a dyn DefDatabase,
43 file_id: Option<HirFileId>,
44 source_ast_id_map: Option<Arc<AstIdMap>>,
47 impl<'a> LowerCtx<'a> {
48 pub fn new(db: &'a dyn DefDatabase, file_id: HirFileId) -> Self {
51 hygiene: Hygiene::new(db.upcast(), file_id),
52 file_id: Some(file_id),
53 source_ast_id_map: Some(db.ast_id_map(file_id)),
57 pub fn with_hygiene(db: &'a dyn DefDatabase, hygiene: &Hygiene) -> Self {
58 LowerCtx { db, hygiene: hygiene.clone(), file_id: None, source_ast_id_map: None }
61 pub(crate) fn hygiene(&self) -> &Hygiene {
65 pub(crate) fn file_id(&self) -> HirFileId {
69 pub(crate) fn lower_path(&self, ast: ast::Path) -> Option<Path> {
70 Path::from_src(ast, self)
73 pub(crate) fn ast_id<N: AstNode>(&self, item: &N) -> Option<FileAstId<N>> {
74 self.source_ast_id_map.as_ref().map(|ast_id_map| ast_id_map.ast_id(item))
81 params: Option<ast::ParamList>,
82 body: Option<ast::Expr>,
83 ) -> (Body, BodySourceMap) {
86 source_map: BodySourceMap::default(),
88 exprs: Arena::default(),
89 pats: Arena::default(),
90 labels: Arena::default(),
92 body_expr: dummy_expr_id(),
93 block_scopes: Vec::new(),
97 statements_in_scope: Vec::new(),
99 .collect(params, body)
102 struct ExprCollector<'a> {
103 db: &'a dyn DefDatabase,
106 source_map: BodySourceMap,
107 statements_in_scope: Vec<Statement>,
110 impl ExprCollector<'_> {
113 param_list: Option<ast::ParamList>,
114 body: Option<ast::Expr>,
115 ) -> (Body, BodySourceMap) {
116 if let Some(param_list) = param_list {
117 if let Some(self_param) = param_list.self_param() {
118 let ptr = AstPtr::new(&self_param);
119 let param_pat = self.alloc_pat(
122 mode: BindingAnnotation::new(
123 self_param.mut_token().is_some() && self_param.amp_token().is_none(),
130 self.body.params.push(param_pat);
133 for pat in param_list.params().filter_map(|param| param.pat()) {
134 let param_pat = self.collect_pat(pat);
135 self.body.params.push(param_pat);
139 self.body.body_expr = self.collect_expr_opt(body);
140 (self.body, self.source_map)
143 fn ctx(&self) -> LowerCtx<'_> {
144 LowerCtx::new(self.db, self.expander.current_file_id)
147 fn alloc_expr(&mut self, expr: Expr, ptr: AstPtr<ast::Expr>) -> ExprId {
148 let src = self.expander.to_source(ptr);
149 let id = self.make_expr(expr, Ok(src.clone()));
150 self.source_map.expr_map.insert(src, id);
153 // desugared exprs don't have ptr, that's wrong and should be fixed
155 fn alloc_expr_desugared(&mut self, expr: Expr) -> ExprId {
156 self.make_expr(expr, Err(SyntheticSyntax))
158 fn unit(&mut self) -> ExprId {
159 self.alloc_expr_desugared(Expr::Tuple { exprs: Box::default() })
161 fn missing_expr(&mut self) -> ExprId {
162 self.alloc_expr_desugared(Expr::Missing)
164 fn make_expr(&mut self, expr: Expr, src: Result<ExprSource, SyntheticSyntax>) -> ExprId {
165 let id = self.body.exprs.alloc(expr);
166 self.source_map.expr_map_back.insert(id, src);
170 fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId {
171 let src = self.expander.to_source(ptr);
172 let id = self.make_pat(pat, Ok(src.clone()));
173 self.source_map.pat_map.insert(src, id);
176 fn missing_pat(&mut self) -> PatId {
177 self.make_pat(Pat::Missing, Err(SyntheticSyntax))
179 fn make_pat(&mut self, pat: Pat, src: Result<PatSource, SyntheticSyntax>) -> PatId {
180 let id = self.body.pats.alloc(pat);
181 self.source_map.pat_map_back.insert(id, src);
185 fn alloc_label(&mut self, label: Label, ptr: AstPtr<ast::Label>) -> LabelId {
186 let src = self.expander.to_source(ptr);
187 let id = self.make_label(label, src.clone());
188 self.source_map.label_map.insert(src, id);
191 fn make_label(&mut self, label: Label, src: LabelSource) -> LabelId {
192 let id = self.body.labels.alloc(label);
193 self.source_map.label_map_back.insert(id, src);
197 fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
198 self.maybe_collect_expr(expr).unwrap_or_else(|| self.missing_expr())
201 /// Returns `None` if and only if the expression is `#[cfg]`d out.
202 fn maybe_collect_expr(&mut self, expr: ast::Expr) -> Option<ExprId> {
203 let syntax_ptr = AstPtr::new(&expr);
204 self.check_cfg(&expr)?;
207 ast::Expr::IfExpr(e) => {
208 let then_branch = self.collect_block_opt(e.then_branch());
210 let else_branch = e.else_branch().map(|b| match b {
211 ast::ElseBranch::Block(it) => self.collect_block(it),
212 ast::ElseBranch::IfExpr(elif) => {
213 let expr: ast::Expr = ast::Expr::cast(elif.syntax().clone()).unwrap();
214 self.collect_expr(expr)
218 let condition = match e.condition() {
219 None => self.missing_expr(),
220 Some(condition) => match condition.pat() {
221 None => self.collect_expr_opt(condition.expr()),
222 // if let -- desugar to match
224 let pat = self.collect_pat(pat);
225 let match_expr = self.collect_expr_opt(condition.expr());
226 let placeholder_pat = self.missing_pat();
228 MatchArm { pat, expr: then_branch, guard: None },
230 pat: placeholder_pat,
231 expr: else_branch.unwrap_or_else(|| self.unit()),
237 self.alloc_expr(Expr::Match { expr: match_expr, arms }, syntax_ptr),
243 self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
245 ast::Expr::BlockExpr(e) => match e.modifier() {
246 Some(ast::BlockModifier::Try(_)) => {
247 let body = self.collect_block(e);
248 self.alloc_expr(Expr::TryBlock { body }, syntax_ptr)
250 Some(ast::BlockModifier::Unsafe(_)) => {
251 let body = self.collect_block(e);
252 self.alloc_expr(Expr::Unsafe { body }, syntax_ptr)
254 // FIXME: we need to record these effects somewhere...
255 Some(ast::BlockModifier::Label(label)) => {
256 let label = self.collect_label(label);
257 let res = self.collect_block(e);
258 match &mut self.body.exprs[res] {
259 Expr::Block { label: block_label, .. } => {
260 *block_label = Some(label);
266 Some(ast::BlockModifier::Async(_)) => {
267 let body = self.collect_block(e);
268 self.alloc_expr(Expr::Async { body }, syntax_ptr)
270 Some(ast::BlockModifier::Const(_)) => {
271 let body = self.collect_block(e);
272 self.alloc_expr(Expr::Const { body }, syntax_ptr)
274 None => self.collect_block(e),
276 ast::Expr::LoopExpr(e) => {
277 let label = e.label().map(|label| self.collect_label(label));
278 let body = self.collect_block_opt(e.loop_body());
279 self.alloc_expr(Expr::Loop { body, label }, syntax_ptr)
281 ast::Expr::WhileExpr(e) => {
282 let label = e.label().map(|label| self.collect_label(label));
283 let body = self.collect_block_opt(e.loop_body());
285 let condition = match e.condition() {
286 None => self.missing_expr(),
287 Some(condition) => match condition.pat() {
288 None => self.collect_expr_opt(condition.expr()),
289 // if let -- desugar to match
291 cov_mark::hit!(infer_resolve_while_let);
292 let pat = self.collect_pat(pat);
293 let match_expr = self.collect_expr_opt(condition.expr());
294 let placeholder_pat = self.missing_pat();
296 self.alloc_expr_desugared(Expr::Break { expr: None, label: None });
298 MatchArm { pat, expr: body, guard: None },
299 MatchArm { pat: placeholder_pat, expr: break_, guard: None },
303 self.alloc_expr_desugared(Expr::Match { expr: match_expr, arms });
305 self.alloc_expr(Expr::Loop { body: match_expr, label }, syntax_ptr),
311 self.alloc_expr(Expr::While { condition, body, label }, syntax_ptr)
313 ast::Expr::ForExpr(e) => {
314 let label = e.label().map(|label| self.collect_label(label));
315 let iterable = self.collect_expr_opt(e.iterable());
316 let pat = self.collect_pat_opt(e.pat());
317 let body = self.collect_block_opt(e.loop_body());
318 self.alloc_expr(Expr::For { iterable, pat, body, label }, syntax_ptr)
320 ast::Expr::CallExpr(e) => {
321 let callee = self.collect_expr_opt(e.expr());
322 let args = if let Some(arg_list) = e.arg_list() {
323 arg_list.args().filter_map(|e| self.maybe_collect_expr(e)).collect()
327 self.alloc_expr(Expr::Call { callee, args }, syntax_ptr)
329 ast::Expr::MethodCallExpr(e) => {
330 let receiver = self.collect_expr_opt(e.receiver());
331 let args = if let Some(arg_list) = e.arg_list() {
332 arg_list.args().filter_map(|e| self.maybe_collect_expr(e)).collect()
336 let method_name = e.name_ref().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
339 .and_then(|it| GenericArgs::from_ast(&self.ctx(), it))
342 Expr::MethodCall { receiver, method_name, args, generic_args },
346 ast::Expr::MatchExpr(e) => {
347 let expr = self.collect_expr_opt(e.expr());
348 let arms = if let Some(match_arm_list) = e.match_arm_list() {
352 self.check_cfg(&arm).map(|()| MatchArm {
353 pat: self.collect_pat_opt(arm.pat()),
354 expr: self.collect_expr_opt(arm.expr()),
355 guard: arm.guard().map(|guard| match guard.pat() {
356 Some(pat) => MatchGuard::IfLet {
357 pat: self.collect_pat(pat),
358 expr: self.collect_expr_opt(guard.expr()),
361 MatchGuard::If { expr: self.collect_expr_opt(guard.expr()) }
370 self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
372 ast::Expr::PathExpr(e) => {
375 .and_then(|path| self.expander.parse_path(self.db, path))
377 .unwrap_or(Expr::Missing);
378 self.alloc_expr(path, syntax_ptr)
380 ast::Expr::ContinueExpr(e) => self.alloc_expr(
381 Expr::Continue { label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
384 ast::Expr::BreakExpr(e) => {
385 let expr = e.expr().map(|e| self.collect_expr(e));
387 Expr::Break { expr, label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
391 ast::Expr::ParenExpr(e) => {
392 let inner = self.collect_expr_opt(e.expr());
393 // make the paren expr point to the inner expression as well
394 let src = self.expander.to_source(syntax_ptr);
395 self.source_map.expr_map.insert(src, inner);
398 ast::Expr::ReturnExpr(e) => {
399 let expr = e.expr().map(|e| self.collect_expr(e));
400 self.alloc_expr(Expr::Return { expr }, syntax_ptr)
402 ast::Expr::YieldExpr(e) => {
403 let expr = e.expr().map(|e| self.collect_expr(e));
404 self.alloc_expr(Expr::Yield { expr }, syntax_ptr)
406 ast::Expr::RecordExpr(e) => {
408 e.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
409 let record_lit = if let Some(nfl) = e.record_expr_field_list() {
412 .filter_map(|field| {
413 self.check_cfg(&field)?;
415 let name = field.field_name()?.as_name();
417 let expr = match field.expr() {
418 Some(e) => self.collect_expr(e),
419 None => self.missing_expr(),
421 let src = self.expander.to_source(AstPtr::new(&field));
422 self.source_map.field_map.insert(src.clone(), expr);
423 self.source_map.field_map_back.insert(expr, src);
424 Some(RecordLitField { name, expr })
427 let spread = nfl.spread().map(|s| self.collect_expr(s));
428 Expr::RecordLit { path, fields, spread }
430 Expr::RecordLit { path, fields: Box::default(), spread: None }
433 self.alloc_expr(record_lit, syntax_ptr)
435 ast::Expr::FieldExpr(e) => {
436 let expr = self.collect_expr_opt(e.expr());
437 let name = match e.field_access() {
438 Some(kind) => kind.as_name(),
439 _ => Name::missing(),
441 self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
443 ast::Expr::AwaitExpr(e) => {
444 let expr = self.collect_expr_opt(e.expr());
445 self.alloc_expr(Expr::Await { expr }, syntax_ptr)
447 ast::Expr::TryExpr(e) => {
448 let expr = self.collect_expr_opt(e.expr());
449 self.alloc_expr(Expr::Try { expr }, syntax_ptr)
451 ast::Expr::CastExpr(e) => {
452 let expr = self.collect_expr_opt(e.expr());
453 let type_ref = Interned::new(TypeRef::from_ast_opt(&self.ctx(), e.ty()));
454 self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
456 ast::Expr::RefExpr(e) => {
457 let expr = self.collect_expr_opt(e.expr());
458 let raw_tok = e.raw_token().is_some();
459 let mutability = if raw_tok {
460 if e.mut_token().is_some() {
462 } else if e.const_token().is_some() {
465 unreachable!("parser only remaps to raw_token() if matching mutability token follows")
468 Mutability::from_mutable(e.mut_token().is_some())
470 let rawness = Rawness::from_raw(raw_tok);
471 self.alloc_expr(Expr::Ref { expr, rawness, mutability }, syntax_ptr)
473 ast::Expr::PrefixExpr(e) => {
474 let expr = self.collect_expr_opt(e.expr());
476 Some(op) => self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr),
477 None => self.alloc_expr(Expr::Missing, syntax_ptr),
480 ast::Expr::ClosureExpr(e) => {
481 let mut args = Vec::new();
482 let mut arg_types = Vec::new();
483 if let Some(pl) = e.param_list() {
484 for param in pl.params() {
485 let pat = self.collect_pat_opt(param.pat());
487 param.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
489 arg_types.push(type_ref);
494 .and_then(|r| r.ty())
495 .map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
496 let body = self.collect_expr_opt(e.body());
498 Expr::Lambda { args: args.into(), arg_types: arg_types.into(), ret_type, body },
502 ast::Expr::BinExpr(e) => {
503 let lhs = self.collect_expr_opt(e.lhs());
504 let rhs = self.collect_expr_opt(e.rhs());
505 let op = e.op_kind();
506 self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr)
508 ast::Expr::TupleExpr(e) => {
509 let exprs = e.fields().map(|expr| self.collect_expr(expr)).collect();
510 self.alloc_expr(Expr::Tuple { exprs }, syntax_ptr)
512 ast::Expr::BoxExpr(e) => {
513 let expr = self.collect_expr_opt(e.expr());
514 self.alloc_expr(Expr::Box { expr }, syntax_ptr)
517 ast::Expr::ArrayExpr(e) => {
521 ArrayExprKind::ElementList(e) => {
522 let exprs = e.map(|expr| self.collect_expr(expr)).collect();
523 self.alloc_expr(Expr::Array(Array::ElementList(exprs)), syntax_ptr)
525 ArrayExprKind::Repeat { initializer, repeat } => {
526 let initializer = self.collect_expr_opt(initializer);
527 let repeat = self.collect_expr_opt(repeat);
529 Expr::Array(Array::Repeat { initializer, repeat }),
536 ast::Expr::Literal(e) => self.alloc_expr(Expr::Literal(e.kind().into()), syntax_ptr),
537 ast::Expr::IndexExpr(e) => {
538 let base = self.collect_expr_opt(e.base());
539 let index = self.collect_expr_opt(e.index());
540 self.alloc_expr(Expr::Index { base, index }, syntax_ptr)
542 ast::Expr::RangeExpr(e) => {
543 let lhs = e.start().map(|lhs| self.collect_expr(lhs));
544 let rhs = e.end().map(|rhs| self.collect_expr(rhs));
546 Some(range_type) => {
547 self.alloc_expr(Expr::Range { lhs, rhs, range_type }, syntax_ptr)
549 None => self.alloc_expr(Expr::Missing, syntax_ptr),
552 ast::Expr::MacroCall(e) => {
553 let macro_ptr = AstPtr::new(&e);
554 let mut ids = vec![];
555 self.collect_macro_call(e, macro_ptr, |this, expansion| {
556 ids.push(match expansion {
557 Some(it) => this.collect_expr(it),
558 None => this.alloc_expr(Expr::Missing, syntax_ptr.clone()),
563 ast::Expr::MacroStmts(e) => {
564 e.statements().for_each(|s| self.collect_stmt(s));
567 .map(|e| self.collect_expr(e))
568 .unwrap_or_else(|| self.alloc_expr(Expr::Missing, syntax_ptr.clone()));
570 self.alloc_expr(Expr::MacroStmts { tail }, syntax_ptr)
575 fn collect_macro_call<F: FnMut(&mut Self, Option<T>), T: ast::AstNode>(
578 syntax_ptr: AstPtr<ast::MacroCall>,
581 // File containing the macro call. Expansion errors will be attached here.
582 let outer_file = self.expander.current_file_id;
584 let macro_call = self.expander.to_source(AstPtr::new(&e));
585 let res = self.expander.enter_expand(self.db, e);
587 let res = match res {
589 Err(UnresolvedMacro { path }) => {
590 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall {
591 node: InFile::new(outer_file, syntax_ptr),
594 collector(self, None);
600 Some(ExpandError::UnresolvedProcMacro) => {
601 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedProcMacro {
602 node: InFile::new(outer_file, syntax_ptr),
606 self.source_map.diagnostics.push(BodyDiagnostic::MacroError {
607 node: InFile::new(outer_file, syntax_ptr),
608 message: err.to_string(),
615 Some((mark, expansion)) => {
616 self.source_map.expansions.insert(macro_call, self.expander.current_file_id);
618 let id = collector(self, Some(expansion));
619 self.expander.exit(self.db, mark);
622 None => collector(self, None),
626 fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
628 Some(expr) => self.collect_expr(expr),
629 None => self.missing_expr(),
633 fn collect_stmt(&mut self, s: ast::Stmt) {
635 ast::Stmt::LetStmt(stmt) => {
636 if self.check_cfg(&stmt).is_none() {
639 let pat = self.collect_pat_opt(stmt.pat());
641 stmt.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
642 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
643 let else_branch = stmt
645 .and_then(|let_else| let_else.block_expr())
646 .map(|block| self.collect_block(block));
647 self.statements_in_scope.push(Statement::Let {
654 ast::Stmt::ExprStmt(stmt) => {
655 if let Some(expr) = stmt.expr() {
656 if self.check_cfg(&expr).is_none() {
660 let has_semi = stmt.semicolon_token().is_some();
661 // Note that macro could be expended to multiple statements
662 if let Some(ast::Expr::MacroCall(m)) = stmt.expr() {
663 let macro_ptr = AstPtr::new(&m);
664 let syntax_ptr = AstPtr::new(&stmt.expr().unwrap());
666 self.collect_macro_call(m, macro_ptr, |this, expansion| match expansion {
668 let statements: ast::MacroStmts = expansion;
670 statements.statements().for_each(|stmt| this.collect_stmt(stmt));
671 if let Some(expr) = statements.expr() {
672 let expr = this.collect_expr(expr);
673 this.statements_in_scope.push(Statement::Expr { expr, has_semi });
677 let expr = this.alloc_expr(Expr::Missing, syntax_ptr.clone());
678 this.statements_in_scope.push(Statement::Expr { expr, has_semi });
682 let expr = self.collect_expr_opt(stmt.expr());
683 self.statements_in_scope.push(Statement::Expr { expr, has_semi });
686 ast::Stmt::Item(item) => {
687 self.check_cfg(&item);
692 fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId {
693 let ast_id = self.expander.ast_id(&block);
695 BlockLoc { ast_id, module: self.expander.def_map.module_id(self.expander.module) };
696 let block_id = self.db.intern_block(block_loc);
698 let (module, def_map) = match self.db.block_def_map(block_id) {
700 self.body.block_scopes.push(block_id);
701 (def_map.root(), def_map)
703 None => (self.expander.module, self.expander.def_map.clone()),
705 let prev_def_map = mem::replace(&mut self.expander.def_map, def_map);
706 let prev_local_module = mem::replace(&mut self.expander.module, module);
707 let prev_statements = std::mem::take(&mut self.statements_in_scope);
709 block.statements().for_each(|s| self.collect_stmt(s));
710 block.tail_expr().and_then(|e| {
711 let expr = self.maybe_collect_expr(e)?;
712 self.statements_in_scope.push(Statement::Expr { expr, has_semi: false });
717 if let Some(Statement::Expr { expr, has_semi: false }) = self.statements_in_scope.last() {
719 self.statements_in_scope.pop();
722 let statements = std::mem::replace(&mut self.statements_in_scope, prev_statements).into();
723 let syntax_node_ptr = AstPtr::new(&block.into());
724 let expr_id = self.alloc_expr(
725 Expr::Block { id: block_id, statements, tail, label: None },
729 self.expander.def_map = prev_def_map;
730 self.expander.module = prev_local_module;
734 fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
736 Some(block) => self.collect_block(block),
737 None => self.missing_expr(),
741 fn collect_label(&mut self, ast_label: ast::Label) -> LabelId {
743 name: ast_label.lifetime().as_ref().map_or_else(Name::missing, Name::new_lifetime),
745 self.alloc_label(label, AstPtr::new(&ast_label))
748 fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
749 let pattern = match &pat {
750 ast::Pat::IdentPat(bp) => {
751 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
753 BindingAnnotation::new(bp.mut_token().is_some(), bp.ref_token().is_some());
754 let subpat = bp.pat().map(|subpat| self.collect_pat(subpat));
755 if annotation == BindingAnnotation::Unannotated && subpat.is_none() {
756 // This could also be a single-segment path pattern. To
757 // decide that, we need to try resolving the name.
758 let (resolved, _) = self.expander.def_map.resolve_path(
760 self.expander.module,
761 &name.clone().into(),
762 BuiltinShadowMode::Other,
764 match resolved.take_values() {
765 Some(ModuleDefId::ConstId(_)) => Pat::Path(name.into()),
766 Some(ModuleDefId::EnumVariantId(_)) => {
767 // this is only really valid for unit variants, but
768 // shadowing other enum variants with a pattern is
770 Pat::Path(name.into())
772 Some(ModuleDefId::AdtId(AdtId::StructId(s)))
773 if self.db.struct_data(s).variant_data.kind() != StructKind::Record =>
775 // Funnily enough, record structs *can* be shadowed
776 // by pattern bindings (but unit or tuple structs
778 Pat::Path(name.into())
780 // shadowing statics is an error as well, so we just ignore that case here
781 _ => Pat::Bind { name, mode: annotation, subpat },
784 Pat::Bind { name, mode: annotation, subpat }
787 ast::Pat::TupleStructPat(p) => {
789 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
790 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
791 Pat::TupleStruct { path, args, ellipsis }
793 ast::Pat::RefPat(p) => {
794 let pat = self.collect_pat_opt(p.pat());
795 let mutability = Mutability::from_mutable(p.mut_token().is_some());
796 Pat::Ref { pat, mutability }
798 ast::Pat::PathPat(p) => {
800 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
801 path.map(Pat::Path).unwrap_or(Pat::Missing)
803 ast::Pat::OrPat(p) => {
804 let pats = p.pats().map(|p| self.collect_pat(p)).collect();
807 ast::Pat::ParenPat(p) => return self.collect_pat_opt(p.pat()),
808 ast::Pat::TuplePat(p) => {
809 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
810 Pat::Tuple { args, ellipsis }
812 ast::Pat::WildcardPat(_) => Pat::Wild,
813 ast::Pat::RecordPat(p) => {
815 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
817 .record_pat_field_list()
818 .expect("every struct should have a field list")
821 let ast_pat = f.pat()?;
822 let pat = self.collect_pat(ast_pat);
823 let name = f.field_name()?.as_name();
824 Some(RecordFieldPat { name, pat })
829 .record_pat_field_list()
830 .expect("every struct should have a field list")
834 Pat::Record { path, args, ellipsis }
836 ast::Pat::SlicePat(p) => {
837 let SlicePatComponents { prefix, slice, suffix } = p.components();
839 // FIXME properly handle `RestPat`
841 prefix: prefix.into_iter().map(|p| self.collect_pat(p)).collect(),
842 slice: slice.map(|p| self.collect_pat(p)),
843 suffix: suffix.into_iter().map(|p| self.collect_pat(p)).collect(),
846 ast::Pat::LiteralPat(lit) => {
847 if let Some(ast_lit) = lit.literal() {
848 let expr = Expr::Literal(ast_lit.kind().into());
849 let expr_ptr = AstPtr::new(&ast::Expr::Literal(ast_lit));
850 let expr_id = self.alloc_expr(expr, expr_ptr);
856 ast::Pat::RestPat(_) => {
857 // `RestPat` requires special handling and should not be mapped
858 // to a Pat. Here we are using `Pat::Missing` as a fallback for
859 // when `RestPat` is mapped to `Pat`, which can easily happen
860 // when the source code being analyzed has a malformed pattern
861 // which includes `..` in a place where it isn't valid.
865 ast::Pat::BoxPat(boxpat) => {
866 let inner = self.collect_pat_opt(boxpat.pat());
869 ast::Pat::ConstBlockPat(const_block_pat) => {
870 if let Some(expr) = const_block_pat.block_expr() {
871 let expr_id = self.collect_block(expr);
872 Pat::ConstBlock(expr_id)
877 ast::Pat::MacroPat(mac) => match mac.macro_call() {
879 let macro_ptr = AstPtr::new(&call);
881 self.collect_macro_call(call, macro_ptr, |this, expanded_pat| {
882 pat = Some(this.collect_pat_opt(expanded_pat));
886 Some(pat) => return pat,
887 None => Pat::Missing,
890 None => Pat::Missing,
893 ast::Pat::RangePat(_) => Pat::Missing,
895 let ptr = AstPtr::new(&pat);
896 self.alloc_pat(pattern, Either::Left(ptr))
899 fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
901 Some(pat) => self.collect_pat(pat),
902 None => self.missing_pat(),
906 fn collect_tuple_pat(&mut self, args: AstChildren<ast::Pat>) -> (Box<[PatId]>, Option<usize>) {
907 // Find the location of the `..`, if there is one. Note that we do not
908 // consider the possibility of there being multiple `..` here.
909 let ellipsis = args.clone().position(|p| matches!(p, ast::Pat::RestPat(_)));
910 // We want to skip the `..` pattern here, since we account for it above.
912 .filter(|p| !matches!(p, ast::Pat::RestPat(_)))
913 .map(|p| self.collect_pat(p))
919 /// Returns `None` (and emits diagnostics) when `owner` if `#[cfg]`d out, and `Some(())` when
921 fn check_cfg(&mut self, owner: &dyn ast::HasAttrs) -> Option<()> {
922 match self.expander.parse_attrs(self.db, owner).cfg() {
924 if self.expander.cfg_options().check(&cfg) != Some(false) {
928 self.source_map.diagnostics.push(BodyDiagnostic::InactiveCode {
930 self.expander.current_file_id,
931 SyntaxNodePtr::new(owner.syntax()),
934 opts: self.expander.cfg_options().clone(),
944 impl From<ast::LiteralKind> for Literal {
945 fn from(ast_lit_kind: ast::LiteralKind) -> Self {
947 // FIXME: these should have actual values filled in, but unsure on perf impact
948 LiteralKind::IntNumber(lit) => {
949 if let builtin @ Some(_) = lit.suffix().and_then(BuiltinFloat::from_suffix) {
950 Literal::Float(Default::default(), builtin)
951 } else if let builtin @ Some(_) =
952 lit.suffix().and_then(|it| BuiltinInt::from_suffix(it))
954 Literal::Int(lit.value().unwrap_or(0) as i128, builtin)
956 let builtin = lit.suffix().and_then(|it| BuiltinUint::from_suffix(it));
957 Literal::Uint(lit.value().unwrap_or(0), builtin)
960 LiteralKind::FloatNumber(lit) => {
961 let ty = lit.suffix().and_then(|it| BuiltinFloat::from_suffix(it));
962 Literal::Float(Default::default(), ty)
964 LiteralKind::ByteString(bs) => {
965 let text = bs.value().map(Box::from).unwrap_or_else(Default::default);
966 Literal::ByteString(text)
968 LiteralKind::String(_) => Literal::String(Default::default()),
969 LiteralKind::Byte => Literal::Uint(Default::default(), Some(BuiltinUint::U8)),
970 LiteralKind::Bool(val) => Literal::Bool(val),
971 LiteralKind::Char => Literal::Char(Default::default()),