1 //! Transforms `ast::Expr` into an equivalent `hir_def::expr::Expr`
4 use std::{any::type_name, mem, sync::Arc};
9 name::{name, AsName, Name},
10 ExpandError, HirFileId, MacroDefId, MacroDefKind,
14 use rustc_hash::FxHashMap;
17 self, ArgListOwner, ArrayExprKind, AstChildren, LiteralKind, LoopBodyOwner, NameOwner,
20 AstNode, AstPtr, SyntaxNodePtr,
26 body::{Body, BodySourceMap, Expander, LabelSource, PatPtr, SyntheticSyntax},
27 builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint},
29 diagnostics::{InactiveCode, MacroError, UnresolvedProcMacro},
31 dummy_expr_id, ArithOp, Array, BinaryOp, BindingAnnotation, CmpOp, Expr, ExprId, Label,
32 LabelId, Literal, LogicOp, MatchArm, Ordering, Pat, PatId, RecordFieldPat, RecordLitField,
35 item_scope::BuiltinShadowMode,
36 item_tree::{ItemTree, ItemTreeId, ItemTreeNode},
37 path::{GenericArgs, Path},
38 type_ref::{Mutability, Rawness, TypeRef},
39 AdtId, BlockLoc, ConstLoc, ContainerId, DefWithBodyId, EnumLoc, FunctionLoc, Intern,
40 ModuleDefId, StaticLoc, StructLoc, TraitLoc, TypeAliasLoc, UnionLoc,
43 use super::{diagnostics::BodyDiagnostic, ExprSource, PatSource};
45 pub(crate) struct LowerCtx {
50 pub(crate) fn new(db: &dyn DefDatabase, file_id: HirFileId) -> Self {
51 LowerCtx { hygiene: Hygiene::new(db.upcast(), file_id) }
53 pub(crate) fn with_hygiene(hygiene: &Hygiene) -> Self {
54 LowerCtx { hygiene: hygiene.clone() }
57 pub(crate) fn lower_path(&self, ast: ast::Path) -> Option<Path> {
58 Path::from_src(ast, &self.hygiene)
66 params: Option<ast::ParamList>,
67 body: Option<ast::Expr>,
68 ) -> (Body, BodySourceMap) {
69 let item_tree = db.item_tree(expander.current_file_id);
73 source_map: BodySourceMap::default(),
75 exprs: Arena::default(),
76 pats: Arena::default(),
77 labels: Arena::default(),
79 body_expr: dummy_expr_id(),
80 item_scope: Default::default(),
84 let mut map = FxHashMap::default();
85 map.insert(expander.current_file_id, item_tree);
90 .collect(params, body)
93 struct ExprCollector<'a> {
94 db: &'a dyn DefDatabase,
98 source_map: BodySourceMap,
100 item_trees: FxHashMap<HirFileId, Arc<ItemTree>>,
103 impl ExprCollector<'_> {
106 param_list: Option<ast::ParamList>,
107 body: Option<ast::Expr>,
108 ) -> (Body, BodySourceMap) {
109 if let Some(param_list) = param_list {
110 if let Some(self_param) = param_list.self_param() {
111 let ptr = AstPtr::new(&self_param);
112 let param_pat = self.alloc_pat(
115 mode: BindingAnnotation::new(
116 self_param.mut_token().is_some() && self_param.amp_token().is_none(),
123 self.body.params.push(param_pat);
126 for param in param_list.params() {
127 let pat = match param.pat() {
131 let param_pat = self.collect_pat(pat);
132 self.body.params.push(param_pat);
136 self.body.body_expr = self.collect_expr_opt(body);
137 (self.body, self.source_map)
140 fn ctx(&self) -> LowerCtx {
141 LowerCtx::new(self.db, self.expander.current_file_id)
144 fn alloc_expr(&mut self, expr: Expr, ptr: AstPtr<ast::Expr>) -> ExprId {
145 let src = self.expander.to_source(ptr);
146 let id = self.make_expr(expr, Ok(src.clone()));
147 self.source_map.expr_map.insert(src, id);
150 // desugared exprs don't have ptr, that's wrong and should be fixed
152 fn alloc_expr_desugared(&mut self, expr: Expr) -> ExprId {
153 self.make_expr(expr, Err(SyntheticSyntax))
155 fn unit(&mut self) -> ExprId {
156 self.alloc_expr_desugared(Expr::Tuple { exprs: Vec::new() })
158 fn missing_expr(&mut self) -> ExprId {
159 self.alloc_expr_desugared(Expr::Missing)
161 fn make_expr(&mut self, expr: Expr, src: Result<ExprSource, SyntheticSyntax>) -> ExprId {
162 let id = self.body.exprs.alloc(expr);
163 self.source_map.expr_map_back.insert(id, src);
167 fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId {
168 let src = self.expander.to_source(ptr);
169 let id = self.make_pat(pat, Ok(src.clone()));
170 self.source_map.pat_map.insert(src, id);
173 fn missing_pat(&mut self) -> PatId {
174 self.make_pat(Pat::Missing, Err(SyntheticSyntax))
176 fn make_pat(&mut self, pat: Pat, src: Result<PatSource, SyntheticSyntax>) -> PatId {
177 let id = self.body.pats.alloc(pat);
178 self.source_map.pat_map_back.insert(id, src);
182 fn alloc_label(&mut self, label: Label, ptr: AstPtr<ast::Label>) -> LabelId {
183 let src = self.expander.to_source(ptr);
184 let id = self.make_label(label, src.clone());
185 self.source_map.label_map.insert(src, id);
188 fn make_label(&mut self, label: Label, src: LabelSource) -> LabelId {
189 let id = self.body.labels.alloc(label);
190 self.source_map.label_map_back.insert(id, src);
194 fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
195 let syntax_ptr = AstPtr::new(&expr);
196 if self.check_cfg(&expr).is_none() {
197 return self.missing_expr();
201 ast::Expr::IfExpr(e) => {
202 let then_branch = self.collect_block_opt(e.then_branch());
204 let else_branch = e.else_branch().map(|b| match b {
205 ast::ElseBranch::Block(it) => self.collect_block(it),
206 ast::ElseBranch::IfExpr(elif) => {
207 let expr: ast::Expr = ast::Expr::cast(elif.syntax().clone()).unwrap();
208 self.collect_expr(expr)
212 let condition = match e.condition() {
213 None => self.missing_expr(),
214 Some(condition) => match condition.pat() {
215 None => self.collect_expr_opt(condition.expr()),
216 // if let -- desugar to match
218 let pat = self.collect_pat(pat);
219 let match_expr = self.collect_expr_opt(condition.expr());
220 let placeholder_pat = self.missing_pat();
222 MatchArm { pat, expr: then_branch, guard: None },
224 pat: placeholder_pat,
225 expr: else_branch.unwrap_or_else(|| self.unit()),
230 .alloc_expr(Expr::Match { expr: match_expr, arms }, syntax_ptr);
235 self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
237 ast::Expr::EffectExpr(e) => match e.effect() {
238 ast::Effect::Try(_) => {
239 let body = self.collect_block_opt(e.block_expr());
240 self.alloc_expr(Expr::TryBlock { body }, syntax_ptr)
242 ast::Effect::Unsafe(_) => {
243 let body = self.collect_block_opt(e.block_expr());
244 self.alloc_expr(Expr::Unsafe { body }, syntax_ptr)
246 // FIXME: we need to record these effects somewhere...
247 ast::Effect::Label(label) => {
248 let label = self.collect_label(label);
249 match e.block_expr() {
251 let res = self.collect_block(block);
252 match &mut self.body.exprs[res] {
253 Expr::Block { label: block_label, .. } => {
254 *block_label = Some(label);
260 None => self.missing_expr(),
263 // FIXME: we need to record these effects somewhere...
264 ast::Effect::Async(_) => {
265 let body = self.collect_block_opt(e.block_expr());
266 self.alloc_expr(Expr::Async { body }, syntax_ptr)
268 ast::Effect::Const(_) => {
269 let body = self.collect_block_opt(e.block_expr());
270 self.alloc_expr(Expr::Const { body }, syntax_ptr)
273 ast::Expr::BlockExpr(e) => self.collect_block(e),
274 ast::Expr::LoopExpr(e) => {
275 let label = e.label().map(|label| self.collect_label(label));
276 let body = self.collect_block_opt(e.loop_body());
277 self.alloc_expr(Expr::Loop { body, label }, syntax_ptr)
279 ast::Expr::WhileExpr(e) => {
280 let label = e.label().map(|label| self.collect_label(label));
281 let body = self.collect_block_opt(e.loop_body());
283 let condition = match e.condition() {
284 None => self.missing_expr(),
285 Some(condition) => match condition.pat() {
286 None => self.collect_expr_opt(condition.expr()),
287 // if let -- desugar to match
289 mark::hit!(infer_resolve_while_let);
290 let pat = self.collect_pat(pat);
291 let match_expr = self.collect_expr_opt(condition.expr());
292 let placeholder_pat = self.missing_pat();
294 self.alloc_expr_desugared(Expr::Break { expr: None, label: None });
296 MatchArm { pat, expr: body, guard: None },
297 MatchArm { pat: placeholder_pat, expr: break_, guard: None },
300 self.alloc_expr_desugared(Expr::Match { expr: match_expr, arms });
302 .alloc_expr(Expr::Loop { body: match_expr, label }, syntax_ptr);
307 self.alloc_expr(Expr::While { condition, body, label }, syntax_ptr)
309 ast::Expr::ForExpr(e) => {
310 let label = e.label().map(|label| self.collect_label(label));
311 let iterable = self.collect_expr_opt(e.iterable());
312 let pat = self.collect_pat_opt(e.pat());
313 let body = self.collect_block_opt(e.loop_body());
314 self.alloc_expr(Expr::For { iterable, pat, body, label }, syntax_ptr)
316 ast::Expr::CallExpr(e) => {
317 let callee = self.collect_expr_opt(e.expr());
318 let args = if let Some(arg_list) = e.arg_list() {
319 arg_list.args().map(|e| self.collect_expr(e)).collect()
323 self.alloc_expr(Expr::Call { callee, args }, syntax_ptr)
325 ast::Expr::MethodCallExpr(e) => {
326 let receiver = self.collect_expr_opt(e.receiver());
327 let args = if let Some(arg_list) = e.arg_list() {
328 arg_list.args().map(|e| self.collect_expr(e)).collect()
332 let method_name = e.name_ref().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
334 e.generic_arg_list().and_then(|it| GenericArgs::from_ast(&self.ctx(), it));
336 Expr::MethodCall { receiver, method_name, args, generic_args },
340 ast::Expr::MatchExpr(e) => {
341 let expr = self.collect_expr_opt(e.expr());
342 let arms = if let Some(match_arm_list) = e.match_arm_list() {
346 self.check_cfg(&arm).map(|()| MatchArm {
347 pat: self.collect_pat_opt(arm.pat()),
348 expr: self.collect_expr_opt(arm.expr()),
351 .and_then(|guard| guard.expr())
352 .map(|e| self.collect_expr(e)),
359 self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
361 ast::Expr::PathExpr(e) => {
364 .and_then(|path| self.expander.parse_path(path))
366 .unwrap_or(Expr::Missing);
367 self.alloc_expr(path, syntax_ptr)
369 ast::Expr::ContinueExpr(e) => self.alloc_expr(
370 Expr::Continue { label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
373 ast::Expr::BreakExpr(e) => {
374 let expr = e.expr().map(|e| self.collect_expr(e));
376 Expr::Break { expr, label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
380 ast::Expr::ParenExpr(e) => {
381 let inner = self.collect_expr_opt(e.expr());
382 // make the paren expr point to the inner expression as well
383 let src = self.expander.to_source(syntax_ptr);
384 self.source_map.expr_map.insert(src, inner);
387 ast::Expr::ReturnExpr(e) => {
388 let expr = e.expr().map(|e| self.collect_expr(e));
389 self.alloc_expr(Expr::Return { expr }, syntax_ptr)
391 ast::Expr::YieldExpr(e) => {
392 let expr = e.expr().map(|e| self.collect_expr(e));
393 self.alloc_expr(Expr::Yield { expr }, syntax_ptr)
395 ast::Expr::RecordExpr(e) => {
396 let path = e.path().and_then(|path| self.expander.parse_path(path));
397 let mut field_ptrs = Vec::new();
398 let record_lit = if let Some(nfl) = e.record_expr_field_list() {
401 .inspect(|field| field_ptrs.push(AstPtr::new(field)))
402 .filter_map(|field| {
403 self.check_cfg(&field)?;
405 let name = field.field_name()?.as_name();
407 Some(RecordLitField {
409 expr: match field.expr() {
410 Some(e) => self.collect_expr(e),
411 None => self.missing_expr(),
416 let spread = nfl.spread().map(|s| self.collect_expr(s));
417 Expr::RecordLit { path, fields, spread }
419 Expr::RecordLit { path, fields: Vec::new(), spread: None }
422 let res = self.alloc_expr(record_lit, syntax_ptr);
423 for (i, ptr) in field_ptrs.into_iter().enumerate() {
424 let src = self.expander.to_source(ptr);
425 self.source_map.field_map.insert((res, i), src);
429 ast::Expr::FieldExpr(e) => {
430 let expr = self.collect_expr_opt(e.expr());
431 let name = match e.field_access() {
432 Some(kind) => kind.as_name(),
433 _ => Name::missing(),
435 self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
437 ast::Expr::AwaitExpr(e) => {
438 let expr = self.collect_expr_opt(e.expr());
439 self.alloc_expr(Expr::Await { expr }, syntax_ptr)
441 ast::Expr::TryExpr(e) => {
442 let expr = self.collect_expr_opt(e.expr());
443 self.alloc_expr(Expr::Try { expr }, syntax_ptr)
445 ast::Expr::CastExpr(e) => {
446 let expr = self.collect_expr_opt(e.expr());
447 let type_ref = TypeRef::from_ast_opt(&self.ctx(), e.ty());
448 self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
450 ast::Expr::RefExpr(e) => {
451 let expr = self.collect_expr_opt(e.expr());
452 let raw_tok = e.raw_token().is_some();
453 let mutability = if raw_tok {
454 if e.mut_token().is_some() {
456 } else if e.const_token().is_some() {
459 unreachable!("parser only remaps to raw_token() if matching mutability token follows")
462 Mutability::from_mutable(e.mut_token().is_some())
464 let rawness = Rawness::from_raw(raw_tok);
465 self.alloc_expr(Expr::Ref { expr, rawness, mutability }, syntax_ptr)
467 ast::Expr::PrefixExpr(e) => {
468 let expr = self.collect_expr_opt(e.expr());
469 if let Some(op) = e.op_kind() {
470 self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr)
472 self.alloc_expr(Expr::Missing, syntax_ptr)
475 ast::Expr::ClosureExpr(e) => {
476 let mut args = Vec::new();
477 let mut arg_types = Vec::new();
478 if let Some(pl) = e.param_list() {
479 for param in pl.params() {
480 let pat = self.collect_pat_opt(param.pat());
481 let type_ref = param.ty().map(|it| TypeRef::from_ast(&self.ctx(), it));
483 arg_types.push(type_ref);
487 e.ret_type().and_then(|r| r.ty()).map(|it| TypeRef::from_ast(&self.ctx(), it));
488 let body = self.collect_expr_opt(e.body());
489 self.alloc_expr(Expr::Lambda { args, arg_types, ret_type, body }, syntax_ptr)
491 ast::Expr::BinExpr(e) => {
492 let lhs = self.collect_expr_opt(e.lhs());
493 let rhs = self.collect_expr_opt(e.rhs());
494 let op = e.op_kind().map(BinaryOp::from);
495 self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr)
497 ast::Expr::TupleExpr(e) => {
498 let exprs = e.fields().map(|expr| self.collect_expr(expr)).collect();
499 self.alloc_expr(Expr::Tuple { exprs }, syntax_ptr)
501 ast::Expr::BoxExpr(e) => {
502 let expr = self.collect_expr_opt(e.expr());
503 self.alloc_expr(Expr::Box { expr }, syntax_ptr)
506 ast::Expr::ArrayExpr(e) => {
510 ArrayExprKind::ElementList(e) => {
511 let exprs = e.map(|expr| self.collect_expr(expr)).collect();
512 self.alloc_expr(Expr::Array(Array::ElementList(exprs)), syntax_ptr)
514 ArrayExprKind::Repeat { initializer, repeat } => {
515 let initializer = self.collect_expr_opt(initializer);
516 let repeat = self.collect_expr_opt(repeat);
518 Expr::Array(Array::Repeat { initializer, repeat }),
525 ast::Expr::Literal(e) => self.alloc_expr(Expr::Literal(e.kind().into()), syntax_ptr),
526 ast::Expr::IndexExpr(e) => {
527 let base = self.collect_expr_opt(e.base());
528 let index = self.collect_expr_opt(e.index());
529 self.alloc_expr(Expr::Index { base, index }, syntax_ptr)
531 ast::Expr::RangeExpr(e) => {
532 let lhs = e.start().map(|lhs| self.collect_expr(lhs));
533 let rhs = e.end().map(|rhs| self.collect_expr(rhs));
535 Some(range_type) => {
536 self.alloc_expr(Expr::Range { lhs, rhs, range_type }, syntax_ptr)
538 None => self.alloc_expr(Expr::Missing, syntax_ptr),
541 ast::Expr::MacroCall(e) => {
542 let mut ids = vec![];
543 self.collect_macro_call(e, syntax_ptr.clone(), |this, expansion| {
544 ids.push(match expansion {
545 Some(it) => this.collect_expr(it),
546 None => this.alloc_expr(Expr::Missing, syntax_ptr.clone()),
554 fn collect_macro_call<F: FnMut(&mut Self, Option<T>), T: ast::AstNode>(
557 syntax_ptr: AstPtr<ast::Expr>,
560 // File containing the macro call. Expansion errors will be attached here.
561 let outer_file = self.expander.current_file_id;
563 let macro_call = self.expander.to_source(AstPtr::new(&e));
564 let res = self.expander.enter_expand(self.db, e);
567 Some(ExpandError::UnresolvedProcMacro) => {
568 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedProcMacro(
569 UnresolvedProcMacro {
571 node: syntax_ptr.into(),
572 precise_location: None,
578 self.source_map.diagnostics.push(BodyDiagnostic::MacroError(MacroError {
580 node: syntax_ptr.into(),
581 message: err.to_string(),
588 Some((mark, expansion)) => {
589 // FIXME: Statements are too complicated to recover from error for now.
590 // It is because we don't have any hygiene for local variable expansion right now.
591 if T::can_cast(syntax::SyntaxKind::MACRO_STMTS) && res.err.is_some() {
592 self.expander.exit(self.db, mark);
593 collector(self, None);
595 self.source_map.expansions.insert(macro_call, self.expander.current_file_id);
597 let item_tree = self.db.item_tree(self.expander.current_file_id);
598 self.item_trees.insert(self.expander.current_file_id, item_tree);
600 let id = collector(self, Some(expansion));
601 self.expander.exit(self.db, mark);
605 None => collector(self, None),
609 fn find_inner_item<N: ItemTreeNode>(&self, ast: &N::Source) -> Option<ItemTreeId<N>> {
610 let id = self.expander.ast_id(ast);
611 let tree = &self.item_trees[&id.file_id];
613 // FIXME: This probably breaks with `use` items, since they produce multiple item tree nodes
615 // Root file (non-macro).
616 let item_tree_id = tree
618 .chain(tree.top_level_items().iter().copied())
619 .filter_map(|mod_item| mod_item.downcast::<N>())
620 .find(|tree_id| tree[*tree_id].ast_id().upcast() == id.value.upcast())
623 "couldn't find inner {} item for {:?} (AST: `{}` - {:?})",
632 Some(ItemTreeId::new(id.file_id, item_tree_id))
635 fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
636 if let Some(expr) = expr {
637 self.collect_expr(expr)
643 fn collect_stmt(&mut self, s: ast::Stmt) -> Option<Vec<Statement>> {
646 ast::Stmt::LetStmt(stmt) => {
647 self.check_cfg(&stmt)?;
649 let pat = self.collect_pat_opt(stmt.pat());
650 let type_ref = stmt.ty().map(|it| TypeRef::from_ast(&self.ctx(), it));
651 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
652 vec![Statement::Let { pat, type_ref, initializer }]
654 ast::Stmt::ExprStmt(stmt) => {
655 self.check_cfg(&stmt)?;
657 // Note that macro could be expended to multiple statements
658 if let Some(ast::Expr::MacroCall(m)) = stmt.expr() {
659 let syntax_ptr = AstPtr::new(&stmt.expr().unwrap());
660 let mut stmts = vec![];
662 self.collect_macro_call(m, syntax_ptr.clone(), |this, expansion| {
665 let statements: ast::MacroStmts = expansion;
666 this.collect_stmts_items(statements.statements());
668 statements.statements().for_each(|stmt| {
669 if let Some(mut r) = this.collect_stmt(stmt) {
670 stmts.append(&mut r);
673 if let Some(expr) = statements.expr() {
674 stmts.push(Statement::Expr(this.collect_expr(expr)));
678 stmts.push(Statement::Expr(
679 this.alloc_expr(Expr::Missing, syntax_ptr.clone()),
686 vec![Statement::Expr(self.collect_expr_opt(stmt.expr()))]
689 ast::Stmt::Item(item) => {
690 self.check_cfg(&item)?;
699 fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId {
700 let ast_id = self.expander.ast_id(&block);
702 BlockLoc { ast_id, module: self.expander.def_map.module_id(self.expander.module) };
703 let block_id = self.db.intern_block(block_loc);
704 let opt_def_map = self.db.block_def_map(block_id);
705 let has_def_map = opt_def_map.is_some();
706 let def_map = opt_def_map.unwrap_or_else(|| self.expander.def_map.clone());
707 let module = if has_def_map { def_map.root() } else { self.expander.module };
708 let prev_def_map = mem::replace(&mut self.expander.def_map, def_map);
709 let prev_local_module = mem::replace(&mut self.expander.module, module);
711 self.collect_stmts_items(block.statements());
713 block.statements().filter_map(|s| self.collect_stmt(s)).flatten().collect();
714 let tail = block.tail_expr().map(|e| self.collect_expr(e));
715 let syntax_node_ptr = AstPtr::new(&block.into());
716 let expr_id = self.alloc_expr(
717 Expr::Block { id: block_id, statements, tail, label: None },
721 self.expander.def_map = prev_def_map;
722 self.expander.module = prev_local_module;
726 fn collect_stmts_items(&mut self, stmts: ast::AstChildren<ast::Stmt>) {
727 let container = ContainerId::DefWithBodyId(self.def);
730 .filter_map(|stmt| match stmt {
731 ast::Stmt::Item(it) => Some(it),
732 ast::Stmt::LetStmt(_) | ast::Stmt::ExprStmt(_) => None,
735 let (def, name): (ModuleDefId, Option<ast::Name>) = match item {
736 ast::Item::Fn(def) => {
737 let id = self.find_inner_item(&def)?;
739 FunctionLoc { container: container.into(), id }.intern(self.db).into(),
743 ast::Item::TypeAlias(def) => {
744 let id = self.find_inner_item(&def)?;
746 TypeAliasLoc { container: container.into(), id }.intern(self.db).into(),
750 ast::Item::Const(def) => {
751 let id = self.find_inner_item(&def)?;
753 ConstLoc { container: container.into(), id }.intern(self.db).into(),
757 ast::Item::Static(def) => {
758 let id = self.find_inner_item(&def)?;
759 (StaticLoc { container, id }.intern(self.db).into(), def.name())
761 ast::Item::Struct(def) => {
762 let id = self.find_inner_item(&def)?;
763 (StructLoc { container, id }.intern(self.db).into(), def.name())
765 ast::Item::Enum(def) => {
766 let id = self.find_inner_item(&def)?;
767 (EnumLoc { container, id }.intern(self.db).into(), def.name())
769 ast::Item::Union(def) => {
770 let id = self.find_inner_item(&def)?;
771 (UnionLoc { container, id }.intern(self.db).into(), def.name())
773 ast::Item::Trait(def) => {
774 let id = self.find_inner_item(&def)?;
775 (TraitLoc { container, id }.intern(self.db).into(), def.name())
777 ast::Item::ExternBlock(_) => return None, // FIXME: collect from extern blocks
780 | ast::Item::ExternCrate(_)
781 | ast::Item::Module(_)
782 | ast::Item::MacroCall(_) => return None,
783 ast::Item::MacroRules(def) => {
784 return Some(Either::Right(ast::Macro::from(def)));
786 ast::Item::MacroDef(def) => {
787 return Some(Either::Right(ast::Macro::from(def)));
791 Some(Either::Left((def, name)))
793 .collect::<Vec<_>>();
795 for either in items {
797 Either::Left((def, name)) => {
798 self.body.item_scope.define_def(def);
799 if let Some(name) = name {
800 let vis = crate::visibility::Visibility::Public; // FIXME determine correctly
801 let has_constructor = match def {
802 ModuleDefId::AdtId(AdtId::StructId(s)) => {
803 self.db.struct_data(s).variant_data.kind() != StructKind::Record
807 self.body.item_scope.push_res(
809 crate::per_ns::PerNs::from_def(def, vis, has_constructor),
813 Either::Right(e) => {
814 let mac = MacroDefId {
815 krate: self.expander.def_map.krate(),
816 ast_id: Some(self.expander.ast_id(&e)),
817 kind: MacroDefKind::Declarative,
820 if let Some(name) = e.name() {
821 self.body.item_scope.define_legacy_macro(name.as_name(), mac);
828 fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
829 if let Some(block) = expr {
830 self.collect_block(block)
836 fn collect_label(&mut self, ast_label: ast::Label) -> LabelId {
838 name: ast_label.lifetime().as_ref().map_or_else(Name::missing, Name::new_lifetime),
840 self.alloc_label(label, AstPtr::new(&ast_label))
843 fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
844 let pattern = match &pat {
845 ast::Pat::IdentPat(bp) => {
846 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
848 BindingAnnotation::new(bp.mut_token().is_some(), bp.ref_token().is_some());
849 let subpat = bp.pat().map(|subpat| self.collect_pat(subpat));
850 if annotation == BindingAnnotation::Unannotated && subpat.is_none() {
851 // This could also be a single-segment path pattern. To
852 // decide that, we need to try resolving the name.
853 let (resolved, _) = self.expander.def_map.resolve_path(
855 self.expander.module,
856 &name.clone().into(),
857 BuiltinShadowMode::Other,
859 match resolved.take_values() {
860 Some(ModuleDefId::ConstId(_)) => Pat::Path(name.into()),
861 Some(ModuleDefId::EnumVariantId(_)) => {
862 // this is only really valid for unit variants, but
863 // shadowing other enum variants with a pattern is
865 Pat::Path(name.into())
867 Some(ModuleDefId::AdtId(AdtId::StructId(s)))
868 if self.db.struct_data(s).variant_data.kind() != StructKind::Record =>
870 // Funnily enough, record structs *can* be shadowed
871 // by pattern bindings (but unit or tuple structs
873 Pat::Path(name.into())
875 // shadowing statics is an error as well, so we just ignore that case here
876 _ => Pat::Bind { name, mode: annotation, subpat },
879 Pat::Bind { name, mode: annotation, subpat }
882 ast::Pat::TupleStructPat(p) => {
883 let path = p.path().and_then(|path| self.expander.parse_path(path));
884 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
885 Pat::TupleStruct { path, args, ellipsis }
887 ast::Pat::RefPat(p) => {
888 let pat = self.collect_pat_opt(p.pat());
889 let mutability = Mutability::from_mutable(p.mut_token().is_some());
890 Pat::Ref { pat, mutability }
892 ast::Pat::PathPat(p) => {
893 let path = p.path().and_then(|path| self.expander.parse_path(path));
894 path.map(Pat::Path).unwrap_or(Pat::Missing)
896 ast::Pat::OrPat(p) => {
897 let pats = p.pats().map(|p| self.collect_pat(p)).collect();
900 ast::Pat::ParenPat(p) => return self.collect_pat_opt(p.pat()),
901 ast::Pat::TuplePat(p) => {
902 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
903 Pat::Tuple { args, ellipsis }
905 ast::Pat::WildcardPat(_) => Pat::Wild,
906 ast::Pat::RecordPat(p) => {
907 let path = p.path().and_then(|path| self.expander.parse_path(path));
909 .record_pat_field_list()
910 .expect("every struct should have a field list")
913 let ast_pat = f.pat()?;
914 let pat = self.collect_pat(ast_pat);
915 let name = f.field_name()?.as_name();
916 Some(RecordFieldPat { name, pat })
921 .record_pat_field_list()
922 .expect("every struct should have a field list")
926 Pat::Record { path, args, ellipsis }
928 ast::Pat::SlicePat(p) => {
929 let SlicePatComponents { prefix, slice, suffix } = p.components();
931 // FIXME properly handle `RestPat`
933 prefix: prefix.into_iter().map(|p| self.collect_pat(p)).collect(),
934 slice: slice.map(|p| self.collect_pat(p)),
935 suffix: suffix.into_iter().map(|p| self.collect_pat(p)).collect(),
938 ast::Pat::LiteralPat(lit) => {
939 if let Some(ast_lit) = lit.literal() {
940 let expr = Expr::Literal(ast_lit.kind().into());
941 let expr_ptr = AstPtr::new(&ast::Expr::Literal(ast_lit));
942 let expr_id = self.alloc_expr(expr, expr_ptr);
948 ast::Pat::RestPat(_) => {
949 // `RestPat` requires special handling and should not be mapped
950 // to a Pat. Here we are using `Pat::Missing` as a fallback for
951 // when `RestPat` is mapped to `Pat`, which can easily happen
952 // when the source code being analyzed has a malformed pattern
953 // which includes `..` in a place where it isn't valid.
957 ast::Pat::BoxPat(boxpat) => {
958 let inner = self.collect_pat_opt(boxpat.pat());
961 ast::Pat::ConstBlockPat(const_block_pat) => {
962 if let Some(expr) = const_block_pat.block_expr() {
963 let expr_id = self.collect_block(expr);
964 Pat::ConstBlock(expr_id)
970 ast::Pat::RangePat(_) | ast::Pat::MacroPat(_) => Pat::Missing,
972 let ptr = AstPtr::new(&pat);
973 self.alloc_pat(pattern, Either::Left(ptr))
976 fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
977 if let Some(pat) = pat {
978 self.collect_pat(pat)
984 fn collect_tuple_pat(&mut self, args: AstChildren<ast::Pat>) -> (Vec<PatId>, Option<usize>) {
985 // Find the location of the `..`, if there is one. Note that we do not
986 // consider the possibility of there being multiple `..` here.
987 let ellipsis = args.clone().position(|p| matches!(p, ast::Pat::RestPat(_)));
988 // We want to skip the `..` pattern here, since we account for it above.
990 .filter(|p| !matches!(p, ast::Pat::RestPat(_)))
991 .map(|p| self.collect_pat(p))
997 /// Returns `None` (and emits diagnostics) when `owner` if `#[cfg]`d out, and `Some(())` when
999 fn check_cfg(&mut self, owner: &dyn ast::AttrsOwner) -> Option<()> {
1000 match self.expander.parse_attrs(self.db, owner).cfg() {
1002 if self.expander.cfg_options().check(&cfg) != Some(false) {
1006 self.source_map.diagnostics.push(BodyDiagnostic::InactiveCode(InactiveCode {
1007 file: self.expander.current_file_id,
1008 node: SyntaxNodePtr::new(owner.syntax()),
1010 opts: self.expander.cfg_options().clone(),
1020 impl From<ast::BinOp> for BinaryOp {
1021 fn from(ast_op: ast::BinOp) -> Self {
1023 ast::BinOp::BooleanOr => BinaryOp::LogicOp(LogicOp::Or),
1024 ast::BinOp::BooleanAnd => BinaryOp::LogicOp(LogicOp::And),
1025 ast::BinOp::EqualityTest => BinaryOp::CmpOp(CmpOp::Eq { negated: false }),
1026 ast::BinOp::NegatedEqualityTest => BinaryOp::CmpOp(CmpOp::Eq { negated: true }),
1027 ast::BinOp::LesserEqualTest => {
1028 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less, strict: false })
1030 ast::BinOp::GreaterEqualTest => {
1031 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: false })
1033 ast::BinOp::LesserTest => {
1034 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less, strict: true })
1036 ast::BinOp::GreaterTest => {
1037 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: true })
1039 ast::BinOp::Addition => BinaryOp::ArithOp(ArithOp::Add),
1040 ast::BinOp::Multiplication => BinaryOp::ArithOp(ArithOp::Mul),
1041 ast::BinOp::Subtraction => BinaryOp::ArithOp(ArithOp::Sub),
1042 ast::BinOp::Division => BinaryOp::ArithOp(ArithOp::Div),
1043 ast::BinOp::Remainder => BinaryOp::ArithOp(ArithOp::Rem),
1044 ast::BinOp::LeftShift => BinaryOp::ArithOp(ArithOp::Shl),
1045 ast::BinOp::RightShift => BinaryOp::ArithOp(ArithOp::Shr),
1046 ast::BinOp::BitwiseXor => BinaryOp::ArithOp(ArithOp::BitXor),
1047 ast::BinOp::BitwiseOr => BinaryOp::ArithOp(ArithOp::BitOr),
1048 ast::BinOp::BitwiseAnd => BinaryOp::ArithOp(ArithOp::BitAnd),
1049 ast::BinOp::Assignment => BinaryOp::Assignment { op: None },
1050 ast::BinOp::AddAssign => BinaryOp::Assignment { op: Some(ArithOp::Add) },
1051 ast::BinOp::DivAssign => BinaryOp::Assignment { op: Some(ArithOp::Div) },
1052 ast::BinOp::MulAssign => BinaryOp::Assignment { op: Some(ArithOp::Mul) },
1053 ast::BinOp::RemAssign => BinaryOp::Assignment { op: Some(ArithOp::Rem) },
1054 ast::BinOp::ShlAssign => BinaryOp::Assignment { op: Some(ArithOp::Shl) },
1055 ast::BinOp::ShrAssign => BinaryOp::Assignment { op: Some(ArithOp::Shr) },
1056 ast::BinOp::SubAssign => BinaryOp::Assignment { op: Some(ArithOp::Sub) },
1057 ast::BinOp::BitOrAssign => BinaryOp::Assignment { op: Some(ArithOp::BitOr) },
1058 ast::BinOp::BitAndAssign => BinaryOp::Assignment { op: Some(ArithOp::BitAnd) },
1059 ast::BinOp::BitXorAssign => BinaryOp::Assignment { op: Some(ArithOp::BitXor) },
1064 impl From<ast::LiteralKind> for Literal {
1065 fn from(ast_lit_kind: ast::LiteralKind) -> Self {
1066 match ast_lit_kind {
1067 LiteralKind::IntNumber(lit) => {
1068 if let builtin @ Some(_) = lit.suffix().and_then(BuiltinFloat::from_suffix) {
1069 return Literal::Float(Default::default(), builtin);
1070 } else if let builtin @ Some(_) =
1071 lit.suffix().and_then(|it| BuiltinInt::from_suffix(&it))
1073 Literal::Int(Default::default(), builtin)
1075 let builtin = lit.suffix().and_then(|it| BuiltinUint::from_suffix(&it));
1076 Literal::Uint(Default::default(), builtin)
1079 LiteralKind::FloatNumber(lit) => {
1080 let ty = lit.suffix().and_then(|it| BuiltinFloat::from_suffix(&it));
1081 Literal::Float(Default::default(), ty)
1083 LiteralKind::ByteString(_) => Literal::ByteString(Default::default()),
1084 LiteralKind::String(_) => Literal::String(Default::default()),
1085 LiteralKind::Byte => Literal::Uint(Default::default(), Some(BuiltinUint::U8)),
1086 LiteralKind::Bool(val) => Literal::Bool(val),
1087 LiteralKind::Char => Literal::Char(Default::default()),