1 //! Transforms `ast::Expr` into an equivalent `hir_def::expr::Expr`
9 name::{name, AsName, Name},
10 ExpandError, HirFileId,
16 self, ArgListOwner, ArrayExprKind, AstChildren, LiteralKind, LoopBodyOwner, NameOwner,
19 AstNode, AstPtr, SyntaxNodePtr,
24 body::{Body, BodySourceMap, Expander, LabelSource, PatPtr, SyntheticSyntax},
25 builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint},
27 diagnostics::{InactiveCode, MacroError, UnresolvedProcMacro},
29 dummy_expr_id, ArithOp, Array, BinaryOp, BindingAnnotation, CmpOp, Expr, ExprId, Label,
30 LabelId, Literal, LogicOp, MatchArm, Ordering, Pat, PatId, RecordFieldPat, RecordLitField,
33 item_scope::BuiltinShadowMode,
34 path::{GenericArgs, Path},
35 type_ref::{Mutability, Rawness, TypeRef},
36 AdtId, BlockLoc, ModuleDefId,
39 use super::{diagnostics::BodyDiagnostic, ExprSource, PatSource};
41 pub(crate) struct LowerCtx {
46 pub(crate) fn new(db: &dyn DefDatabase, file_id: HirFileId) -> Self {
47 LowerCtx { hygiene: Hygiene::new(db.upcast(), file_id) }
49 pub(crate) fn with_hygiene(hygiene: &Hygiene) -> Self {
50 LowerCtx { hygiene: hygiene.clone() }
53 pub(crate) fn lower_path(&self, ast: ast::Path) -> Option<Path> {
54 Path::from_src(ast, &self.hygiene)
61 params: Option<ast::ParamList>,
62 body: Option<ast::Expr>,
63 ) -> (Body, BodySourceMap) {
66 source_map: BodySourceMap::default(),
68 exprs: Arena::default(),
69 pats: Arena::default(),
70 labels: Arena::default(),
72 body_expr: dummy_expr_id(),
73 block_scopes: Vec::new(),
78 .collect(params, body)
81 struct ExprCollector<'a> {
82 db: &'a dyn DefDatabase,
85 source_map: BodySourceMap,
88 impl ExprCollector<'_> {
91 param_list: Option<ast::ParamList>,
92 body: Option<ast::Expr>,
93 ) -> (Body, BodySourceMap) {
94 if let Some(param_list) = param_list {
95 if let Some(self_param) = param_list.self_param() {
96 let ptr = AstPtr::new(&self_param);
97 let param_pat = self.alloc_pat(
100 mode: BindingAnnotation::new(
101 self_param.mut_token().is_some() && self_param.amp_token().is_none(),
108 self.body.params.push(param_pat);
111 for param in param_list.params() {
112 let pat = match param.pat() {
116 let param_pat = self.collect_pat(pat);
117 self.body.params.push(param_pat);
121 self.body.body_expr = self.collect_expr_opt(body);
122 (self.body, self.source_map)
125 fn ctx(&self) -> LowerCtx {
126 LowerCtx::new(self.db, self.expander.current_file_id)
129 fn alloc_expr(&mut self, expr: Expr, ptr: AstPtr<ast::Expr>) -> ExprId {
130 let src = self.expander.to_source(ptr);
131 let id = self.make_expr(expr, Ok(src.clone()));
132 self.source_map.expr_map.insert(src, id);
135 // desugared exprs don't have ptr, that's wrong and should be fixed
137 fn alloc_expr_desugared(&mut self, expr: Expr) -> ExprId {
138 self.make_expr(expr, Err(SyntheticSyntax))
140 fn unit(&mut self) -> ExprId {
141 self.alloc_expr_desugared(Expr::Tuple { exprs: Vec::new() })
143 fn missing_expr(&mut self) -> ExprId {
144 self.alloc_expr_desugared(Expr::Missing)
146 fn make_expr(&mut self, expr: Expr, src: Result<ExprSource, SyntheticSyntax>) -> ExprId {
147 let id = self.body.exprs.alloc(expr);
148 self.source_map.expr_map_back.insert(id, src);
152 fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId {
153 let src = self.expander.to_source(ptr);
154 let id = self.make_pat(pat, Ok(src.clone()));
155 self.source_map.pat_map.insert(src, id);
158 fn missing_pat(&mut self) -> PatId {
159 self.make_pat(Pat::Missing, Err(SyntheticSyntax))
161 fn make_pat(&mut self, pat: Pat, src: Result<PatSource, SyntheticSyntax>) -> PatId {
162 let id = self.body.pats.alloc(pat);
163 self.source_map.pat_map_back.insert(id, src);
167 fn alloc_label(&mut self, label: Label, ptr: AstPtr<ast::Label>) -> LabelId {
168 let src = self.expander.to_source(ptr);
169 let id = self.make_label(label, src.clone());
170 self.source_map.label_map.insert(src, id);
173 fn make_label(&mut self, label: Label, src: LabelSource) -> LabelId {
174 let id = self.body.labels.alloc(label);
175 self.source_map.label_map_back.insert(id, src);
179 fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
180 let syntax_ptr = AstPtr::new(&expr);
181 if self.check_cfg(&expr).is_none() {
182 return self.missing_expr();
186 ast::Expr::IfExpr(e) => {
187 let then_branch = self.collect_block_opt(e.then_branch());
189 let else_branch = e.else_branch().map(|b| match b {
190 ast::ElseBranch::Block(it) => self.collect_block(it),
191 ast::ElseBranch::IfExpr(elif) => {
192 let expr: ast::Expr = ast::Expr::cast(elif.syntax().clone()).unwrap();
193 self.collect_expr(expr)
197 let condition = match e.condition() {
198 None => self.missing_expr(),
199 Some(condition) => match condition.pat() {
200 None => self.collect_expr_opt(condition.expr()),
201 // if let -- desugar to match
203 let pat = self.collect_pat(pat);
204 let match_expr = self.collect_expr_opt(condition.expr());
205 let placeholder_pat = self.missing_pat();
207 MatchArm { pat, expr: then_branch, guard: None },
209 pat: placeholder_pat,
210 expr: else_branch.unwrap_or_else(|| self.unit()),
215 .alloc_expr(Expr::Match { expr: match_expr, arms }, syntax_ptr);
220 self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
222 ast::Expr::EffectExpr(e) => match e.effect() {
223 ast::Effect::Try(_) => {
224 let body = self.collect_block_opt(e.block_expr());
225 self.alloc_expr(Expr::TryBlock { body }, syntax_ptr)
227 ast::Effect::Unsafe(_) => {
228 let body = self.collect_block_opt(e.block_expr());
229 self.alloc_expr(Expr::Unsafe { body }, syntax_ptr)
231 // FIXME: we need to record these effects somewhere...
232 ast::Effect::Label(label) => {
233 let label = self.collect_label(label);
234 match e.block_expr() {
236 let res = self.collect_block(block);
237 match &mut self.body.exprs[res] {
238 Expr::Block { label: block_label, .. } => {
239 *block_label = Some(label);
245 None => self.missing_expr(),
248 // FIXME: we need to record these effects somewhere...
249 ast::Effect::Async(_) => {
250 let body = self.collect_block_opt(e.block_expr());
251 self.alloc_expr(Expr::Async { body }, syntax_ptr)
253 ast::Effect::Const(_) => {
254 let body = self.collect_block_opt(e.block_expr());
255 self.alloc_expr(Expr::Const { body }, syntax_ptr)
258 ast::Expr::BlockExpr(e) => self.collect_block(e),
259 ast::Expr::LoopExpr(e) => {
260 let label = e.label().map(|label| self.collect_label(label));
261 let body = self.collect_block_opt(e.loop_body());
262 self.alloc_expr(Expr::Loop { body, label }, syntax_ptr)
264 ast::Expr::WhileExpr(e) => {
265 let label = e.label().map(|label| self.collect_label(label));
266 let body = self.collect_block_opt(e.loop_body());
268 let condition = match e.condition() {
269 None => self.missing_expr(),
270 Some(condition) => match condition.pat() {
271 None => self.collect_expr_opt(condition.expr()),
272 // if let -- desugar to match
274 cov_mark::hit!(infer_resolve_while_let);
275 let pat = self.collect_pat(pat);
276 let match_expr = self.collect_expr_opt(condition.expr());
277 let placeholder_pat = self.missing_pat();
279 self.alloc_expr_desugared(Expr::Break { expr: None, label: None });
281 MatchArm { pat, expr: body, guard: None },
282 MatchArm { pat: placeholder_pat, expr: break_, guard: None },
285 self.alloc_expr_desugared(Expr::Match { expr: match_expr, arms });
287 .alloc_expr(Expr::Loop { body: match_expr, label }, syntax_ptr);
292 self.alloc_expr(Expr::While { condition, body, label }, syntax_ptr)
294 ast::Expr::ForExpr(e) => {
295 let label = e.label().map(|label| self.collect_label(label));
296 let iterable = self.collect_expr_opt(e.iterable());
297 let pat = self.collect_pat_opt(e.pat());
298 let body = self.collect_block_opt(e.loop_body());
299 self.alloc_expr(Expr::For { iterable, pat, body, label }, syntax_ptr)
301 ast::Expr::CallExpr(e) => {
302 let callee = self.collect_expr_opt(e.expr());
303 let args = if let Some(arg_list) = e.arg_list() {
304 arg_list.args().map(|e| self.collect_expr(e)).collect()
308 self.alloc_expr(Expr::Call { callee, args }, syntax_ptr)
310 ast::Expr::MethodCallExpr(e) => {
311 let receiver = self.collect_expr_opt(e.receiver());
312 let args = if let Some(arg_list) = e.arg_list() {
313 arg_list.args().map(|e| self.collect_expr(e)).collect()
317 let method_name = e.name_ref().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
319 e.generic_arg_list().and_then(|it| GenericArgs::from_ast(&self.ctx(), it));
321 Expr::MethodCall { receiver, method_name, args, generic_args },
325 ast::Expr::MatchExpr(e) => {
326 let expr = self.collect_expr_opt(e.expr());
327 let arms = if let Some(match_arm_list) = e.match_arm_list() {
331 self.check_cfg(&arm).map(|()| MatchArm {
332 pat: self.collect_pat_opt(arm.pat()),
333 expr: self.collect_expr_opt(arm.expr()),
336 .and_then(|guard| guard.expr())
337 .map(|e| self.collect_expr(e)),
344 self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
346 ast::Expr::PathExpr(e) => {
349 .and_then(|path| self.expander.parse_path(path))
351 .unwrap_or(Expr::Missing);
352 self.alloc_expr(path, syntax_ptr)
354 ast::Expr::ContinueExpr(e) => self.alloc_expr(
355 Expr::Continue { label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
358 ast::Expr::BreakExpr(e) => {
359 let expr = e.expr().map(|e| self.collect_expr(e));
361 Expr::Break { expr, label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
365 ast::Expr::ParenExpr(e) => {
366 let inner = self.collect_expr_opt(e.expr());
367 // make the paren expr point to the inner expression as well
368 let src = self.expander.to_source(syntax_ptr);
369 self.source_map.expr_map.insert(src, inner);
372 ast::Expr::ReturnExpr(e) => {
373 let expr = e.expr().map(|e| self.collect_expr(e));
374 self.alloc_expr(Expr::Return { expr }, syntax_ptr)
376 ast::Expr::YieldExpr(e) => {
377 let expr = e.expr().map(|e| self.collect_expr(e));
378 self.alloc_expr(Expr::Yield { expr }, syntax_ptr)
380 ast::Expr::RecordExpr(e) => {
381 let path = e.path().and_then(|path| self.expander.parse_path(path));
382 let record_lit = if let Some(nfl) = e.record_expr_field_list() {
385 .filter_map(|field| {
386 self.check_cfg(&field)?;
388 let name = field.field_name()?.as_name();
390 let expr = match field.expr() {
391 Some(e) => self.collect_expr(e),
392 None => self.missing_expr(),
394 let src = self.expander.to_source(AstPtr::new(&field));
395 self.source_map.field_map.insert(src.clone(), expr);
396 self.source_map.field_map_back.insert(expr, src);
397 Some(RecordLitField { name, expr })
400 let spread = nfl.spread().map(|s| self.collect_expr(s));
401 Expr::RecordLit { path, fields, spread }
403 Expr::RecordLit { path, fields: Vec::new(), spread: None }
406 self.alloc_expr(record_lit, syntax_ptr)
408 ast::Expr::FieldExpr(e) => {
409 let expr = self.collect_expr_opt(e.expr());
410 let name = match e.field_access() {
411 Some(kind) => kind.as_name(),
412 _ => Name::missing(),
414 self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
416 ast::Expr::AwaitExpr(e) => {
417 let expr = self.collect_expr_opt(e.expr());
418 self.alloc_expr(Expr::Await { expr }, syntax_ptr)
420 ast::Expr::TryExpr(e) => {
421 let expr = self.collect_expr_opt(e.expr());
422 self.alloc_expr(Expr::Try { expr }, syntax_ptr)
424 ast::Expr::CastExpr(e) => {
425 let expr = self.collect_expr_opt(e.expr());
426 let type_ref = TypeRef::from_ast_opt(&self.ctx(), e.ty());
427 self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
429 ast::Expr::RefExpr(e) => {
430 let expr = self.collect_expr_opt(e.expr());
431 let raw_tok = e.raw_token().is_some();
432 let mutability = if raw_tok {
433 if e.mut_token().is_some() {
435 } else if e.const_token().is_some() {
438 unreachable!("parser only remaps to raw_token() if matching mutability token follows")
441 Mutability::from_mutable(e.mut_token().is_some())
443 let rawness = Rawness::from_raw(raw_tok);
444 self.alloc_expr(Expr::Ref { expr, rawness, mutability }, syntax_ptr)
446 ast::Expr::PrefixExpr(e) => {
447 let expr = self.collect_expr_opt(e.expr());
448 if let Some(op) = e.op_kind() {
449 self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr)
451 self.alloc_expr(Expr::Missing, syntax_ptr)
454 ast::Expr::ClosureExpr(e) => {
455 let mut args = Vec::new();
456 let mut arg_types = Vec::new();
457 if let Some(pl) = e.param_list() {
458 for param in pl.params() {
459 let pat = self.collect_pat_opt(param.pat());
460 let type_ref = param.ty().map(|it| TypeRef::from_ast(&self.ctx(), it));
462 arg_types.push(type_ref);
466 e.ret_type().and_then(|r| r.ty()).map(|it| TypeRef::from_ast(&self.ctx(), it));
467 let body = self.collect_expr_opt(e.body());
468 self.alloc_expr(Expr::Lambda { args, arg_types, ret_type, body }, syntax_ptr)
470 ast::Expr::BinExpr(e) => {
471 let lhs = self.collect_expr_opt(e.lhs());
472 let rhs = self.collect_expr_opt(e.rhs());
473 let op = e.op_kind().map(BinaryOp::from);
474 self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr)
476 ast::Expr::TupleExpr(e) => {
477 let exprs = e.fields().map(|expr| self.collect_expr(expr)).collect();
478 self.alloc_expr(Expr::Tuple { exprs }, syntax_ptr)
480 ast::Expr::BoxExpr(e) => {
481 let expr = self.collect_expr_opt(e.expr());
482 self.alloc_expr(Expr::Box { expr }, syntax_ptr)
485 ast::Expr::ArrayExpr(e) => {
489 ArrayExprKind::ElementList(e) => {
490 let exprs = e.map(|expr| self.collect_expr(expr)).collect();
491 self.alloc_expr(Expr::Array(Array::ElementList(exprs)), syntax_ptr)
493 ArrayExprKind::Repeat { initializer, repeat } => {
494 let initializer = self.collect_expr_opt(initializer);
495 let repeat = self.collect_expr_opt(repeat);
497 Expr::Array(Array::Repeat { initializer, repeat }),
504 ast::Expr::Literal(e) => self.alloc_expr(Expr::Literal(e.kind().into()), syntax_ptr),
505 ast::Expr::IndexExpr(e) => {
506 let base = self.collect_expr_opt(e.base());
507 let index = self.collect_expr_opt(e.index());
508 self.alloc_expr(Expr::Index { base, index }, syntax_ptr)
510 ast::Expr::RangeExpr(e) => {
511 let lhs = e.start().map(|lhs| self.collect_expr(lhs));
512 let rhs = e.end().map(|rhs| self.collect_expr(rhs));
514 Some(range_type) => {
515 self.alloc_expr(Expr::Range { lhs, rhs, range_type }, syntax_ptr)
517 None => self.alloc_expr(Expr::Missing, syntax_ptr),
520 ast::Expr::MacroCall(e) => {
521 let mut ids = vec![];
522 self.collect_macro_call(e, syntax_ptr.clone(), |this, expansion| {
523 ids.push(match expansion {
524 Some(it) => this.collect_expr(it),
525 None => this.alloc_expr(Expr::Missing, syntax_ptr.clone()),
533 fn collect_macro_call<F: FnMut(&mut Self, Option<T>), T: ast::AstNode>(
536 syntax_ptr: AstPtr<ast::Expr>,
539 // File containing the macro call. Expansion errors will be attached here.
540 let outer_file = self.expander.current_file_id;
542 let macro_call = self.expander.to_source(AstPtr::new(&e));
543 let res = self.expander.enter_expand(self.db, e);
546 Some(ExpandError::UnresolvedProcMacro) => {
547 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedProcMacro(
548 UnresolvedProcMacro {
550 node: syntax_ptr.into(),
551 precise_location: None,
557 self.source_map.diagnostics.push(BodyDiagnostic::MacroError(MacroError {
559 node: syntax_ptr.into(),
560 message: err.to_string(),
567 Some((mark, expansion)) => {
568 // FIXME: Statements are too complicated to recover from error for now.
569 // It is because we don't have any hygiene for local variable expansion right now.
570 if T::can_cast(syntax::SyntaxKind::MACRO_STMTS) && res.err.is_some() {
571 self.expander.exit(self.db, mark);
572 collector(self, None);
574 self.source_map.expansions.insert(macro_call, self.expander.current_file_id);
576 let id = collector(self, Some(expansion));
577 self.expander.exit(self.db, mark);
581 None => collector(self, None),
585 fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
586 if let Some(expr) = expr {
587 self.collect_expr(expr)
593 fn collect_stmt(&mut self, s: ast::Stmt) -> Option<Vec<Statement>> {
596 ast::Stmt::LetStmt(stmt) => {
597 self.check_cfg(&stmt)?;
599 let pat = self.collect_pat_opt(stmt.pat());
600 let type_ref = stmt.ty().map(|it| TypeRef::from_ast(&self.ctx(), it));
601 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
602 vec![Statement::Let { pat, type_ref, initializer }]
604 ast::Stmt::ExprStmt(stmt) => {
605 self.check_cfg(&stmt)?;
607 // Note that macro could be expended to multiple statements
608 if let Some(ast::Expr::MacroCall(m)) = stmt.expr() {
609 let syntax_ptr = AstPtr::new(&stmt.expr().unwrap());
610 let mut stmts = vec![];
612 self.collect_macro_call(m, syntax_ptr.clone(), |this, expansion| {
615 let statements: ast::MacroStmts = expansion;
617 statements.statements().for_each(|stmt| {
618 if let Some(mut r) = this.collect_stmt(stmt) {
619 stmts.append(&mut r);
622 if let Some(expr) = statements.expr() {
623 stmts.push(Statement::Expr(this.collect_expr(expr)));
627 stmts.push(Statement::Expr(
628 this.alloc_expr(Expr::Missing, syntax_ptr.clone()),
635 vec![Statement::Expr(self.collect_expr_opt(stmt.expr()))]
638 ast::Stmt::Item(item) => {
639 self.check_cfg(&item)?;
648 fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId {
649 let ast_id = self.expander.ast_id(&block);
651 BlockLoc { ast_id, module: self.expander.def_map.module_id(self.expander.module) };
652 let block_id = self.db.intern_block(block_loc);
653 self.body.block_scopes.push(block_id);
655 let opt_def_map = self.db.block_def_map(block_id);
656 let has_def_map = opt_def_map.is_some();
657 let def_map = opt_def_map.unwrap_or_else(|| self.expander.def_map.clone());
658 let module = if has_def_map { def_map.root() } else { self.expander.module };
659 let prev_def_map = mem::replace(&mut self.expander.def_map, def_map);
660 let prev_local_module = mem::replace(&mut self.expander.module, module);
663 block.statements().filter_map(|s| self.collect_stmt(s)).flatten().collect();
664 let tail = block.tail_expr().map(|e| self.collect_expr(e));
665 let syntax_node_ptr = AstPtr::new(&block.into());
666 let expr_id = self.alloc_expr(
667 Expr::Block { id: block_id, statements, tail, label: None },
671 self.expander.def_map = prev_def_map;
672 self.expander.module = prev_local_module;
676 fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
677 if let Some(block) = expr {
678 self.collect_block(block)
684 fn collect_label(&mut self, ast_label: ast::Label) -> LabelId {
686 name: ast_label.lifetime().as_ref().map_or_else(Name::missing, Name::new_lifetime),
688 self.alloc_label(label, AstPtr::new(&ast_label))
691 fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
692 let pattern = match &pat {
693 ast::Pat::IdentPat(bp) => {
694 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
696 BindingAnnotation::new(bp.mut_token().is_some(), bp.ref_token().is_some());
697 let subpat = bp.pat().map(|subpat| self.collect_pat(subpat));
698 if annotation == BindingAnnotation::Unannotated && subpat.is_none() {
699 // This could also be a single-segment path pattern. To
700 // decide that, we need to try resolving the name.
701 let (resolved, _) = self.expander.def_map.resolve_path(
703 self.expander.module,
704 &name.clone().into(),
705 BuiltinShadowMode::Other,
707 match resolved.take_values() {
708 Some(ModuleDefId::ConstId(_)) => Pat::Path(name.into()),
709 Some(ModuleDefId::EnumVariantId(_)) => {
710 // this is only really valid for unit variants, but
711 // shadowing other enum variants with a pattern is
713 Pat::Path(name.into())
715 Some(ModuleDefId::AdtId(AdtId::StructId(s)))
716 if self.db.struct_data(s).variant_data.kind() != StructKind::Record =>
718 // Funnily enough, record structs *can* be shadowed
719 // by pattern bindings (but unit or tuple structs
721 Pat::Path(name.into())
723 // shadowing statics is an error as well, so we just ignore that case here
724 _ => Pat::Bind { name, mode: annotation, subpat },
727 Pat::Bind { name, mode: annotation, subpat }
730 ast::Pat::TupleStructPat(p) => {
731 let path = p.path().and_then(|path| self.expander.parse_path(path));
732 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
733 Pat::TupleStruct { path, args, ellipsis }
735 ast::Pat::RefPat(p) => {
736 let pat = self.collect_pat_opt(p.pat());
737 let mutability = Mutability::from_mutable(p.mut_token().is_some());
738 Pat::Ref { pat, mutability }
740 ast::Pat::PathPat(p) => {
741 let path = p.path().and_then(|path| self.expander.parse_path(path));
742 path.map(Pat::Path).unwrap_or(Pat::Missing)
744 ast::Pat::OrPat(p) => {
745 let pats = p.pats().map(|p| self.collect_pat(p)).collect();
748 ast::Pat::ParenPat(p) => return self.collect_pat_opt(p.pat()),
749 ast::Pat::TuplePat(p) => {
750 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
751 Pat::Tuple { args, ellipsis }
753 ast::Pat::WildcardPat(_) => Pat::Wild,
754 ast::Pat::RecordPat(p) => {
755 let path = p.path().and_then(|path| self.expander.parse_path(path));
757 .record_pat_field_list()
758 .expect("every struct should have a field list")
761 let ast_pat = f.pat()?;
762 let pat = self.collect_pat(ast_pat);
763 let name = f.field_name()?.as_name();
764 Some(RecordFieldPat { name, pat })
769 .record_pat_field_list()
770 .expect("every struct should have a field list")
774 Pat::Record { path, args, ellipsis }
776 ast::Pat::SlicePat(p) => {
777 let SlicePatComponents { prefix, slice, suffix } = p.components();
779 // FIXME properly handle `RestPat`
781 prefix: prefix.into_iter().map(|p| self.collect_pat(p)).collect(),
782 slice: slice.map(|p| self.collect_pat(p)),
783 suffix: suffix.into_iter().map(|p| self.collect_pat(p)).collect(),
786 ast::Pat::LiteralPat(lit) => {
787 if let Some(ast_lit) = lit.literal() {
788 let expr = Expr::Literal(ast_lit.kind().into());
789 let expr_ptr = AstPtr::new(&ast::Expr::Literal(ast_lit));
790 let expr_id = self.alloc_expr(expr, expr_ptr);
796 ast::Pat::RestPat(_) => {
797 // `RestPat` requires special handling and should not be mapped
798 // to a Pat. Here we are using `Pat::Missing` as a fallback for
799 // when `RestPat` is mapped to `Pat`, which can easily happen
800 // when the source code being analyzed has a malformed pattern
801 // which includes `..` in a place where it isn't valid.
805 ast::Pat::BoxPat(boxpat) => {
806 let inner = self.collect_pat_opt(boxpat.pat());
809 ast::Pat::ConstBlockPat(const_block_pat) => {
810 if let Some(expr) = const_block_pat.block_expr() {
811 let expr_id = self.collect_block(expr);
812 Pat::ConstBlock(expr_id)
818 ast::Pat::RangePat(_) | ast::Pat::MacroPat(_) => Pat::Missing,
820 let ptr = AstPtr::new(&pat);
821 self.alloc_pat(pattern, Either::Left(ptr))
824 fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
825 if let Some(pat) = pat {
826 self.collect_pat(pat)
832 fn collect_tuple_pat(&mut self, args: AstChildren<ast::Pat>) -> (Vec<PatId>, Option<usize>) {
833 // Find the location of the `..`, if there is one. Note that we do not
834 // consider the possibility of there being multiple `..` here.
835 let ellipsis = args.clone().position(|p| matches!(p, ast::Pat::RestPat(_)));
836 // We want to skip the `..` pattern here, since we account for it above.
838 .filter(|p| !matches!(p, ast::Pat::RestPat(_)))
839 .map(|p| self.collect_pat(p))
845 /// Returns `None` (and emits diagnostics) when `owner` if `#[cfg]`d out, and `Some(())` when
847 fn check_cfg(&mut self, owner: &dyn ast::AttrsOwner) -> Option<()> {
848 match self.expander.parse_attrs(self.db, owner).cfg() {
850 if self.expander.cfg_options().check(&cfg) != Some(false) {
854 self.source_map.diagnostics.push(BodyDiagnostic::InactiveCode(InactiveCode {
855 file: self.expander.current_file_id,
856 node: SyntaxNodePtr::new(owner.syntax()),
858 opts: self.expander.cfg_options().clone(),
868 impl From<ast::BinOp> for BinaryOp {
869 fn from(ast_op: ast::BinOp) -> Self {
871 ast::BinOp::BooleanOr => BinaryOp::LogicOp(LogicOp::Or),
872 ast::BinOp::BooleanAnd => BinaryOp::LogicOp(LogicOp::And),
873 ast::BinOp::EqualityTest => BinaryOp::CmpOp(CmpOp::Eq { negated: false }),
874 ast::BinOp::NegatedEqualityTest => BinaryOp::CmpOp(CmpOp::Eq { negated: true }),
875 ast::BinOp::LesserEqualTest => {
876 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less, strict: false })
878 ast::BinOp::GreaterEqualTest => {
879 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: false })
881 ast::BinOp::LesserTest => {
882 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less, strict: true })
884 ast::BinOp::GreaterTest => {
885 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: true })
887 ast::BinOp::Addition => BinaryOp::ArithOp(ArithOp::Add),
888 ast::BinOp::Multiplication => BinaryOp::ArithOp(ArithOp::Mul),
889 ast::BinOp::Subtraction => BinaryOp::ArithOp(ArithOp::Sub),
890 ast::BinOp::Division => BinaryOp::ArithOp(ArithOp::Div),
891 ast::BinOp::Remainder => BinaryOp::ArithOp(ArithOp::Rem),
892 ast::BinOp::LeftShift => BinaryOp::ArithOp(ArithOp::Shl),
893 ast::BinOp::RightShift => BinaryOp::ArithOp(ArithOp::Shr),
894 ast::BinOp::BitwiseXor => BinaryOp::ArithOp(ArithOp::BitXor),
895 ast::BinOp::BitwiseOr => BinaryOp::ArithOp(ArithOp::BitOr),
896 ast::BinOp::BitwiseAnd => BinaryOp::ArithOp(ArithOp::BitAnd),
897 ast::BinOp::Assignment => BinaryOp::Assignment { op: None },
898 ast::BinOp::AddAssign => BinaryOp::Assignment { op: Some(ArithOp::Add) },
899 ast::BinOp::DivAssign => BinaryOp::Assignment { op: Some(ArithOp::Div) },
900 ast::BinOp::MulAssign => BinaryOp::Assignment { op: Some(ArithOp::Mul) },
901 ast::BinOp::RemAssign => BinaryOp::Assignment { op: Some(ArithOp::Rem) },
902 ast::BinOp::ShlAssign => BinaryOp::Assignment { op: Some(ArithOp::Shl) },
903 ast::BinOp::ShrAssign => BinaryOp::Assignment { op: Some(ArithOp::Shr) },
904 ast::BinOp::SubAssign => BinaryOp::Assignment { op: Some(ArithOp::Sub) },
905 ast::BinOp::BitOrAssign => BinaryOp::Assignment { op: Some(ArithOp::BitOr) },
906 ast::BinOp::BitAndAssign => BinaryOp::Assignment { op: Some(ArithOp::BitAnd) },
907 ast::BinOp::BitXorAssign => BinaryOp::Assignment { op: Some(ArithOp::BitXor) },
912 impl From<ast::LiteralKind> for Literal {
913 fn from(ast_lit_kind: ast::LiteralKind) -> Self {
915 LiteralKind::IntNumber(lit) => {
916 if let builtin @ Some(_) = lit.suffix().and_then(BuiltinFloat::from_suffix) {
917 return Literal::Float(Default::default(), builtin);
918 } else if let builtin @ Some(_) =
919 lit.suffix().and_then(|it| BuiltinInt::from_suffix(&it))
921 Literal::Int(Default::default(), builtin)
923 let builtin = lit.suffix().and_then(|it| BuiltinUint::from_suffix(&it));
924 Literal::Uint(Default::default(), builtin)
927 LiteralKind::FloatNumber(lit) => {
928 let ty = lit.suffix().and_then(|it| BuiltinFloat::from_suffix(&it));
929 Literal::Float(Default::default(), ty)
931 LiteralKind::ByteString(_) => Literal::ByteString(Default::default()),
932 LiteralKind::String(_) => Literal::String(Default::default()),
933 LiteralKind::Byte => Literal::Uint(Default::default(), Some(BuiltinUint::U8)),
934 LiteralKind::Bool(val) => Literal::Bool(val),
935 LiteralKind::Char => Literal::Char(Default::default()),