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, ArgListOwner, ArrayExprKind, AstChildren, LiteralKind, LoopBodyOwner, NameOwner,
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, 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 pub struct LowerCtx<'a> {
42 pub db: &'a dyn DefDatabase,
44 file_id: Option<HirFileId>,
45 source_ast_id_map: Option<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 file_id: Some(file_id),
54 source_ast_id_map: Some(db.ast_id_map(file_id)),
58 pub fn with_hygiene(db: &'a dyn DefDatabase, hygiene: &Hygiene) -> Self {
59 LowerCtx { db, 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(self.db, 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) => {
412 e.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
413 let record_lit = if let Some(nfl) = e.record_expr_field_list() {
416 .filter_map(|field| {
417 self.check_cfg(&field)?;
419 let name = field.field_name()?.as_name();
421 let expr = match field.expr() {
422 Some(e) => self.collect_expr(e),
423 None => self.missing_expr(),
425 let src = self.expander.to_source(AstPtr::new(&field));
426 self.source_map.field_map.insert(src.clone(), expr);
427 self.source_map.field_map_back.insert(expr, src);
428 Some(RecordLitField { name, expr })
431 let spread = nfl.spread().map(|s| self.collect_expr(s));
432 Expr::RecordLit { path, fields, spread }
434 Expr::RecordLit { path, fields: Vec::new(), spread: None }
437 self.alloc_expr(record_lit, syntax_ptr)
439 ast::Expr::FieldExpr(e) => {
440 let expr = self.collect_expr_opt(e.expr());
441 let name = match e.field_access() {
442 Some(kind) => kind.as_name(),
443 _ => Name::missing(),
445 self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
447 ast::Expr::AwaitExpr(e) => {
448 let expr = self.collect_expr_opt(e.expr());
449 self.alloc_expr(Expr::Await { expr }, syntax_ptr)
451 ast::Expr::TryExpr(e) => {
452 let expr = self.collect_expr_opt(e.expr());
453 self.alloc_expr(Expr::Try { expr }, syntax_ptr)
455 ast::Expr::CastExpr(e) => {
456 let expr = self.collect_expr_opt(e.expr());
457 let type_ref = Interned::new(TypeRef::from_ast_opt(&self.ctx(), e.ty()));
458 self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
460 ast::Expr::RefExpr(e) => {
461 let expr = self.collect_expr_opt(e.expr());
462 let raw_tok = e.raw_token().is_some();
463 let mutability = if raw_tok {
464 if e.mut_token().is_some() {
466 } else if e.const_token().is_some() {
469 unreachable!("parser only remaps to raw_token() if matching mutability token follows")
472 Mutability::from_mutable(e.mut_token().is_some())
474 let rawness = Rawness::from_raw(raw_tok);
475 self.alloc_expr(Expr::Ref { expr, rawness, mutability }, syntax_ptr)
477 ast::Expr::PrefixExpr(e) => {
478 let expr = self.collect_expr_opt(e.expr());
479 if let Some(op) = e.op_kind() {
480 self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr)
482 self.alloc_expr(Expr::Missing, syntax_ptr)
485 ast::Expr::ClosureExpr(e) => {
486 let mut args = Vec::new();
487 let mut arg_types = Vec::new();
488 if let Some(pl) = e.param_list() {
489 for param in pl.params() {
490 let pat = self.collect_pat_opt(param.pat());
492 param.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
494 arg_types.push(type_ref);
499 .and_then(|r| r.ty())
500 .map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
501 let body = self.collect_expr_opt(e.body());
502 self.alloc_expr(Expr::Lambda { args, arg_types, ret_type, body }, syntax_ptr)
504 ast::Expr::BinExpr(e) => {
505 let lhs = self.collect_expr_opt(e.lhs());
506 let rhs = self.collect_expr_opt(e.rhs());
507 let op = e.op_kind().map(BinaryOp::from);
508 self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr)
510 ast::Expr::TupleExpr(e) => {
511 let exprs = e.fields().map(|expr| self.collect_expr(expr)).collect();
512 self.alloc_expr(Expr::Tuple { exprs }, syntax_ptr)
514 ast::Expr::BoxExpr(e) => {
515 let expr = self.collect_expr_opt(e.expr());
516 self.alloc_expr(Expr::Box { expr }, syntax_ptr)
519 ast::Expr::ArrayExpr(e) => {
523 ArrayExprKind::ElementList(e) => {
524 let exprs = e.map(|expr| self.collect_expr(expr)).collect();
525 self.alloc_expr(Expr::Array(Array::ElementList(exprs)), syntax_ptr)
527 ArrayExprKind::Repeat { initializer, repeat } => {
528 let initializer = self.collect_expr_opt(initializer);
529 let repeat = self.collect_expr_opt(repeat);
531 Expr::Array(Array::Repeat { initializer, repeat }),
538 ast::Expr::Literal(e) => self.alloc_expr(Expr::Literal(e.kind().into()), syntax_ptr),
539 ast::Expr::IndexExpr(e) => {
540 let base = self.collect_expr_opt(e.base());
541 let index = self.collect_expr_opt(e.index());
542 self.alloc_expr(Expr::Index { base, index }, syntax_ptr)
544 ast::Expr::RangeExpr(e) => {
545 let lhs = e.start().map(|lhs| self.collect_expr(lhs));
546 let rhs = e.end().map(|rhs| self.collect_expr(rhs));
548 Some(range_type) => {
549 self.alloc_expr(Expr::Range { lhs, rhs, range_type }, syntax_ptr)
551 None => self.alloc_expr(Expr::Missing, syntax_ptr),
554 ast::Expr::MacroCall(e) => {
555 let macro_ptr = AstPtr::new(&e);
556 let mut ids = vec![];
557 self.collect_macro_call(e, macro_ptr, true, |this, expansion| {
558 ids.push(match expansion {
559 Some(it) => this.collect_expr(it),
560 None => this.alloc_expr(Expr::Missing, syntax_ptr.clone()),
565 ast::Expr::MacroStmts(e) => {
566 e.statements().for_each(|s| self.collect_stmt(s));
569 .map(|e| self.collect_expr(e))
570 .unwrap_or_else(|| self.alloc_expr(Expr::Missing, syntax_ptr.clone()));
572 self.alloc_expr(Expr::MacroStmts { tail }, syntax_ptr)
577 fn collect_macro_call<F: FnMut(&mut Self, Option<T>), T: ast::AstNode>(
580 syntax_ptr: AstPtr<ast::MacroCall>,
581 is_error_recoverable: bool,
584 // File containing the macro call. Expansion errors will be attached here.
585 let outer_file = self.expander.current_file_id;
587 let macro_call = self.expander.to_source(AstPtr::new(&e));
588 let res = self.expander.enter_expand(self.db, e);
590 let res = match res {
592 Err(UnresolvedMacro { path }) => {
593 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall {
594 node: InFile::new(outer_file, syntax_ptr),
597 collector(self, None);
603 Some(ExpandError::UnresolvedProcMacro) => {
604 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedProcMacro {
605 node: InFile::new(outer_file, syntax_ptr),
609 self.source_map.diagnostics.push(BodyDiagnostic::MacroError {
610 node: InFile::new(outer_file, syntax_ptr),
611 message: err.to_string(),
618 Some((mark, expansion)) => {
619 // FIXME: Statements are too complicated to recover from error for now.
620 // It is because we don't have any hygiene for local variable expansion right now.
621 if !is_error_recoverable && res.err.is_some() {
622 self.expander.exit(self.db, mark);
623 collector(self, None);
625 self.source_map.expansions.insert(macro_call, self.expander.current_file_id);
627 let id = collector(self, Some(expansion));
628 self.expander.exit(self.db, mark);
632 None => collector(self, None),
636 fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
637 if let Some(expr) = expr {
638 self.collect_expr(expr)
644 fn collect_stmt(&mut self, s: ast::Stmt) {
646 ast::Stmt::LetStmt(stmt) => {
647 if self.check_cfg(&stmt).is_none() {
650 let pat = self.collect_pat_opt(stmt.pat());
652 stmt.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
653 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
654 self.statements_in_scope.push(Statement::Let { pat, type_ref, initializer });
656 ast::Stmt::ExprStmt(stmt) => {
657 if self.check_cfg(&stmt).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(
670 |this, expansion| match expansion {
672 let statements: ast::MacroStmts = expansion;
674 statements.statements().for_each(|stmt| this.collect_stmt(stmt));
675 if let Some(expr) = statements.expr() {
676 let expr = this.collect_expr(expr);
677 this.statements_in_scope
678 .push(Statement::Expr { expr, has_semi });
682 let expr = this.alloc_expr(Expr::Missing, syntax_ptr.clone());
683 this.statements_in_scope.push(Statement::Expr { expr, has_semi });
688 let expr = self.collect_expr_opt(stmt.expr());
689 self.statements_in_scope.push(Statement::Expr { expr, has_semi });
692 ast::Stmt::Item(item) => {
693 if self.check_cfg(&item).is_none() {
700 fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId {
701 let ast_id = self.expander.ast_id(&block);
703 BlockLoc { ast_id, module: self.expander.def_map.module_id(self.expander.module) };
704 let block_id = self.db.intern_block(block_loc);
706 let (module, def_map) = match self.db.block_def_map(block_id) {
708 self.body.block_scopes.push(block_id);
709 (def_map.root(), def_map)
711 None => (self.expander.module, self.expander.def_map.clone()),
713 let prev_def_map = mem::replace(&mut self.expander.def_map, def_map);
714 let prev_local_module = mem::replace(&mut self.expander.module, module);
715 let prev_statements = std::mem::take(&mut self.statements_in_scope);
717 block.statements().for_each(|s| self.collect_stmt(s));
718 block.tail_expr().and_then(|e| {
719 let expr = self.maybe_collect_expr(e)?;
720 Some(self.statements_in_scope.push(Statement::Expr { expr, has_semi: false }))
724 if let Some(Statement::Expr { expr, has_semi: false }) = self.statements_in_scope.last() {
726 self.statements_in_scope.pop();
729 let statements = std::mem::replace(&mut self.statements_in_scope, prev_statements);
730 let syntax_node_ptr = AstPtr::new(&block.into());
731 let expr_id = self.alloc_expr(
732 Expr::Block { id: block_id, statements, tail, label: None },
736 self.expander.def_map = prev_def_map;
737 self.expander.module = prev_local_module;
741 fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
742 if let Some(block) = expr {
743 self.collect_block(block)
749 fn collect_label(&mut self, ast_label: ast::Label) -> LabelId {
751 name: ast_label.lifetime().as_ref().map_or_else(Name::missing, Name::new_lifetime),
753 self.alloc_label(label, AstPtr::new(&ast_label))
756 fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
757 let pattern = match &pat {
758 ast::Pat::IdentPat(bp) => {
759 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
761 BindingAnnotation::new(bp.mut_token().is_some(), bp.ref_token().is_some());
762 let subpat = bp.pat().map(|subpat| self.collect_pat(subpat));
763 if annotation == BindingAnnotation::Unannotated && subpat.is_none() {
764 // This could also be a single-segment path pattern. To
765 // decide that, we need to try resolving the name.
766 let (resolved, _) = self.expander.def_map.resolve_path(
768 self.expander.module,
769 &name.clone().into(),
770 BuiltinShadowMode::Other,
772 match resolved.take_values() {
773 Some(ModuleDefId::ConstId(_)) => Pat::Path(name.into()),
774 Some(ModuleDefId::EnumVariantId(_)) => {
775 // this is only really valid for unit variants, but
776 // shadowing other enum variants with a pattern is
778 Pat::Path(name.into())
780 Some(ModuleDefId::AdtId(AdtId::StructId(s)))
781 if self.db.struct_data(s).variant_data.kind() != StructKind::Record =>
783 // Funnily enough, record structs *can* be shadowed
784 // by pattern bindings (but unit or tuple structs
786 Pat::Path(name.into())
788 // shadowing statics is an error as well, so we just ignore that case here
789 _ => Pat::Bind { name, mode: annotation, subpat },
792 Pat::Bind { name, mode: annotation, subpat }
795 ast::Pat::TupleStructPat(p) => {
797 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
798 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
799 Pat::TupleStruct { path, args, ellipsis }
801 ast::Pat::RefPat(p) => {
802 let pat = self.collect_pat_opt(p.pat());
803 let mutability = Mutability::from_mutable(p.mut_token().is_some());
804 Pat::Ref { pat, mutability }
806 ast::Pat::PathPat(p) => {
808 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
809 path.map(Pat::Path).unwrap_or(Pat::Missing)
811 ast::Pat::OrPat(p) => {
812 let pats = p.pats().map(|p| self.collect_pat(p)).collect();
815 ast::Pat::ParenPat(p) => return self.collect_pat_opt(p.pat()),
816 ast::Pat::TuplePat(p) => {
817 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
818 Pat::Tuple { args, ellipsis }
820 ast::Pat::WildcardPat(_) => Pat::Wild,
821 ast::Pat::RecordPat(p) => {
823 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
825 .record_pat_field_list()
826 .expect("every struct should have a field list")
829 let ast_pat = f.pat()?;
830 let pat = self.collect_pat(ast_pat);
831 let name = f.field_name()?.as_name();
832 Some(RecordFieldPat { name, pat })
837 .record_pat_field_list()
838 .expect("every struct should have a field list")
842 Pat::Record { path, args, ellipsis }
844 ast::Pat::SlicePat(p) => {
845 let SlicePatComponents { prefix, slice, suffix } = p.components();
847 // FIXME properly handle `RestPat`
849 prefix: prefix.into_iter().map(|p| self.collect_pat(p)).collect(),
850 slice: slice.map(|p| self.collect_pat(p)),
851 suffix: suffix.into_iter().map(|p| self.collect_pat(p)).collect(),
854 ast::Pat::LiteralPat(lit) => {
855 if let Some(ast_lit) = lit.literal() {
856 let expr = Expr::Literal(ast_lit.kind().into());
857 let expr_ptr = AstPtr::new(&ast::Expr::Literal(ast_lit));
858 let expr_id = self.alloc_expr(expr, expr_ptr);
864 ast::Pat::RestPat(_) => {
865 // `RestPat` requires special handling and should not be mapped
866 // to a Pat. Here we are using `Pat::Missing` as a fallback for
867 // when `RestPat` is mapped to `Pat`, which can easily happen
868 // when the source code being analyzed has a malformed pattern
869 // which includes `..` in a place where it isn't valid.
873 ast::Pat::BoxPat(boxpat) => {
874 let inner = self.collect_pat_opt(boxpat.pat());
877 ast::Pat::ConstBlockPat(const_block_pat) => {
878 if let Some(expr) = const_block_pat.block_expr() {
879 let expr_id = self.collect_block(expr);
880 Pat::ConstBlock(expr_id)
885 ast::Pat::MacroPat(mac) => match mac.macro_call() {
887 let macro_ptr = AstPtr::new(&call);
889 self.collect_macro_call(call, macro_ptr, true, |this, expanded_pat| {
890 pat = Some(this.collect_pat_opt(expanded_pat));
894 Some(pat) => return pat,
895 None => Pat::Missing,
898 None => Pat::Missing,
901 ast::Pat::RangePat(_) => Pat::Missing,
903 let ptr = AstPtr::new(&pat);
904 self.alloc_pat(pattern, Either::Left(ptr))
907 fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
908 if let Some(pat) = pat {
909 self.collect_pat(pat)
915 fn collect_tuple_pat(&mut self, args: AstChildren<ast::Pat>) -> (Vec<PatId>, Option<usize>) {
916 // Find the location of the `..`, if there is one. Note that we do not
917 // consider the possibility of there being multiple `..` here.
918 let ellipsis = args.clone().position(|p| matches!(p, ast::Pat::RestPat(_)));
919 // We want to skip the `..` pattern here, since we account for it above.
921 .filter(|p| !matches!(p, ast::Pat::RestPat(_)))
922 .map(|p| self.collect_pat(p))
928 /// Returns `None` (and emits diagnostics) when `owner` if `#[cfg]`d out, and `Some(())` when
930 fn check_cfg(&mut self, owner: &dyn ast::AttrsOwner) -> Option<()> {
931 match self.expander.parse_attrs(self.db, owner).cfg() {
933 if self.expander.cfg_options().check(&cfg) != Some(false) {
937 self.source_map.diagnostics.push(BodyDiagnostic::InactiveCode {
939 self.expander.current_file_id,
940 SyntaxNodePtr::new(owner.syntax()),
943 opts: self.expander.cfg_options().clone(),
953 impl From<ast::BinOp> for BinaryOp {
954 fn from(ast_op: ast::BinOp) -> Self {
956 ast::BinOp::BooleanOr => BinaryOp::LogicOp(LogicOp::Or),
957 ast::BinOp::BooleanAnd => BinaryOp::LogicOp(LogicOp::And),
958 ast::BinOp::EqualityTest => BinaryOp::CmpOp(CmpOp::Eq { negated: false }),
959 ast::BinOp::NegatedEqualityTest => BinaryOp::CmpOp(CmpOp::Eq { negated: true }),
960 ast::BinOp::LesserEqualTest => {
961 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less, strict: false })
963 ast::BinOp::GreaterEqualTest => {
964 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: false })
966 ast::BinOp::LesserTest => {
967 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less, strict: true })
969 ast::BinOp::GreaterTest => {
970 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: true })
972 ast::BinOp::Addition => BinaryOp::ArithOp(ArithOp::Add),
973 ast::BinOp::Multiplication => BinaryOp::ArithOp(ArithOp::Mul),
974 ast::BinOp::Subtraction => BinaryOp::ArithOp(ArithOp::Sub),
975 ast::BinOp::Division => BinaryOp::ArithOp(ArithOp::Div),
976 ast::BinOp::Remainder => BinaryOp::ArithOp(ArithOp::Rem),
977 ast::BinOp::LeftShift => BinaryOp::ArithOp(ArithOp::Shl),
978 ast::BinOp::RightShift => BinaryOp::ArithOp(ArithOp::Shr),
979 ast::BinOp::BitwiseXor => BinaryOp::ArithOp(ArithOp::BitXor),
980 ast::BinOp::BitwiseOr => BinaryOp::ArithOp(ArithOp::BitOr),
981 ast::BinOp::BitwiseAnd => BinaryOp::ArithOp(ArithOp::BitAnd),
982 ast::BinOp::Assignment => BinaryOp::Assignment { op: None },
983 ast::BinOp::AddAssign => BinaryOp::Assignment { op: Some(ArithOp::Add) },
984 ast::BinOp::DivAssign => BinaryOp::Assignment { op: Some(ArithOp::Div) },
985 ast::BinOp::MulAssign => BinaryOp::Assignment { op: Some(ArithOp::Mul) },
986 ast::BinOp::RemAssign => BinaryOp::Assignment { op: Some(ArithOp::Rem) },
987 ast::BinOp::ShlAssign => BinaryOp::Assignment { op: Some(ArithOp::Shl) },
988 ast::BinOp::ShrAssign => BinaryOp::Assignment { op: Some(ArithOp::Shr) },
989 ast::BinOp::SubAssign => BinaryOp::Assignment { op: Some(ArithOp::Sub) },
990 ast::BinOp::BitOrAssign => BinaryOp::Assignment { op: Some(ArithOp::BitOr) },
991 ast::BinOp::BitAndAssign => BinaryOp::Assignment { op: Some(ArithOp::BitAnd) },
992 ast::BinOp::BitXorAssign => BinaryOp::Assignment { op: Some(ArithOp::BitXor) },
997 impl From<ast::LiteralKind> for Literal {
998 fn from(ast_lit_kind: ast::LiteralKind) -> Self {
1000 // FIXME: these should have actual values filled in, but unsure on perf impact
1001 LiteralKind::IntNumber(lit) => {
1002 if let builtin @ Some(_) = lit.suffix().and_then(BuiltinFloat::from_suffix) {
1003 Literal::Float(Default::default(), builtin)
1004 } else if let builtin @ Some(_) =
1005 lit.suffix().and_then(|it| BuiltinInt::from_suffix(it))
1007 Literal::Int(lit.value().unwrap_or(0) as i128, builtin)
1009 let builtin = lit.suffix().and_then(|it| BuiltinUint::from_suffix(it));
1010 Literal::Uint(lit.value().unwrap_or(0), builtin)
1013 LiteralKind::FloatNumber(lit) => {
1014 let ty = lit.suffix().and_then(|it| BuiltinFloat::from_suffix(it));
1015 Literal::Float(Default::default(), ty)
1017 LiteralKind::ByteString(bs) => {
1018 let text = bs.value().map(Vec::from).unwrap_or_else(Default::default);
1019 Literal::ByteString(text)
1021 LiteralKind::String(_) => Literal::String(Default::default()),
1022 LiteralKind::Byte => Literal::Uint(Default::default(), Some(BuiltinUint::U8)),
1023 LiteralKind::Bool(val) => Literal::Bool(val),
1024 LiteralKind::Char => Literal::Char(Default::default()),