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,
17 self, ArgListOwner, ArrayExprKind, AstChildren, LiteralKind, LoopBodyOwner, NameOwner,
20 AstNode, AstPtr, SyntaxNodePtr,
25 body::{Body, BodySourceMap, Expander, LabelSource, PatPtr, SyntheticSyntax},
26 builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint},
28 diagnostics::{InactiveCode, MacroError, UnresolvedMacroCall, UnresolvedProcMacro},
30 dummy_expr_id, ArithOp, Array, BinaryOp, BindingAnnotation, CmpOp, Expr, ExprId, Label,
31 LabelId, Literal, LogicOp, MatchArm, Ordering, Pat, PatId, RecordFieldPat, RecordLitField,
35 item_scope::BuiltinShadowMode,
36 path::{GenericArgs, Path},
37 type_ref::{Mutability, Rawness, TypeRef},
38 AdtId, BlockLoc, ModuleDefId, UnresolvedMacro,
41 use super::{diagnostics::BodyDiagnostic, ExprSource, PatSource};
45 file_id: Option<HirFileId>,
46 source_ast_id_map: Option<Arc<AstIdMap>>,
50 pub fn new(db: &dyn DefDatabase, file_id: HirFileId) -> Self {
52 hygiene: Hygiene::new(db.upcast(), file_id),
53 file_id: Some(file_id),
54 source_ast_id_map: Some(db.ast_id_map(file_id)),
58 pub fn with_hygiene(hygiene: &Hygiene) -> Self {
59 LowerCtx { hygiene: hygiene.clone(), file_id: None, source_ast_id_map: None }
62 pub(crate) fn hygiene(&self) -> &Hygiene {
66 pub(crate) fn file_id(&self) -> HirFileId {
70 pub(crate) fn lower_path(&self, ast: ast::Path) -> Option<Path> {
71 Path::from_src(ast, self)
74 pub(crate) fn ast_id<N: AstNode>(&self, item: &N) -> Option<FileAstId<N>> {
75 self.source_ast_id_map.as_ref().map(|ast_id_map| ast_id_map.ast_id(item))
82 params: Option<ast::ParamList>,
83 body: Option<ast::Expr>,
84 ) -> (Body, BodySourceMap) {
87 source_map: BodySourceMap::default(),
89 exprs: Arena::default(),
90 pats: Arena::default(),
91 labels: Arena::default(),
93 body_expr: dummy_expr_id(),
94 block_scopes: Vec::new(),
98 statements_in_scope: Vec::new(),
100 .collect(params, body)
103 struct ExprCollector<'a> {
104 db: &'a dyn DefDatabase,
107 source_map: BodySourceMap,
108 statements_in_scope: Vec<Statement>,
111 impl ExprCollector<'_> {
114 param_list: Option<ast::ParamList>,
115 body: Option<ast::Expr>,
116 ) -> (Body, BodySourceMap) {
117 if let Some(param_list) = param_list {
118 if let Some(self_param) = param_list.self_param() {
119 let ptr = AstPtr::new(&self_param);
120 let param_pat = self.alloc_pat(
123 mode: BindingAnnotation::new(
124 self_param.mut_token().is_some() && self_param.amp_token().is_none(),
131 self.body.params.push(param_pat);
134 for param in param_list.params() {
135 let pat = match param.pat() {
139 let param_pat = self.collect_pat(pat);
140 self.body.params.push(param_pat);
144 self.body.body_expr = self.collect_expr_opt(body);
145 (self.body, self.source_map)
148 fn ctx(&self) -> LowerCtx {
149 LowerCtx::new(self.db, self.expander.current_file_id)
152 fn alloc_expr(&mut self, expr: Expr, ptr: AstPtr<ast::Expr>) -> ExprId {
153 let src = self.expander.to_source(ptr);
154 let id = self.make_expr(expr, Ok(src.clone()));
155 self.source_map.expr_map.insert(src, id);
158 // desugared exprs don't have ptr, that's wrong and should be fixed
160 fn alloc_expr_desugared(&mut self, expr: Expr) -> ExprId {
161 self.make_expr(expr, Err(SyntheticSyntax))
163 fn unit(&mut self) -> ExprId {
164 self.alloc_expr_desugared(Expr::Tuple { exprs: Vec::new() })
166 fn missing_expr(&mut self) -> ExprId {
167 self.alloc_expr_desugared(Expr::Missing)
169 fn make_expr(&mut self, expr: Expr, src: Result<ExprSource, SyntheticSyntax>) -> ExprId {
170 let id = self.body.exprs.alloc(expr);
171 self.source_map.expr_map_back.insert(id, src);
175 fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId {
176 let src = self.expander.to_source(ptr);
177 let id = self.make_pat(pat, Ok(src.clone()));
178 self.source_map.pat_map.insert(src, id);
181 fn missing_pat(&mut self) -> PatId {
182 self.make_pat(Pat::Missing, Err(SyntheticSyntax))
184 fn make_pat(&mut self, pat: Pat, src: Result<PatSource, SyntheticSyntax>) -> PatId {
185 let id = self.body.pats.alloc(pat);
186 self.source_map.pat_map_back.insert(id, src);
190 fn alloc_label(&mut self, label: Label, ptr: AstPtr<ast::Label>) -> LabelId {
191 let src = self.expander.to_source(ptr);
192 let id = self.make_label(label, src.clone());
193 self.source_map.label_map.insert(src, id);
196 fn make_label(&mut self, label: Label, src: LabelSource) -> LabelId {
197 let id = self.body.labels.alloc(label);
198 self.source_map.label_map_back.insert(id, src);
202 fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
203 self.maybe_collect_expr(expr).unwrap_or_else(|| self.missing_expr())
206 /// Returns `None` if and only if the expression is `#[cfg]`d out.
207 fn maybe_collect_expr(&mut self, expr: ast::Expr) -> Option<ExprId> {
208 let syntax_ptr = AstPtr::new(&expr);
209 self.check_cfg(&expr)?;
212 ast::Expr::IfExpr(e) => {
213 let then_branch = self.collect_block_opt(e.then_branch());
215 let else_branch = e.else_branch().map(|b| match b {
216 ast::ElseBranch::Block(it) => self.collect_block(it),
217 ast::ElseBranch::IfExpr(elif) => {
218 let expr: ast::Expr = ast::Expr::cast(elif.syntax().clone()).unwrap();
219 self.collect_expr(expr)
223 let condition = match e.condition() {
224 None => self.missing_expr(),
225 Some(condition) => match condition.pat() {
226 None => self.collect_expr_opt(condition.expr()),
227 // if let -- desugar to match
229 let pat = self.collect_pat(pat);
230 let match_expr = self.collect_expr_opt(condition.expr());
231 let placeholder_pat = self.missing_pat();
233 MatchArm { pat, expr: then_branch, guard: None },
235 pat: placeholder_pat,
236 expr: else_branch.unwrap_or_else(|| self.unit()),
241 self.alloc_expr(Expr::Match { expr: match_expr, arms }, syntax_ptr),
247 self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
249 ast::Expr::EffectExpr(e) => match e.effect() {
250 ast::Effect::Try(_) => {
251 let body = self.collect_block_opt(e.block_expr());
252 self.alloc_expr(Expr::TryBlock { body }, syntax_ptr)
254 ast::Effect::Unsafe(_) => {
255 let body = self.collect_block_opt(e.block_expr());
256 self.alloc_expr(Expr::Unsafe { body }, syntax_ptr)
258 // FIXME: we need to record these effects somewhere...
259 ast::Effect::Label(label) => {
260 let label = self.collect_label(label);
261 match e.block_expr() {
263 let res = self.collect_block(block);
264 match &mut self.body.exprs[res] {
265 Expr::Block { label: block_label, .. } => {
266 *block_label = Some(label);
272 None => self.missing_expr(),
275 // FIXME: we need to record these effects somewhere...
276 ast::Effect::Async(_) => {
277 let body = self.collect_block_opt(e.block_expr());
278 self.alloc_expr(Expr::Async { body }, syntax_ptr)
280 ast::Effect::Const(_) => {
281 let body = self.collect_block_opt(e.block_expr());
282 self.alloc_expr(Expr::Const { body }, syntax_ptr)
285 ast::Expr::BlockExpr(e) => self.collect_block(e),
286 ast::Expr::LoopExpr(e) => {
287 let label = e.label().map(|label| self.collect_label(label));
288 let body = self.collect_block_opt(e.loop_body());
289 self.alloc_expr(Expr::Loop { body, label }, syntax_ptr)
291 ast::Expr::WhileExpr(e) => {
292 let label = e.label().map(|label| self.collect_label(label));
293 let body = self.collect_block_opt(e.loop_body());
295 let condition = match e.condition() {
296 None => self.missing_expr(),
297 Some(condition) => match condition.pat() {
298 None => self.collect_expr_opt(condition.expr()),
299 // if let -- desugar to match
301 cov_mark::hit!(infer_resolve_while_let);
302 let pat = self.collect_pat(pat);
303 let match_expr = self.collect_expr_opt(condition.expr());
304 let placeholder_pat = self.missing_pat();
306 self.alloc_expr_desugared(Expr::Break { expr: None, label: None });
308 MatchArm { pat, expr: body, guard: None },
309 MatchArm { pat: placeholder_pat, expr: break_, guard: None },
312 self.alloc_expr_desugared(Expr::Match { expr: match_expr, arms });
314 self.alloc_expr(Expr::Loop { body: match_expr, label }, syntax_ptr),
320 self.alloc_expr(Expr::While { condition, body, label }, syntax_ptr)
322 ast::Expr::ForExpr(e) => {
323 let label = e.label().map(|label| self.collect_label(label));
324 let iterable = self.collect_expr_opt(e.iterable());
325 let pat = self.collect_pat_opt(e.pat());
326 let body = self.collect_block_opt(e.loop_body());
327 self.alloc_expr(Expr::For { iterable, pat, body, label }, syntax_ptr)
329 ast::Expr::CallExpr(e) => {
330 let callee = self.collect_expr_opt(e.expr());
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 self.alloc_expr(Expr::Call { callee, args }, syntax_ptr)
338 ast::Expr::MethodCallExpr(e) => {
339 let receiver = self.collect_expr_opt(e.receiver());
340 let args = if let Some(arg_list) = e.arg_list() {
341 arg_list.args().filter_map(|e| self.maybe_collect_expr(e)).collect()
345 let method_name = e.name_ref().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
348 .and_then(|it| GenericArgs::from_ast(&self.ctx(), it))
351 Expr::MethodCall { receiver, method_name, args, generic_args },
355 ast::Expr::MatchExpr(e) => {
356 let expr = self.collect_expr_opt(e.expr());
357 let arms = if let Some(match_arm_list) = e.match_arm_list() {
361 self.check_cfg(&arm).map(|()| MatchArm {
362 pat: self.collect_pat_opt(arm.pat()),
363 expr: self.collect_expr_opt(arm.expr()),
366 .and_then(|guard| guard.expr())
367 .map(|e| self.collect_expr(e)),
374 self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
376 ast::Expr::PathExpr(e) => {
379 .and_then(|path| self.expander.parse_path(path))
381 .unwrap_or(Expr::Missing);
382 self.alloc_expr(path, syntax_ptr)
384 ast::Expr::ContinueExpr(e) => self.alloc_expr(
385 Expr::Continue { label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
388 ast::Expr::BreakExpr(e) => {
389 let expr = e.expr().map(|e| self.collect_expr(e));
391 Expr::Break { expr, label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
395 ast::Expr::ParenExpr(e) => {
396 let inner = self.collect_expr_opt(e.expr());
397 // make the paren expr point to the inner expression as well
398 let src = self.expander.to_source(syntax_ptr);
399 self.source_map.expr_map.insert(src, inner);
402 ast::Expr::ReturnExpr(e) => {
403 let expr = e.expr().map(|e| self.collect_expr(e));
404 self.alloc_expr(Expr::Return { expr }, syntax_ptr)
406 ast::Expr::YieldExpr(e) => {
407 let expr = e.expr().map(|e| self.collect_expr(e));
408 self.alloc_expr(Expr::Yield { expr }, syntax_ptr)
410 ast::Expr::RecordExpr(e) => {
411 let path = e.path().and_then(|path| self.expander.parse_path(path)).map(Box::new);
412 let record_lit = if let Some(nfl) = e.record_expr_field_list() {
415 .filter_map(|field| {
416 self.check_cfg(&field)?;
418 let name = field.field_name()?.as_name();
420 let expr = match field.expr() {
421 Some(e) => self.collect_expr(e),
422 None => self.missing_expr(),
424 let src = self.expander.to_source(AstPtr::new(&field));
425 self.source_map.field_map.insert(src.clone(), expr);
426 self.source_map.field_map_back.insert(expr, src);
427 Some(RecordLitField { name, expr })
430 let spread = nfl.spread().map(|s| self.collect_expr(s));
431 Expr::RecordLit { path, fields, spread }
433 Expr::RecordLit { path, fields: Vec::new(), spread: None }
436 self.alloc_expr(record_lit, syntax_ptr)
438 ast::Expr::FieldExpr(e) => {
439 let expr = self.collect_expr_opt(e.expr());
440 let name = match e.field_access() {
441 Some(kind) => kind.as_name(),
442 _ => Name::missing(),
444 self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
446 ast::Expr::AwaitExpr(e) => {
447 let expr = self.collect_expr_opt(e.expr());
448 self.alloc_expr(Expr::Await { expr }, syntax_ptr)
450 ast::Expr::TryExpr(e) => {
451 let expr = self.collect_expr_opt(e.expr());
452 self.alloc_expr(Expr::Try { expr }, syntax_ptr)
454 ast::Expr::CastExpr(e) => {
455 let expr = self.collect_expr_opt(e.expr());
456 let type_ref = Interned::new(TypeRef::from_ast_opt(&self.ctx(), e.ty()));
457 self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
459 ast::Expr::RefExpr(e) => {
460 let expr = self.collect_expr_opt(e.expr());
461 let raw_tok = e.raw_token().is_some();
462 let mutability = if raw_tok {
463 if e.mut_token().is_some() {
465 } else if e.const_token().is_some() {
468 unreachable!("parser only remaps to raw_token() if matching mutability token follows")
471 Mutability::from_mutable(e.mut_token().is_some())
473 let rawness = Rawness::from_raw(raw_tok);
474 self.alloc_expr(Expr::Ref { expr, rawness, mutability }, syntax_ptr)
476 ast::Expr::PrefixExpr(e) => {
477 let expr = self.collect_expr_opt(e.expr());
478 if let Some(op) = e.op_kind() {
479 self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr)
481 self.alloc_expr(Expr::Missing, syntax_ptr)
484 ast::Expr::ClosureExpr(e) => {
485 let mut args = Vec::new();
486 let mut arg_types = Vec::new();
487 if let Some(pl) = e.param_list() {
488 for param in pl.params() {
489 let pat = self.collect_pat_opt(param.pat());
491 param.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
493 arg_types.push(type_ref);
498 .and_then(|r| r.ty())
499 .map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
500 let body = self.collect_expr_opt(e.body());
501 self.alloc_expr(Expr::Lambda { args, arg_types, ret_type, body }, syntax_ptr)
503 ast::Expr::BinExpr(e) => {
504 let lhs = self.collect_expr_opt(e.lhs());
505 let rhs = self.collect_expr_opt(e.rhs());
506 let op = e.op_kind().map(BinaryOp::from);
507 self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr)
509 ast::Expr::TupleExpr(e) => {
510 let exprs = e.fields().map(|expr| self.collect_expr(expr)).collect();
511 self.alloc_expr(Expr::Tuple { exprs }, syntax_ptr)
513 ast::Expr::BoxExpr(e) => {
514 let expr = self.collect_expr_opt(e.expr());
515 self.alloc_expr(Expr::Box { expr }, syntax_ptr)
518 ast::Expr::ArrayExpr(e) => {
522 ArrayExprKind::ElementList(e) => {
523 let exprs = e.map(|expr| self.collect_expr(expr)).collect();
524 self.alloc_expr(Expr::Array(Array::ElementList(exprs)), syntax_ptr)
526 ArrayExprKind::Repeat { initializer, repeat } => {
527 let initializer = self.collect_expr_opt(initializer);
528 let repeat = self.collect_expr_opt(repeat);
530 Expr::Array(Array::Repeat { initializer, repeat }),
537 ast::Expr::Literal(e) => self.alloc_expr(Expr::Literal(e.kind().into()), syntax_ptr),
538 ast::Expr::IndexExpr(e) => {
539 let base = self.collect_expr_opt(e.base());
540 let index = self.collect_expr_opt(e.index());
541 self.alloc_expr(Expr::Index { base, index }, syntax_ptr)
543 ast::Expr::RangeExpr(e) => {
544 let lhs = e.start().map(|lhs| self.collect_expr(lhs));
545 let rhs = e.end().map(|rhs| self.collect_expr(rhs));
547 Some(range_type) => {
548 self.alloc_expr(Expr::Range { lhs, rhs, range_type }, syntax_ptr)
550 None => self.alloc_expr(Expr::Missing, syntax_ptr),
553 ast::Expr::MacroCall(e) => {
554 let macro_ptr = AstPtr::new(&e);
555 let mut ids = vec![];
556 self.collect_macro_call(e, macro_ptr, true, |this, expansion| {
557 ids.push(match expansion {
558 Some(it) => this.collect_expr(it),
559 None => this.alloc_expr(Expr::Missing, syntax_ptr.clone()),
564 ast::Expr::MacroStmts(e) => {
565 e.statements().for_each(|s| self.collect_stmt(s));
568 .map(|e| self.collect_expr(e))
569 .unwrap_or_else(|| self.alloc_expr(Expr::Missing, syntax_ptr.clone()));
571 self.alloc_expr(Expr::MacroStmts { tail }, syntax_ptr)
576 fn collect_macro_call<F: FnMut(&mut Self, Option<T>), T: ast::AstNode>(
579 syntax_ptr: AstPtr<ast::MacroCall>,
580 is_error_recoverable: bool,
583 // File containing the macro call. Expansion errors will be attached here.
584 let outer_file = self.expander.current_file_id;
586 let macro_call = self.expander.to_source(AstPtr::new(&e));
587 let res = self.expander.enter_expand(self.db, e);
589 let res = match res {
591 Err(UnresolvedMacro { path }) => {
592 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall(
593 UnresolvedMacroCall {
595 node: syntax_ptr.cast().unwrap(),
599 collector(self, None);
605 Some(ExpandError::UnresolvedProcMacro) => {
606 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedProcMacro(
607 UnresolvedProcMacro {
609 node: syntax_ptr.into(),
610 precise_location: None,
616 self.source_map.diagnostics.push(BodyDiagnostic::MacroError(MacroError {
618 node: syntax_ptr.into(),
619 message: err.to_string(),
626 Some((mark, expansion)) => {
627 // FIXME: Statements are too complicated to recover from error for now.
628 // It is because we don't have any hygiene for local variable expansion right now.
629 if !is_error_recoverable && res.err.is_some() {
630 self.expander.exit(self.db, mark);
631 collector(self, None);
633 self.source_map.expansions.insert(macro_call, self.expander.current_file_id);
635 let id = collector(self, Some(expansion));
636 self.expander.exit(self.db, mark);
640 None => collector(self, None),
644 fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
645 if let Some(expr) = expr {
646 self.collect_expr(expr)
652 fn collect_stmt(&mut self, s: ast::Stmt) {
654 ast::Stmt::LetStmt(stmt) => {
655 if self.check_cfg(&stmt).is_none() {
658 let pat = self.collect_pat_opt(stmt.pat());
660 stmt.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
661 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
662 self.statements_in_scope.push(Statement::Let { pat, type_ref, initializer });
664 ast::Stmt::ExprStmt(stmt) => {
665 if self.check_cfg(&stmt).is_none() {
668 let has_semi = stmt.semicolon_token().is_some();
669 // Note that macro could be expended to multiple statements
670 if let Some(ast::Expr::MacroCall(m)) = stmt.expr() {
671 let macro_ptr = AstPtr::new(&m);
672 let syntax_ptr = AstPtr::new(&stmt.expr().unwrap());
674 self.collect_macro_call(
678 |this, expansion| match expansion {
680 let statements: ast::MacroStmts = expansion;
682 statements.statements().for_each(|stmt| this.collect_stmt(stmt));
683 if let Some(expr) = statements.expr() {
684 let expr = this.collect_expr(expr);
685 this.statements_in_scope
686 .push(Statement::Expr { expr, has_semi });
690 let expr = this.alloc_expr(Expr::Missing, syntax_ptr.clone());
691 this.statements_in_scope.push(Statement::Expr { expr, has_semi });
696 let expr = self.collect_expr_opt(stmt.expr());
697 self.statements_in_scope.push(Statement::Expr { expr, has_semi });
700 ast::Stmt::Item(item) => {
701 if self.check_cfg(&item).is_none() {
708 fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId {
709 let ast_id = self.expander.ast_id(&block);
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);
723 let prev_statements = std::mem::take(&mut self.statements_in_scope);
725 block.statements().for_each(|s| self.collect_stmt(s));
726 block.tail_expr().and_then(|e| {
727 let expr = self.maybe_collect_expr(e)?;
728 Some(self.statements_in_scope.push(Statement::Expr { expr, has_semi: false }))
732 if let Some(Statement::Expr { expr, has_semi: false }) = self.statements_in_scope.last() {
734 self.statements_in_scope.pop();
737 let statements = std::mem::replace(&mut self.statements_in_scope, prev_statements);
738 let syntax_node_ptr = AstPtr::new(&block.into());
739 let expr_id = self.alloc_expr(
740 Expr::Block { id: block_id, statements, tail, label: None },
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 {
750 if let Some(block) = expr {
751 self.collect_block(block)
757 fn collect_label(&mut self, ast_label: ast::Label) -> LabelId {
759 name: ast_label.lifetime().as_ref().map_or_else(Name::missing, Name::new_lifetime),
761 self.alloc_label(label, AstPtr::new(&ast_label))
764 fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
765 let pattern = match &pat {
766 ast::Pat::IdentPat(bp) => {
767 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
769 BindingAnnotation::new(bp.mut_token().is_some(), bp.ref_token().is_some());
770 let subpat = bp.pat().map(|subpat| self.collect_pat(subpat));
771 if annotation == BindingAnnotation::Unannotated && subpat.is_none() {
772 // This could also be a single-segment path pattern. To
773 // decide that, we need to try resolving the name.
774 let (resolved, _) = self.expander.def_map.resolve_path(
776 self.expander.module,
777 &name.clone().into(),
778 BuiltinShadowMode::Other,
780 match resolved.take_values() {
781 Some(ModuleDefId::ConstId(_)) => Pat::Path(name.into()),
782 Some(ModuleDefId::EnumVariantId(_)) => {
783 // this is only really valid for unit variants, but
784 // shadowing other enum variants with a pattern is
786 Pat::Path(name.into())
788 Some(ModuleDefId::AdtId(AdtId::StructId(s)))
789 if self.db.struct_data(s).variant_data.kind() != StructKind::Record =>
791 // Funnily enough, record structs *can* be shadowed
792 // by pattern bindings (but unit or tuple structs
794 Pat::Path(name.into())
796 // shadowing statics is an error as well, so we just ignore that case here
797 _ => Pat::Bind { name, mode: annotation, subpat },
800 Pat::Bind { name, mode: annotation, subpat }
803 ast::Pat::TupleStructPat(p) => {
804 let path = p.path().and_then(|path| self.expander.parse_path(path)).map(Box::new);
805 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
806 Pat::TupleStruct { path, args, ellipsis }
808 ast::Pat::RefPat(p) => {
809 let pat = self.collect_pat_opt(p.pat());
810 let mutability = Mutability::from_mutable(p.mut_token().is_some());
811 Pat::Ref { pat, mutability }
813 ast::Pat::PathPat(p) => {
814 let path = p.path().and_then(|path| self.expander.parse_path(path)).map(Box::new);
815 path.map(Pat::Path).unwrap_or(Pat::Missing)
817 ast::Pat::OrPat(p) => {
818 let pats = p.pats().map(|p| self.collect_pat(p)).collect();
821 ast::Pat::ParenPat(p) => return self.collect_pat_opt(p.pat()),
822 ast::Pat::TuplePat(p) => {
823 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
824 Pat::Tuple { args, ellipsis }
826 ast::Pat::WildcardPat(_) => Pat::Wild,
827 ast::Pat::RecordPat(p) => {
828 let path = p.path().and_then(|path| self.expander.parse_path(path)).map(Box::new);
830 .record_pat_field_list()
831 .expect("every struct should have a field list")
834 let ast_pat = f.pat()?;
835 let pat = self.collect_pat(ast_pat);
836 let name = f.field_name()?.as_name();
837 Some(RecordFieldPat { name, pat })
842 .record_pat_field_list()
843 .expect("every struct should have a field list")
847 Pat::Record { path, args, ellipsis }
849 ast::Pat::SlicePat(p) => {
850 let SlicePatComponents { prefix, slice, suffix } = p.components();
852 // FIXME properly handle `RestPat`
854 prefix: prefix.into_iter().map(|p| self.collect_pat(p)).collect(),
855 slice: slice.map(|p| self.collect_pat(p)),
856 suffix: suffix.into_iter().map(|p| self.collect_pat(p)).collect(),
859 ast::Pat::LiteralPat(lit) => {
860 if let Some(ast_lit) = lit.literal() {
861 let expr = Expr::Literal(ast_lit.kind().into());
862 let expr_ptr = AstPtr::new(&ast::Expr::Literal(ast_lit));
863 let expr_id = self.alloc_expr(expr, expr_ptr);
869 ast::Pat::RestPat(_) => {
870 // `RestPat` requires special handling and should not be mapped
871 // to a Pat. Here we are using `Pat::Missing` as a fallback for
872 // when `RestPat` is mapped to `Pat`, which can easily happen
873 // when the source code being analyzed has a malformed pattern
874 // which includes `..` in a place where it isn't valid.
878 ast::Pat::BoxPat(boxpat) => {
879 let inner = self.collect_pat_opt(boxpat.pat());
882 ast::Pat::ConstBlockPat(const_block_pat) => {
883 if let Some(expr) = const_block_pat.block_expr() {
884 let expr_id = self.collect_block(expr);
885 Pat::ConstBlock(expr_id)
890 ast::Pat::MacroPat(mac) => match mac.macro_call() {
892 let macro_ptr = AstPtr::new(&call);
894 self.collect_macro_call(call, macro_ptr, true, |this, expanded_pat| {
895 pat = Some(this.collect_pat_opt(expanded_pat));
899 Some(pat) => return pat,
900 None => Pat::Missing,
903 None => Pat::Missing,
906 ast::Pat::RangePat(_) => Pat::Missing,
908 let ptr = AstPtr::new(&pat);
909 self.alloc_pat(pattern, Either::Left(ptr))
912 fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
913 if let Some(pat) = pat {
914 self.collect_pat(pat)
920 fn collect_tuple_pat(&mut self, args: AstChildren<ast::Pat>) -> (Vec<PatId>, Option<usize>) {
921 // Find the location of the `..`, if there is one. Note that we do not
922 // consider the possibility of there being multiple `..` here.
923 let ellipsis = args.clone().position(|p| matches!(p, ast::Pat::RestPat(_)));
924 // We want to skip the `..` pattern here, since we account for it above.
926 .filter(|p| !matches!(p, ast::Pat::RestPat(_)))
927 .map(|p| self.collect_pat(p))
933 /// Returns `None` (and emits diagnostics) when `owner` if `#[cfg]`d out, and `Some(())` when
935 fn check_cfg(&mut self, owner: &dyn ast::AttrsOwner) -> Option<()> {
936 match self.expander.parse_attrs(self.db, owner).cfg() {
938 if self.expander.cfg_options().check(&cfg) != Some(false) {
942 self.source_map.diagnostics.push(BodyDiagnostic::InactiveCode(InactiveCode {
943 file: self.expander.current_file_id,
944 node: SyntaxNodePtr::new(owner.syntax()),
946 opts: self.expander.cfg_options().clone(),
956 impl From<ast::BinOp> for BinaryOp {
957 fn from(ast_op: ast::BinOp) -> Self {
959 ast::BinOp::BooleanOr => BinaryOp::LogicOp(LogicOp::Or),
960 ast::BinOp::BooleanAnd => BinaryOp::LogicOp(LogicOp::And),
961 ast::BinOp::EqualityTest => BinaryOp::CmpOp(CmpOp::Eq { negated: false }),
962 ast::BinOp::NegatedEqualityTest => BinaryOp::CmpOp(CmpOp::Eq { negated: true }),
963 ast::BinOp::LesserEqualTest => {
964 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less, strict: false })
966 ast::BinOp::GreaterEqualTest => {
967 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: false })
969 ast::BinOp::LesserTest => {
970 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less, strict: true })
972 ast::BinOp::GreaterTest => {
973 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: true })
975 ast::BinOp::Addition => BinaryOp::ArithOp(ArithOp::Add),
976 ast::BinOp::Multiplication => BinaryOp::ArithOp(ArithOp::Mul),
977 ast::BinOp::Subtraction => BinaryOp::ArithOp(ArithOp::Sub),
978 ast::BinOp::Division => BinaryOp::ArithOp(ArithOp::Div),
979 ast::BinOp::Remainder => BinaryOp::ArithOp(ArithOp::Rem),
980 ast::BinOp::LeftShift => BinaryOp::ArithOp(ArithOp::Shl),
981 ast::BinOp::RightShift => BinaryOp::ArithOp(ArithOp::Shr),
982 ast::BinOp::BitwiseXor => BinaryOp::ArithOp(ArithOp::BitXor),
983 ast::BinOp::BitwiseOr => BinaryOp::ArithOp(ArithOp::BitOr),
984 ast::BinOp::BitwiseAnd => BinaryOp::ArithOp(ArithOp::BitAnd),
985 ast::BinOp::Assignment => BinaryOp::Assignment { op: None },
986 ast::BinOp::AddAssign => BinaryOp::Assignment { op: Some(ArithOp::Add) },
987 ast::BinOp::DivAssign => BinaryOp::Assignment { op: Some(ArithOp::Div) },
988 ast::BinOp::MulAssign => BinaryOp::Assignment { op: Some(ArithOp::Mul) },
989 ast::BinOp::RemAssign => BinaryOp::Assignment { op: Some(ArithOp::Rem) },
990 ast::BinOp::ShlAssign => BinaryOp::Assignment { op: Some(ArithOp::Shl) },
991 ast::BinOp::ShrAssign => BinaryOp::Assignment { op: Some(ArithOp::Shr) },
992 ast::BinOp::SubAssign => BinaryOp::Assignment { op: Some(ArithOp::Sub) },
993 ast::BinOp::BitOrAssign => BinaryOp::Assignment { op: Some(ArithOp::BitOr) },
994 ast::BinOp::BitAndAssign => BinaryOp::Assignment { op: Some(ArithOp::BitAnd) },
995 ast::BinOp::BitXorAssign => BinaryOp::Assignment { op: Some(ArithOp::BitXor) },
1000 impl From<ast::LiteralKind> for Literal {
1001 fn from(ast_lit_kind: ast::LiteralKind) -> Self {
1002 match ast_lit_kind {
1003 LiteralKind::IntNumber(lit) => {
1004 if let builtin @ Some(_) = lit.suffix().and_then(BuiltinFloat::from_suffix) {
1005 return Literal::Float(Default::default(), builtin);
1006 } else if let builtin @ Some(_) =
1007 lit.suffix().and_then(|it| BuiltinInt::from_suffix(&it))
1009 Literal::Int(Default::default(), builtin)
1011 let builtin = lit.suffix().and_then(|it| BuiltinUint::from_suffix(&it));
1012 Literal::Uint(Default::default(), builtin)
1015 LiteralKind::FloatNumber(lit) => {
1016 let ty = lit.suffix().and_then(|it| BuiltinFloat::from_suffix(&it));
1017 Literal::Float(Default::default(), ty)
1019 LiteralKind::ByteString(_) => Literal::ByteString(Default::default()),
1020 LiteralKind::String(_) => Literal::String(Default::default()),
1021 LiteralKind::Byte => Literal::Uint(Default::default(), Some(BuiltinUint::U8)),
1022 LiteralKind::Bool(val) => Literal::Bool(val),
1023 LiteralKind::Char => Literal::Char(Default::default()),