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 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 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 self.maybe_collect_expr(expr).unwrap_or_else(|| self.missing_expr())
198 /// Returns `None` if and only if the expression is `#[cfg]`d out.
199 fn maybe_collect_expr(&mut self, expr: ast::Expr) -> Option<ExprId> {
200 let syntax_ptr = AstPtr::new(&expr);
201 self.check_cfg(&expr)?;
204 ast::Expr::IfExpr(e) => {
205 let then_branch = self.collect_block_opt(e.then_branch());
207 let else_branch = e.else_branch().map(|b| match b {
208 ast::ElseBranch::Block(it) => self.collect_block(it),
209 ast::ElseBranch::IfExpr(elif) => {
210 let expr: ast::Expr = ast::Expr::cast(elif.syntax().clone()).unwrap();
211 self.collect_expr(expr)
215 let condition = self.collect_expr_opt(e.condition());
217 self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
219 ast::Expr::LetExpr(e) => {
220 let pat = self.collect_pat_opt(e.pat());
221 let expr = self.collect_expr_opt(e.expr());
222 self.alloc_expr(Expr::Let { pat, expr }, syntax_ptr)
224 ast::Expr::BlockExpr(e) => match e.modifier() {
225 Some(ast::BlockModifier::Try(_)) => {
226 let body = self.collect_block(e);
227 self.alloc_expr(Expr::TryBlock { body }, syntax_ptr)
229 Some(ast::BlockModifier::Unsafe(_)) => {
230 let body = self.collect_block(e);
231 self.alloc_expr(Expr::Unsafe { body }, syntax_ptr)
233 // FIXME: we need to record these effects somewhere...
234 Some(ast::BlockModifier::Label(label)) => {
235 let label = self.collect_label(label);
236 let res = self.collect_block(e);
237 match &mut self.body.exprs[res] {
238 Expr::Block { label: block_label, .. } => {
239 *block_label = Some(label);
245 Some(ast::BlockModifier::Async(_)) => {
246 let body = self.collect_block(e);
247 self.alloc_expr(Expr::Async { body }, syntax_ptr)
249 Some(ast::BlockModifier::Const(_)) => {
250 let body = self.collect_block(e);
251 self.alloc_expr(Expr::Const { body }, syntax_ptr)
253 None => self.collect_block(e),
255 ast::Expr::LoopExpr(e) => {
256 let label = e.label().map(|label| self.collect_label(label));
257 let body = self.collect_block_opt(e.loop_body());
258 self.alloc_expr(Expr::Loop { body, label }, syntax_ptr)
260 ast::Expr::WhileExpr(e) => {
261 let label = e.label().map(|label| self.collect_label(label));
262 let body = self.collect_block_opt(e.loop_body());
264 let condition = self.collect_expr_opt(e.condition());
266 self.alloc_expr(Expr::While { condition, body, label }, syntax_ptr)
268 ast::Expr::ForExpr(e) => {
269 let label = e.label().map(|label| self.collect_label(label));
270 let iterable = self.collect_expr_opt(e.iterable());
271 let pat = self.collect_pat_opt(e.pat());
272 let body = self.collect_block_opt(e.loop_body());
273 self.alloc_expr(Expr::For { iterable, pat, body, label }, syntax_ptr)
275 ast::Expr::CallExpr(e) => {
276 let callee = self.collect_expr_opt(e.expr());
277 let args = if let Some(arg_list) = e.arg_list() {
278 arg_list.args().filter_map(|e| self.maybe_collect_expr(e)).collect()
282 self.alloc_expr(Expr::Call { callee, args }, syntax_ptr)
284 ast::Expr::MethodCallExpr(e) => {
285 let receiver = self.collect_expr_opt(e.receiver());
286 let args = if let Some(arg_list) = e.arg_list() {
287 arg_list.args().filter_map(|e| self.maybe_collect_expr(e)).collect()
291 let method_name = e.name_ref().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
294 .and_then(|it| GenericArgs::from_ast(&self.ctx(), it))
297 Expr::MethodCall { receiver, method_name, args, generic_args },
301 ast::Expr::MatchExpr(e) => {
302 let expr = self.collect_expr_opt(e.expr());
303 let arms = if let Some(match_arm_list) = e.match_arm_list() {
307 self.check_cfg(&arm).map(|()| MatchArm {
308 pat: self.collect_pat_opt(arm.pat()),
309 expr: self.collect_expr_opt(arm.expr()),
312 .map(|guard| self.collect_expr_opt(guard.condition())),
319 self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
321 ast::Expr::PathExpr(e) => {
324 .and_then(|path| self.expander.parse_path(self.db, path))
326 .unwrap_or(Expr::Missing);
327 self.alloc_expr(path, syntax_ptr)
329 ast::Expr::ContinueExpr(e) => self.alloc_expr(
330 Expr::Continue { label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
333 ast::Expr::BreakExpr(e) => {
334 let expr = e.expr().map(|e| self.collect_expr(e));
336 Expr::Break { expr, label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
340 ast::Expr::ParenExpr(e) => {
341 let inner = self.collect_expr_opt(e.expr());
342 // make the paren expr point to the inner expression as well
343 let src = self.expander.to_source(syntax_ptr);
344 self.source_map.expr_map.insert(src, inner);
347 ast::Expr::ReturnExpr(e) => {
348 let expr = e.expr().map(|e| self.collect_expr(e));
349 self.alloc_expr(Expr::Return { expr }, syntax_ptr)
351 ast::Expr::YieldExpr(e) => {
352 let expr = e.expr().map(|e| self.collect_expr(e));
353 self.alloc_expr(Expr::Yield { expr }, syntax_ptr)
355 ast::Expr::RecordExpr(e) => {
357 e.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
358 let record_lit = if let Some(nfl) = e.record_expr_field_list() {
361 .filter_map(|field| {
362 self.check_cfg(&field)?;
364 let name = field.field_name()?.as_name();
366 let expr = match field.expr() {
367 Some(e) => self.collect_expr(e),
368 None => self.missing_expr(),
370 let src = self.expander.to_source(AstPtr::new(&field));
371 self.source_map.field_map.insert(src.clone(), expr);
372 self.source_map.field_map_back.insert(expr, src);
373 Some(RecordLitField { name, expr })
376 let spread = nfl.spread().map(|s| self.collect_expr(s));
377 Expr::RecordLit { path, fields, spread }
379 Expr::RecordLit { path, fields: Box::default(), spread: None }
382 self.alloc_expr(record_lit, syntax_ptr)
384 ast::Expr::FieldExpr(e) => {
385 let expr = self.collect_expr_opt(e.expr());
386 let name = match e.field_access() {
387 Some(kind) => kind.as_name(),
388 _ => Name::missing(),
390 self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
392 ast::Expr::AwaitExpr(e) => {
393 let expr = self.collect_expr_opt(e.expr());
394 self.alloc_expr(Expr::Await { expr }, syntax_ptr)
396 ast::Expr::TryExpr(e) => {
397 let expr = self.collect_expr_opt(e.expr());
398 self.alloc_expr(Expr::Try { expr }, syntax_ptr)
400 ast::Expr::CastExpr(e) => {
401 let expr = self.collect_expr_opt(e.expr());
402 let type_ref = Interned::new(TypeRef::from_ast_opt(&self.ctx(), e.ty()));
403 self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
405 ast::Expr::RefExpr(e) => {
406 let expr = self.collect_expr_opt(e.expr());
407 let raw_tok = e.raw_token().is_some();
408 let mutability = if raw_tok {
409 if e.mut_token().is_some() {
411 } else if e.const_token().is_some() {
414 unreachable!("parser only remaps to raw_token() if matching mutability token follows")
417 Mutability::from_mutable(e.mut_token().is_some())
419 let rawness = Rawness::from_raw(raw_tok);
420 self.alloc_expr(Expr::Ref { expr, rawness, mutability }, syntax_ptr)
422 ast::Expr::PrefixExpr(e) => {
423 let expr = self.collect_expr_opt(e.expr());
425 Some(op) => self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr),
426 None => self.alloc_expr(Expr::Missing, syntax_ptr),
429 ast::Expr::ClosureExpr(e) => {
430 let mut args = Vec::new();
431 let mut arg_types = Vec::new();
432 if let Some(pl) = e.param_list() {
433 for param in pl.params() {
434 let pat = self.collect_pat_opt(param.pat());
436 param.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
438 arg_types.push(type_ref);
443 .and_then(|r| r.ty())
444 .map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
445 let body = self.collect_expr_opt(e.body());
447 Expr::Lambda { args: args.into(), arg_types: arg_types.into(), ret_type, body },
451 ast::Expr::BinExpr(e) => {
452 let lhs = self.collect_expr_opt(e.lhs());
453 let rhs = self.collect_expr_opt(e.rhs());
454 let op = e.op_kind();
455 self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr)
457 ast::Expr::TupleExpr(e) => {
458 let exprs = e.fields().map(|expr| self.collect_expr(expr)).collect();
459 self.alloc_expr(Expr::Tuple { exprs }, syntax_ptr)
461 ast::Expr::BoxExpr(e) => {
462 let expr = self.collect_expr_opt(e.expr());
463 self.alloc_expr(Expr::Box { expr }, syntax_ptr)
466 ast::Expr::ArrayExpr(e) => {
470 ArrayExprKind::ElementList(e) => {
471 let exprs = e.map(|expr| self.collect_expr(expr)).collect();
472 self.alloc_expr(Expr::Array(Array::ElementList(exprs)), syntax_ptr)
474 ArrayExprKind::Repeat { initializer, repeat } => {
475 let initializer = self.collect_expr_opt(initializer);
476 let repeat = self.collect_expr_opt(repeat);
478 Expr::Array(Array::Repeat { initializer, repeat }),
485 ast::Expr::Literal(e) => self.alloc_expr(Expr::Literal(e.kind().into()), syntax_ptr),
486 ast::Expr::IndexExpr(e) => {
487 let base = self.collect_expr_opt(e.base());
488 let index = self.collect_expr_opt(e.index());
489 self.alloc_expr(Expr::Index { base, index }, syntax_ptr)
491 ast::Expr::RangeExpr(e) => {
492 let lhs = e.start().map(|lhs| self.collect_expr(lhs));
493 let rhs = e.end().map(|rhs| self.collect_expr(rhs));
495 Some(range_type) => {
496 self.alloc_expr(Expr::Range { lhs, rhs, range_type }, syntax_ptr)
498 None => self.alloc_expr(Expr::Missing, syntax_ptr),
501 ast::Expr::MacroCall(e) => {
502 let macro_ptr = AstPtr::new(&e);
503 let mut ids = vec![];
504 self.collect_macro_call(e, macro_ptr, true, |this, expansion| {
505 ids.push(match expansion {
506 Some(it) => this.collect_expr(it),
507 None => this.alloc_expr(Expr::Missing, syntax_ptr.clone()),
512 ast::Expr::MacroStmts(e) => {
513 e.statements().for_each(|s| self.collect_stmt(s));
516 .map(|e| self.collect_expr(e))
517 .unwrap_or_else(|| self.alloc_expr(Expr::Missing, syntax_ptr.clone()));
519 self.alloc_expr(Expr::MacroStmts { tail }, syntax_ptr)
524 fn collect_macro_call<F: FnMut(&mut Self, Option<T>), T: ast::AstNode>(
527 syntax_ptr: AstPtr<ast::MacroCall>,
528 record_diagnostics: bool,
531 // File containing the macro call. Expansion errors will be attached here.
532 let outer_file = self.expander.current_file_id;
534 let macro_call = self.expander.to_source(AstPtr::new(&e));
535 let res = self.expander.enter_expand(self.db, e);
537 let res = match res {
539 Err(UnresolvedMacro { path }) => {
540 if record_diagnostics {
541 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall {
542 node: InFile::new(outer_file, syntax_ptr),
546 collector(self, None);
551 if record_diagnostics {
553 Some(ExpandError::UnresolvedProcMacro) => {
554 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedProcMacro {
555 node: InFile::new(outer_file, syntax_ptr),
559 self.source_map.diagnostics.push(BodyDiagnostic::MacroError {
560 node: InFile::new(outer_file, syntax_ptr),
561 message: err.to_string(),
569 Some((mark, expansion)) => {
570 self.source_map.expansions.insert(macro_call, self.expander.current_file_id);
572 let id = collector(self, Some(expansion));
573 self.expander.exit(self.db, mark);
576 None => collector(self, None),
580 fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
582 Some(expr) => self.collect_expr(expr),
583 None => self.missing_expr(),
587 fn collect_stmt(&mut self, s: ast::Stmt) {
589 ast::Stmt::LetStmt(stmt) => {
590 if self.check_cfg(&stmt).is_none() {
593 let pat = self.collect_pat_opt(stmt.pat());
595 stmt.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
596 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
597 let else_branch = stmt
599 .and_then(|let_else| let_else.block_expr())
600 .map(|block| self.collect_block(block));
601 self.statements_in_scope.push(Statement::Let {
608 ast::Stmt::ExprStmt(stmt) => {
609 if let Some(expr) = stmt.expr() {
610 if self.check_cfg(&expr).is_none() {
614 let has_semi = stmt.semicolon_token().is_some();
615 // Note that macro could be expended to multiple statements
616 if let Some(ast::Expr::MacroCall(m)) = stmt.expr() {
617 let macro_ptr = AstPtr::new(&m);
618 let syntax_ptr = AstPtr::new(&stmt.expr().unwrap());
620 self.collect_macro_call(
624 |this, expansion| match expansion {
626 let statements: ast::MacroStmts = expansion;
628 statements.statements().for_each(|stmt| this.collect_stmt(stmt));
629 if let Some(expr) = statements.expr() {
630 let expr = this.collect_expr(expr);
631 this.statements_in_scope
632 .push(Statement::Expr { expr, has_semi });
636 let expr = this.alloc_expr(Expr::Missing, syntax_ptr.clone());
637 this.statements_in_scope.push(Statement::Expr { expr, has_semi });
642 let expr = self.collect_expr_opt(stmt.expr());
643 self.statements_in_scope.push(Statement::Expr { expr, has_semi });
646 ast::Stmt::Item(_item) => {}
650 fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId {
651 let ast_id = self.expander.ast_id(&block);
653 BlockLoc { ast_id, module: self.expander.def_map.module_id(self.expander.module) };
654 let block_id = self.db.intern_block(block_loc);
656 let (module, def_map) = match self.db.block_def_map(block_id) {
658 self.body.block_scopes.push(block_id);
659 (def_map.root(), def_map)
661 None => (self.expander.module, self.expander.def_map.clone()),
663 let prev_def_map = mem::replace(&mut self.expander.def_map, def_map);
664 let prev_local_module = mem::replace(&mut self.expander.module, module);
665 let prev_statements = std::mem::take(&mut self.statements_in_scope);
667 block.statements().for_each(|s| self.collect_stmt(s));
668 block.tail_expr().and_then(|e| {
669 let expr = self.maybe_collect_expr(e)?;
670 self.statements_in_scope.push(Statement::Expr { expr, has_semi: false });
675 if let Some(Statement::Expr { expr, has_semi: false }) = self.statements_in_scope.last() {
677 self.statements_in_scope.pop();
680 let statements = std::mem::replace(&mut self.statements_in_scope, prev_statements).into();
681 let syntax_node_ptr = AstPtr::new(&block.into());
682 let expr_id = self.alloc_expr(
683 Expr::Block { id: block_id, statements, tail, label: None },
687 self.expander.def_map = prev_def_map;
688 self.expander.module = prev_local_module;
692 fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
694 Some(block) => self.collect_block(block),
695 None => self.missing_expr(),
699 fn collect_label(&mut self, ast_label: ast::Label) -> LabelId {
701 name: ast_label.lifetime().as_ref().map_or_else(Name::missing, Name::new_lifetime),
703 self.alloc_label(label, AstPtr::new(&ast_label))
706 fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
707 let pattern = match &pat {
708 ast::Pat::IdentPat(bp) => {
709 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
711 BindingAnnotation::new(bp.mut_token().is_some(), bp.ref_token().is_some());
712 let subpat = bp.pat().map(|subpat| self.collect_pat(subpat));
713 if annotation == BindingAnnotation::Unannotated && subpat.is_none() {
714 // This could also be a single-segment path pattern. To
715 // decide that, we need to try resolving the name.
716 let (resolved, _) = self.expander.def_map.resolve_path(
718 self.expander.module,
719 &name.clone().into(),
720 BuiltinShadowMode::Other,
722 match resolved.take_values() {
723 Some(ModuleDefId::ConstId(_)) => Pat::Path(name.into()),
724 Some(ModuleDefId::EnumVariantId(_)) => {
725 // this is only really valid for unit variants, but
726 // shadowing other enum variants with a pattern is
728 Pat::Path(name.into())
730 Some(ModuleDefId::AdtId(AdtId::StructId(s)))
731 if self.db.struct_data(s).variant_data.kind() != StructKind::Record =>
733 // Funnily enough, record structs *can* be shadowed
734 // by pattern bindings (but unit or tuple structs
736 Pat::Path(name.into())
738 // shadowing statics is an error as well, so we just ignore that case here
739 _ => Pat::Bind { name, mode: annotation, subpat },
742 Pat::Bind { name, mode: annotation, subpat }
745 ast::Pat::TupleStructPat(p) => {
747 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
748 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
749 Pat::TupleStruct { path, args, ellipsis }
751 ast::Pat::RefPat(p) => {
752 let pat = self.collect_pat_opt(p.pat());
753 let mutability = Mutability::from_mutable(p.mut_token().is_some());
754 Pat::Ref { pat, mutability }
756 ast::Pat::PathPat(p) => {
758 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
759 path.map(Pat::Path).unwrap_or(Pat::Missing)
761 ast::Pat::OrPat(p) => {
762 let pats = p.pats().map(|p| self.collect_pat(p)).collect();
765 ast::Pat::ParenPat(p) => return self.collect_pat_opt(p.pat()),
766 ast::Pat::TuplePat(p) => {
767 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
768 Pat::Tuple { args, ellipsis }
770 ast::Pat::WildcardPat(_) => Pat::Wild,
771 ast::Pat::RecordPat(p) => {
773 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
775 .record_pat_field_list()
776 .expect("every struct should have a field list")
779 let ast_pat = f.pat()?;
780 let pat = self.collect_pat(ast_pat);
781 let name = f.field_name()?.as_name();
782 Some(RecordFieldPat { name, pat })
787 .record_pat_field_list()
788 .expect("every struct should have a field list")
792 Pat::Record { path, args, ellipsis }
794 ast::Pat::SlicePat(p) => {
795 let SlicePatComponents { prefix, slice, suffix } = p.components();
797 // FIXME properly handle `RestPat`
799 prefix: prefix.into_iter().map(|p| self.collect_pat(p)).collect(),
800 slice: slice.map(|p| self.collect_pat(p)),
801 suffix: suffix.into_iter().map(|p| self.collect_pat(p)).collect(),
804 ast::Pat::LiteralPat(lit) => {
805 if let Some(ast_lit) = lit.literal() {
806 let expr = Expr::Literal(ast_lit.kind().into());
807 let expr_ptr = AstPtr::new(&ast::Expr::Literal(ast_lit));
808 let expr_id = self.alloc_expr(expr, expr_ptr);
814 ast::Pat::RestPat(_) => {
815 // `RestPat` requires special handling and should not be mapped
816 // to a Pat. Here we are using `Pat::Missing` as a fallback for
817 // when `RestPat` is mapped to `Pat`, which can easily happen
818 // when the source code being analyzed has a malformed pattern
819 // which includes `..` in a place where it isn't valid.
823 ast::Pat::BoxPat(boxpat) => {
824 let inner = self.collect_pat_opt(boxpat.pat());
827 ast::Pat::ConstBlockPat(const_block_pat) => {
828 if let Some(expr) = const_block_pat.block_expr() {
829 let expr_id = self.collect_block(expr);
830 Pat::ConstBlock(expr_id)
835 ast::Pat::MacroPat(mac) => match mac.macro_call() {
837 let macro_ptr = AstPtr::new(&call);
839 self.collect_macro_call(call, macro_ptr, true, |this, expanded_pat| {
840 pat = Some(this.collect_pat_opt(expanded_pat));
844 Some(pat) => return pat,
845 None => Pat::Missing,
848 None => Pat::Missing,
851 ast::Pat::RangePat(_) => Pat::Missing,
853 let ptr = AstPtr::new(&pat);
854 self.alloc_pat(pattern, Either::Left(ptr))
857 fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
859 Some(pat) => self.collect_pat(pat),
860 None => self.missing_pat(),
864 fn collect_tuple_pat(&mut self, args: AstChildren<ast::Pat>) -> (Box<[PatId]>, Option<usize>) {
865 // Find the location of the `..`, if there is one. Note that we do not
866 // consider the possibility of there being multiple `..` here.
867 let ellipsis = args.clone().position(|p| matches!(p, ast::Pat::RestPat(_)));
868 // We want to skip the `..` pattern here, since we account for it above.
870 .filter(|p| !matches!(p, ast::Pat::RestPat(_)))
871 .map(|p| self.collect_pat(p))
877 /// Returns `None` (and emits diagnostics) when `owner` if `#[cfg]`d out, and `Some(())` when
879 fn check_cfg(&mut self, owner: &dyn ast::HasAttrs) -> Option<()> {
880 match self.expander.parse_attrs(self.db, owner).cfg() {
882 if self.expander.cfg_options().check(&cfg) != Some(false) {
886 self.source_map.diagnostics.push(BodyDiagnostic::InactiveCode {
888 self.expander.current_file_id,
889 SyntaxNodePtr::new(owner.syntax()),
892 opts: self.expander.cfg_options().clone(),
902 impl From<ast::LiteralKind> for Literal {
903 fn from(ast_lit_kind: ast::LiteralKind) -> Self {
905 // FIXME: these should have actual values filled in, but unsure on perf impact
906 LiteralKind::IntNumber(lit) => {
907 if let builtin @ Some(_) = lit.suffix().and_then(BuiltinFloat::from_suffix) {
908 Literal::Float(Default::default(), builtin)
909 } else if let builtin @ Some(_) =
910 lit.suffix().and_then(|it| BuiltinInt::from_suffix(it))
912 Literal::Int(lit.value().unwrap_or(0) as i128, builtin)
914 let builtin = lit.suffix().and_then(|it| BuiltinUint::from_suffix(it));
915 Literal::Uint(lit.value().unwrap_or(0), builtin)
918 LiteralKind::FloatNumber(lit) => {
919 let ty = lit.suffix().and_then(|it| BuiltinFloat::from_suffix(it));
920 Literal::Float(Default::default(), ty)
922 LiteralKind::ByteString(bs) => {
923 let text = bs.value().map(Box::from).unwrap_or_else(Default::default);
924 Literal::ByteString(text)
926 LiteralKind::String(_) => Literal::String(Default::default()),
927 LiteralKind::Byte => Literal::Uint(Default::default(), Some(BuiltinUint::U8)),
928 LiteralKind::Bool(val) => Literal::Bool(val),
929 LiteralKind::Char => Literal::Char(Default::default()),