Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 37 additions & 3 deletions src/spaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,7 @@ pub fn metrics<'a, T: ParserTrait>(parser: &'a T, path: &'a Path) -> Option<Func
// in a map instead of using the O(depth) `tree_sitter::Node::parent`.
let parents = Parents::new(&root);
let node = root.with_parents(&parents);
let root_id = node.id();
let mut cursor = node.cursor();
let mut stack = Vec::new();
let mut children = Vec::new();
Expand All @@ -307,9 +308,17 @@ pub fn metrics<'a, T: ParserTrait>(parser: &'a T, path: &'a Path) -> Option<Func
last_level = level;
}

let kind = T::Getter::get_space_kind(&node);
let mut kind = T::Getter::get_space_kind(&node);
let mut func_space = T::Checker::is_func(&node) || T::Checker::is_func_space(&node);

// The root must always open a space, otherwise the first space found
// below it would become the root and absorb all the following ones.
// This happens when error recovery makes the root an ERROR node.
if node.id() == root_id && !func_space {
kind = SpaceKind::Unit;
func_space = true;
}

let func_space = T::Checker::is_func(&node) || T::Checker::is_func_space(&node);
let unit = kind == SpaceKind::Unit;

let new_level = if func_space {
Expand Down Expand Up @@ -386,7 +395,32 @@ impl Callback for Metrics {

#[cfg(test)]
mod tests {
use crate::{CppParser, check_func_space};
use std::path::Path;

use super::*;
use crate::{CppParser, MozjsParser, check_func_space};

// Error recovery can make the root of the tree an ERROR node, which is not
// a space for any language: the root must still be the unit containing
// all the other spaces.
#[test]
fn error_root_is_unit() {
let code = "const F = {\n a: x => 1\n};\nclass A {\n g() {\n";
let path = Path::new("foo.js");
let parser = MozjsParser::new(code.as_bytes().to_vec(), path, None);
assert_eq!(parser.get_root().kind_id(), u16::MAX);

let space = metrics(&parser, path).unwrap();
assert_eq!(space.kind, SpaceKind::Unit);
assert_eq!((space.start_line, space.end_line), (1, 5));
assert_eq!(space.metrics.loc.sloc(), 5.);
assert_eq!(space.spaces.len(), 1);
assert_eq!(space.spaces[0].name.as_deref(), Some("a"));
assert_eq!(
(space.spaces[0].start_line, space.spaces[0].end_line),
(2, 2)
);
}

#[test]
fn c_scope_resolution_operator() {
Expand Down