]> git.lizzy.rs Git - rust.git/blobdiff - crates/hir_def/src/body.rs
parameters.split_last()
[rust.git] / crates / hir_def / src / body.rs
index 9510a8575f7bd6d2b11fb8fc03de6125768975d9..8488b4f0d03ff5fe1c4cadf978fbbf920ab96a2d 100644 (file)
@@ -1,7 +1,6 @@
 //! Defines `Body`: a lowered representation of bodies of functions, statics and
 //! consts.
 mod lower;
-mod diagnostics;
 #[cfg(test)]
 mod tests;
 pub mod scope;
@@ -9,19 +8,18 @@
 use std::{mem, ops::Index, sync::Arc};
 
 use base_db::CrateId;
-use cfg::CfgOptions;
+use cfg::{CfgExpr, CfgOptions};
 use drop_bomb::DropBomb;
 use either::Either;
 use hir_expand::{
-    ast_id_map::AstIdMap, diagnostics::DiagnosticSink, hygiene::Hygiene, AstId, ExpandResult,
-    HirFileId, InFile, MacroDefId,
+    ast_id_map::AstIdMap, hygiene::Hygiene, AstId, ExpandError, ExpandResult, HirFileId, InFile,
+    MacroCallId, MacroDefId,
 };
 use la_arena::{Arena, ArenaMap};
+use limit::Limit;
 use profile::Count;
 use rustc_hash::FxHashMap;
-use syntax::{ast, AstNode, AstPtr};
-
-pub use lower::LowerCtx;
+use syntax::{ast, AstNode, AstPtr, SyntaxNodePtr};
 
 use crate::{
     attr::{Attrs, RawAttrs},
@@ -35,6 +33,8 @@
     UnresolvedMacro,
 };
 
+pub use lower::LowerCtx;
+
 /// A subset of Expander that only deals with cfg attributes. We only need it to
 /// avoid cyclic queries in crate def map during enum processing.
 #[derive(Debug)]
@@ -54,12 +54,6 @@ pub struct Expander {
     recursion_limit: usize,
 }
 
-#[cfg(test)]
-const EXPANSION_RECURSION_LIMIT: usize = 32;
-
-#[cfg(not(test))]
-const EXPANSION_RECURSION_LIMIT: usize = 128;
-
 impl CfgExpander {
     pub(crate) fn new(
         db: &dyn DefDatabase,
@@ -71,11 +65,11 @@ pub(crate) fn new(
         CfgExpander { cfg_options, hygiene, krate }
     }
 
-    pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::AttrsOwner) -> Attrs {
+    pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
         RawAttrs::new(db, owner, &self.hygiene).filter(db, self.krate)
     }
 
-    pub(crate) fn is_cfg_enabled(&self, db: &dyn DefDatabase, owner: &dyn ast::AttrsOwner) -> bool {
+    pub(crate) fn is_cfg_enabled(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> bool {
         let attrs = self.parse_attrs(db, owner);
         attrs.is_cfg_enabled(&self.cfg_options)
     }
@@ -101,7 +95,7 @@ pub fn enter_expand<T: ast::AstNode>(
         db: &dyn DefDatabase,
         macro_call: ast::MacroCall,
     ) -> Result<ExpandResult<Option<(Mark, T)>>, UnresolvedMacro> {
-        if self.recursion_limit + 1 > EXPANSION_RECURSION_LIMIT {
+        if self.recursion_limit(db).check(self.recursion_limit + 1).is_err() {
             cov_mark::hit!(your_stack_belongs_to_me);
             return Ok(ExpandResult::str_err(
                 "reached recursion limit during macro expansion".into(),
@@ -125,6 +119,23 @@ pub fn enter_expand<T: ast::AstNode>(
             }
         };
 
+        Ok(self.enter_expand_inner(db, call_id, err))
+    }
+
+    pub fn enter_expand_id<T: ast::AstNode>(
+        &mut self,
+        db: &dyn DefDatabase,
+        call_id: MacroCallId,
+    ) -> ExpandResult<Option<(Mark, T)>> {
+        self.enter_expand_inner(db, call_id, None)
+    }
+
+    fn enter_expand_inner<T: ast::AstNode>(
+        &mut self,
+        db: &dyn DefDatabase,
+        call_id: MacroCallId,
+        mut err: Option<ExpandError>,
+    ) -> ExpandResult<Option<(Mark, T)>> {
         if err.is_none() {
             err = db.macro_expand_error(call_id);
         }
@@ -136,12 +147,12 @@ pub fn enter_expand<T: ast::AstNode>(
             None => {
                 // Only `None` if the macro expansion produced no usable AST.
                 if err.is_none() {
-                    log::warn!("no error despite `parse_or_expand` failing");
+                    tracing::warn!("no error despite `parse_or_expand` failing");
                 }
 
-                return Ok(ExpandResult::only_err(err.unwrap_or_else(|| {
+                return ExpandResult::only_err(err.unwrap_or_else(|| {
                     mbe::ExpandError::Other("failed to parse macro invocation".into())
-                })));
+                }));
             }
         };
 
@@ -149,11 +160,11 @@ pub fn enter_expand<T: ast::AstNode>(
             Some(it) => it,
             None => {
                 // This can happen without being an error, so only forward previous errors.
-                return Ok(ExpandResult { value: None, err });
+                return ExpandResult { value: None, err };
             }
         };
 
-        log::debug!("macro expansion {:#?}", node.syntax());
+        tracing::debug!("macro expansion {:#?}", node.syntax());
 
         self.recursion_limit += 1;
         let mark = Mark {
@@ -165,7 +176,7 @@ pub fn enter_expand<T: ast::AstNode>(
         self.current_file_id = file_id;
         self.ast_id_map = db.ast_id_map(file_id);
 
-        Ok(ExpandResult { value: Some((mark, node)), err })
+        ExpandResult { value: Some((mark, node)), err }
     }
 
     pub fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
@@ -180,7 +191,7 @@ pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
         InFile { file_id: self.current_file_id, value }
     }
 
-    pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::AttrsOwner) -> Attrs {
+    pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
         self.cfg_expander.parse_attrs(db, owner)
     }
 
@@ -194,7 +205,7 @@ pub fn current_file_id(&self) -> HirFileId {
 
     fn parse_path(&mut self, db: &dyn DefDatabase, path: ast::Path) -> Option<Path> {
         let ctx = LowerCtx::with_hygiene(db, &self.cfg_expander.hygiene);
-        Path::from_src(db, path, &ctx)
+        Path::from_src(path, &ctx)
     }
 
     fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
@@ -205,6 +216,17 @@ fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
         let file_local_id = self.ast_id_map.ast_id(item);
         AstId::new(self.current_file_id, file_local_id)
     }
+
+    fn recursion_limit(&self, db: &dyn DefDatabase) -> Limit {
+        let limit = db.crate_limits(self.cfg_expander.krate).recursion_limit as _;
+
+        #[cfg(not(test))]
+        return Limit::new(limit);
+
+        // Without this, `body::tests::your_stack_belongs_to_me` stack-overflows in debug
+        #[cfg(test)]
+        return Limit::new(std::cmp::min(32, limit));
+    }
 }
 
 #[derive(Debug)]
@@ -273,12 +295,20 @@ pub struct BodySourceMap {
 
     /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
     /// the source map (since they're just as volatile).
-    diagnostics: Vec<diagnostics::BodyDiagnostic>,
+    diagnostics: Vec<BodyDiagnostic>,
 }
 
 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
 pub struct SyntheticSyntax;
 
+#[derive(Debug, Eq, PartialEq)]
+pub enum BodyDiagnostic {
+    InactiveCode { node: InFile<SyntaxNodePtr>, cfg: CfgExpr, opts: CfgOptions },
+    MacroError { node: InFile<AstPtr<ast::MacroCall>>, message: String },
+    UnresolvedProcMacro { node: InFile<AstPtr<ast::MacroCall>> },
+    UnresolvedMacroCall { node: InFile<AstPtr<ast::MacroCall>>, path: ModPath },
+}
+
 impl Body {
     pub(crate) fn body_with_source_map_query(
         db: &dyn DefDatabase,
@@ -416,9 +446,8 @@ pub fn node_field(&self, node: InFile<&ast::RecordExprField>) -> Option<ExprId>
         self.field_map.get(&src).cloned()
     }
 
-    pub(crate) fn add_diagnostics(&self, _db: &dyn DefDatabase, sink: &mut DiagnosticSink<'_>) {
-        for diag in &self.diagnostics {
-            diag.add_to(sink);
-        }
+    /// Get a reference to the body source map's diagnostics.
+    pub fn diagnostics(&self) -> &[BodyDiagnostic] {
+        &self.diagnostics
     }
 }