use cpp_code_analysis::Known;
use cpp_code_analysis::semantic::{Name, NameKind, Provenance};
use cpp_code_analysis::{
CompilerConfig, MemoryFiles, OpenDocuments, Session, SessionFiles, WatchFilter,
};
fn session_with(files: &[(&str, &str)]) -> Session<MemoryFiles> {
let mut memory = MemoryFiles::new();
for (path, source) in files {
memory = memory.with_file(*path, *source);
}
let providers = SessionFiles::new(OpenDocuments::new(), memory);
let mut session = Session::with_config(
"/p",
providers,
WatchFilter::new("/p"),
CompilerConfig::default(),
);
session.add_project_files(
files
.iter()
.map(|(path, _)| std::path::PathBuf::from(*path)),
);
for (path, _) in files {
session.want_cooked_reading(std::path::Path::new(path));
}
session.index_everything();
session
}
fn classified(source: &str) -> Vec<(String, NameKind, bool)> {
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
session
.classified_names(&view)
.into_iter()
.map(|name: Name| {
(
source[name.range.start_offset..name.range.end_offset()].to_string(),
name.kind,
name.declaration,
)
})
.collect()
}
fn kind_of(source: &str, spelling: &str) -> Option<NameKind> {
let found: Vec<NameKind> = classified(source)
.into_iter()
.filter(|(text, _, _)| text == spelling)
.map(|(_, kind, _)| kind)
.collect();
found.first().copied()
}
fn all_of(source: &str, spelling: &str) -> Vec<(NameKind, bool)> {
classified(source)
.into_iter()
.filter(|(text, _, _)| text == spelling)
.map(|(_, kind, declaration)| (kind, declaration))
.collect()
}
#[test]
fn each_kind_of_name_is_classified_by_what_declares_it() {
let source = "\
#define LIMIT 8
namespace ns {
enum Color { Red, Green };
struct Widget {
int size;
int scaled(int factor) const;
};
int count(int total) {
int local = total;
return local;
}
}
";
let cases = [
("LIMIT", Some(NameKind::Macro)),
("ns", Some(NameKind::Namespace)),
("Color", Some(NameKind::Type)),
("Widget", Some(NameKind::Type)),
("Red", Some(NameKind::EnumMember)),
("factor", Some(NameKind::Parameter)),
("total", Some(NameKind::Parameter)),
("local", Some(NameKind::Variable)),
("size", Some(NameKind::Variable)),
("scaled", Some(NameKind::Method)),
("count", Some(NameKind::Function)),
];
for (spelling, expected) in cases {
assert_eq!(kind_of(source, spelling), expected, "`{spelling}`");
}
}
#[test]
fn a_use_is_classified_like_the_declaration_it_names() {
let source = "\
int size(int value);
int f() { return size(1); }
";
let size: Vec<(String, NameKind, bool)> = classified(source)
.into_iter()
.filter(|(text, _, _)| text == "size")
.collect();
assert_eq!(size.len(), 2, "the declaration and the use: {size:?}");
assert_eq!(size[0].1, NameKind::Function);
assert!(size[0].2, "the declaration's own name");
assert_eq!(size[1].1, NameKind::Function);
assert!(!size[1].2, "the use");
}
#[test]
fn a_name_from_another_file_is_classified() {
let header = "struct Widget { int size; };\nint measure(Widget& w);\n";
let source = "#include \"b.h\"\nint f(Widget& w) { return measure(w); }\n";
let session = session_with(&[("/p/a.cpp", source), ("/p/b.h", header)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let found: Vec<(String, NameKind)> = session
.classified_names(&view)
.into_iter()
.map(|name| {
(
source[name.range.start_offset..name.range.end_offset()].to_string(),
name.kind,
)
})
.collect();
assert!(
found.contains(&("Widget".to_string(), NameKind::Type)),
"the header's class: {found:?}"
);
assert!(
found.contains(&("measure".to_string(), NameKind::Function)),
"and its function: {found:?}"
);
}
#[test]
fn a_name_nothing_declares_is_not_classified() {
let source = "int f() { return unknown_thing + 1; }\n";
assert_eq!(kind_of(source, "unknown_thing"), None);
}
#[test]
fn a_macro_in_an_untaken_branch_is_still_a_macro() {
let source = "\
#if 0
#define ONLY_HERE 1
#endif
int f() { return ONLY_HERE; }
";
assert_eq!(kind_of(source, "ONLY_HERE"), Some(NameKind::Macro));
}
#[test]
fn one_spelling_with_two_declarations_is_still_classified() {
let source = "\
int pick(int value);
double pick(double value);
double f() { return pick(1.5); }
";
let picks: Vec<(String, NameKind, bool)> = classified(source)
.into_iter()
.filter(|(text, _, _)| text == "pick")
.collect();
assert_eq!(picks.len(), 3, "{picks:?}");
assert!(picks.iter().all(|(_, kind, _)| *kind == NameKind::Function));
}
#[test]
fn a_template_parameter_is_its_own_kind() {
let source = "template <class T> T identity(T value) { return value; }\n";
assert_eq!(kind_of(source, "T"), Some(NameKind::TypeParameter));
}
#[test]
fn the_classifications_are_sorted_and_disjoint() {
let source = "\
#define LIMIT 8
namespace ns {
struct Widget { int size; };
int count(Widget& w) { int local = LIMIT; return local + w.size; }
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let names = session.classified_names(&view);
assert!(!names.is_empty());
for pair in names.windows(2) {
assert!(
pair[0].range.end_offset() <= pair[1].range.start_offset,
"out of order or overlapping: {:?} then {:?}",
pair[0],
pair[1]
);
}
assert!(names.iter().all(|name| name.range.length > 0));
}
#[test]
fn a_use_resolves_to_the_declaration_it_names_not_to_the_spelling() {
let source = "\
struct Widget { int size; };
int size(int value);
int scaled(int size) { return size * size; }
int area(Widget& w) { return w.size; }
";
let size = all_of(source, "size");
assert_eq!(
size,
vec![
(NameKind::Variable, true),
(NameKind::Function, true),
(NameKind::Parameter, true),
(NameKind::Parameter, false),
(NameKind::Parameter, false),
(NameKind::Variable, false),
],
"a parameter is not the file-scope function that shares its spelling, and a member is what its object's type says"
);
}
#[test]
fn a_member_access_whose_spelling_is_shared_is_still_classified() {
let source = "\
struct Widget { int size; };
int size(int value);
int area(Widget& w) { return w.size; }
";
let size = all_of(source, "size");
assert_eq!(
size,
vec![
(NameKind::Variable, true),
(NameKind::Function, true),
(NameKind::Variable, false),
],
"the two declarations are drawn, and the member access is drawn as the member it names"
);
}
#[test]
fn a_member_access_is_classified_from_the_class_it_is_a_member_of() {
let header = "struct Widget { int size; };\n";
let source = "#include \"b.h\"\nint measure(Widget& w) { return w.size; }\n";
let session = session_with(&[("/p/a.cpp", source), ("/p/b.h", header)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let names: Vec<(String, NameKind, Provenance)> = session
.classified_names(&view)
.into_iter()
.map(|name| {
(
source[name.range.start_offset..name.range.end_offset()].to_string(),
name.kind,
name.provenance,
)
})
.collect();
assert!(
names.contains(&("size".to_string(), NameKind::Variable, Provenance::Found)),
"the member's declaration is what `w.size` names: {names:?}"
);
}
#[test]
fn the_provenance_says_which_layer_answered() {
let header = "struct Widget { int size; };\n";
let source = "\
#include \"b.h\"
#define LIMIT 8
int scale(int factor) { return factor * LIMIT; }
int measure(Widget& w) { return w.size; }
";
let session = session_with(&[("/p/a.cpp", source), ("/p/b.h", header)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let provenance = |spelling: &str| -> Vec<Provenance> {
session
.classified_names(&view)
.into_iter()
.filter(|name| &source[name.range.start_offset..name.range.end_offset()] == spelling)
.map(|name| name.provenance)
.collect()
};
assert_eq!(
provenance("scale"),
vec![Provenance::DeclaredHere],
"written here"
);
assert_eq!(
provenance("factor"),
vec![Provenance::DeclaredHere, Provenance::Held],
"a parameter's own name, then the use the scope chain resolved"
);
assert_eq!(
provenance("size"),
vec![Provenance::Found],
"a member of a class in another file is the index's answer"
);
assert_eq!(
provenance("Widget"),
vec![Provenance::Found],
"and so is the class itself"
);
assert_eq!(
provenance("LIMIT"),
vec![Provenance::Macro, Provenance::Macro],
"a #define, not a declaration"
);
}
#[test]
fn keywords_and_literals_are_not_classified() {
let source = "struct Widget { int size; };\nint f() { return 1; }\n";
let kinds = classified(source);
for (text, _, _) in &kinds {
assert!(
!matches!(text.as_str(), "int" | "return" | "struct"),
"`{text}` is not a name this layer classifies: {kinds:?}"
);
}
}
#[test]
fn a_written_type_resolves_a_member_the_class_inherits() {
let session = session_with(&[
(
"/p/base.h",
"template <class _Alloc>\nstruct _Normal {\n using pointer = int*;\n int size;\n};\n",
),
(
"/p/a.cpp",
"#include \"base.h\"\nnamespace std {\ntemplate <class _Alloc>\nstruct allocator_traits : _Normal<_Alloc> {};\n}\n",
),
]);
let view = session.view("/p/a.cpp").expect("the file is held");
match session.definition_of_a_written_type(&view, "std::allocator_traits::pointer", None, 0) {
Known::Yes(found) => assert_eq!(found.fact.name, "pointer"),
other => panic!(
"`pointer` is inherited from `_Normal` and has to be found through it: {other:?}"
),
}
assert!(
matches!(
session.definition_of_a_written_type(
&view,
"std::allocator_traits::nothing_here",
None,
0
),
Known::Unknown(_)
),
"the walk reads the chain; it does not invent a member: {:?}",
session.definition_of_a_written_type(&view, "std::allocator_traits::nothing_here", None, 0)
);
}
#[test]
fn a_local_type_is_looked_up_from_the_namespace_around_it() {
let session = session_with(&[(
"/p/a.cpp",
"namespace app {\nstruct Widget { int size; };\nvoid f() { Widget w; }\n}\n",
)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let at = "namespace app {\nstruct Widget { int size; };\nvoid f() { ".len();
match session.definition_of_a_written_type(&view, "Widget", None, at) {
Known::Yes(found) => assert_eq!(found.fact.qualified_name(), "app::Widget"),
other => panic!("a local `Widget` in `namespace app` names `app::Widget`: {other:?}"),
}
assert!(
matches!(
session.definition_of_a_written_type(&view, "Nothing_here_at_all", None, at),
Known::Unknown(_)
),
"a name no declaration holds is still nowhere: {:?}",
session.definition_of_a_written_type(&view, "Nothing_here_at_all", None, at)
);
}
#[test]
fn a_local_fact_carries_a_namespace_the_file_only_opens_with_a_macro() {
let session = session_with(&[
(
"/p/ns.h",
"#define BEGIN_APP namespace app {\n#define END_APP }\n",
),
(
"/p/a.cpp",
"#include \"ns.h\"\nBEGIN_APP\nstruct Widget { int size; };\nvoid f() { Widget w; }\nEND_APP\n",
),
]);
let view = session.view("/p/a.cpp").expect("the file is held");
let local = session
.index()
.summaries()
.flat_map(|summary| summary.declarations.iter())
.find(|fact| fact.local && fact.name == "w")
.expect("the local is declared");
assert_eq!(
local.in_namespace.as_deref(),
Some("app"),
"the summary is read with the closure's macros in hand, so the namespace is known"
);
assert!(
local.scope.is_none(),
"…and a body contributes no segment to a qualified name, which is why the field is needed: {:?}",
local.scope
);
assert!(
view.scopes.scope_with_qualified_name("app").is_some(),
"the view is parsed with the closure's macros in hand, so `BEGIN_APP` opens `app` here too"
);
match session.definition_of_a_written_type(
&view,
"Widget",
local.in_namespace.as_deref(),
local.range.start_offset,
) {
Known::Yes(found) => assert_eq!(found.fact.qualified_name(), "app::Widget"),
other => panic!("`Widget` written in `app` names `app::Widget`: {other:?}"),
}
}
#[test]
fn a_stray_identifier_in_a_template_argument_drops_the_declarations_after_it() {
let source = "template <class T> struct Spec {};\n\
template <class T> struct Spec<T> { using d = W<decltype(_STD f<T>())>; };\n\
template <class T> struct After { int c; };\n";
let parsed = cpp_parser::CppParser::parse(source, cpp_parser::ParserConfig::default());
let root = parsed.get_red_root();
let scopes = cpp_code_analysis::sema::scopes::build_scopes(
&root,
&cpp_code_analysis::sema::scopes::NoMacroBodies,
);
let bound: Vec<&str> = scopes
.scopes()
.iter()
.flat_map(|scope| scope.bindings.iter())
.filter_map(|binding| binding.name.identifier_text())
.collect();
let top: Vec<String> = root
.children()
.map(|child| {
let text: String = child.text().to_string();
format!(
"{:?} len={} {:?}",
cpp_parser::CppSyntaxKind::from(child.kind()),
text.len(),
text
)
})
.collect();
eprintln!("TOP {top:#?}");
let events: Vec<String> =
cpp_parser::CppParser::parse_with_events(source, cpp_parser::ParserConfig::default())
.1
.iter()
.enumerate()
.map(|(at, event)| format!("{at}: {event:?}"))
.collect();
eprintln!("EVENTS {events:#?}");
assert!(
bound.contains(&"After"),
"…and if the binding is missing too, the loss is in `build_scopes`: got {bound:?}"
);
let summary = cpp_code_analysis::summarize(
std::path::Path::new("/p/a.cpp"),
source,
cpp_code_analysis::SummaryKey::new(0, 0),
);
let names: Vec<&str> = summary
.declarations
.iter()
.map(|fact| fact.name.as_str())
.collect();
assert!(
names.contains(&"After"),
"`After` is a class definition in the tree, so it has to be a fact: got {names:?}"
);
}
#[test]
fn a_decltype_whose_body_is_not_an_expression_still_ends_at_its_own_paren() {
for source in [
"using d = decltype(_STD x);\nstruct After { int c; };\n",
"struct S { using d = decltype(_STD x); };\nstruct After { int c; };\n",
] {
let summary = cpp_code_analysis::summarize(
std::path::Path::new("/p/a.cpp"),
source,
cpp_code_analysis::SummaryKey::new(0, 0),
);
let found = summary
.declarations
.iter()
.find(|fact| fact.name == "After")
.unwrap_or_else(|| {
panic!(
"`After` is written after the alias and has to be read: {:?}",
summary
.declarations
.iter()
.map(|fact| fact.qualified_name())
.collect::<Vec<_>>()
)
});
assert_eq!(
found.qualified_name(),
"After",
"it is a declaration of the **file**, not a member of what stands before it: {source:?}"
);
}
}
#[test]
fn a_std_shaped_call_in_a_condition_keeps_what_follows_it() {
for source in [
"struct S { void f() { if (!_STD g()) { } } };\nstruct After { int c; };\n",
"struct S { void f() { while (_STD g()) { } } };\nstruct After { int c; };\n",
"struct S { void f() { if (_STD g()) { } else { } } };\nstruct After { int c; };\n",
] {
let summary = cpp_code_analysis::summarize(
std::path::Path::new("/p/a.cpp"),
source,
cpp_code_analysis::SummaryKey::new(0, 0),
);
let found = summary
.declarations
.iter()
.find(|fact| fact.name == "After")
.unwrap_or_else(|| {
panic!(
"the declaration after the function has to be read: {:?}",
summary
.declarations
.iter()
.map(|fact| fact.qualified_name())
.collect::<Vec<_>>()
)
});
assert_eq!(
found.qualified_name(),
"After",
"it is a declaration of the **file**, not of the class above it: {source:?}"
);
}
}
#[test]
fn a_name_after_an_unseen_macro_is_still_a_name() {
for source in [
"struct S { void f() { _STD g(); } };\nstruct After { int c; };\n",
"struct S { void f() { _STD g(p, [] { }); } };\nstruct After { int c; };\n",
"struct S { int f() { return _STD g(x); } };\nstruct After { int c; };\n",
"struct S { void f() { if (!_STD g()) { } } };\nstruct After { int c; };\n",
] {
let summary = cpp_code_analysis::summarize(
std::path::Path::new("/p/a.cpp"),
source,
cpp_code_analysis::SummaryKey::new(0, 0),
);
let found = summary
.declarations
.iter()
.find(|fact| fact.name == "After")
.unwrap_or_else(|| {
panic!(
"the declaration after the function has to be read: {:?}",
summary
.declarations
.iter()
.map(|fact| fact.qualified_name())
.collect::<Vec<_>>()
)
});
assert_eq!(
found.qualified_name(),
"After",
"it is a declaration of the **file**, not of the class above it: {source:?}"
);
}
}
#[test]
fn an_alias_target_after_an_unseen_macro_is_one_name() {
for source in [
"struct S { using a = _STD rt; };\nstruct After { int c; };\n",
"struct S { using a = _STD rt<i>; };\nstruct After { int c; };\n",
"struct S { using a = _STD rt<i>; int member; };\nstruct After { int c; };\n",
] {
let summary = cpp_code_analysis::summarize(
std::path::Path::new("/p/a.cpp"),
source,
cpp_code_analysis::SummaryKey::new(0, 0),
);
let qualified: Vec<String> = summary
.declarations
.iter()
.map(|fact| fact.qualified_name())
.collect();
assert!(
qualified.iter().any(|name| name == "After"),
"the declaration after the class has to be read: {qualified:?}"
);
if source.contains("member") {
assert!(
qualified.iter().any(|name| name.ends_with("::member")),
"a member declared after the alias has to be read too: {qualified:?}"
);
}
}
}
#[test]
fn a_template_parameter_takes_the_type_of_the_argument() {
let session = session_with(&[(
"/p/a.cpp",
"int* a_pointer = nullptr;\n\
template <class _It>\n\
auto get_itself(_It p) { return p; }\n\
template <class _Ty>\n\
auto get_through_a_pointer(_Ty* p) { return p; }\n\
void f() {\n\
auto b = get_itself(a_pointer);\n\
auto d = get_through_a_pointer(a_pointer);\n\
}\n",
)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let facts: Vec<cpp_code_analysis::DeclFact> = session
.index()
.summaries()
.flat_map(|summary| summary.declarations.iter().cloned())
.collect();
let deduced = |name: &str| -> String {
let fact = facts
.iter()
.find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto"))
.unwrap_or_else(|| panic!("`{name}` is an `auto` the file writes"));
let offset = fact.name_range.start_offset;
match session.type_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(offset),
) {
cpp_code_analysis::Known::Yes(type_of) => type_of.type_of.clone(),
other => panic!("`{name}` has a type the file gives: {other:?}"),
}
};
assert_eq!(
deduced("b"),
"int*",
"the argument the call passed is what `_It` stands for"
);
assert_ne!(
deduced("b"),
"_It",
"and the parameter's own name is not an answer"
);
}
#[test]
fn an_auto_is_deduced_from_its_initializer() {
let session = session_with(&[(
"/p/a.cpp",
"int f();\n\
long g();\n\
struct T { int a; };\n\
void h() {\n\
int y = 1;\n\
auto from_a_call = f();\n\
auto from_a_name = y;\n\
auto from_a_cast = static_cast<T>(y);\n\
auto from_an_int = 1;\n\
auto no_initializer;\n\
}\n\
auto a_return_type() { return 1; }\n",
)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let facts: Vec<cpp_code_analysis::DeclFact> = session
.index()
.summaries()
.flat_map(|summary| summary.declarations.iter().cloned())
.collect();
let deduced = |name: &str| -> String {
let fact = facts
.iter()
.find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto"))
.unwrap_or_else(|| {
panic!(
"`{name}` is declared `auto`: {:?}",
facts
.iter()
.map(|f| (&f.name, &f.type_of))
.collect::<Vec<_>>()
)
});
match cpp_code_analysis::sema::deduce::deduced_type_of(
session.index(),
&view.scopes,
&view.root,
&view.path,
fact,
) {
Known::Yes(type_of) => type_of,
other => panic!("`{name}` has a type the file gives: {other:?}"),
}
};
assert_eq!(deduced("from_a_call"), "int", "the callee's return type");
assert_eq!(deduced("from_a_name"), "int", "the name's own type");
assert_eq!(deduced("from_an_int"), "int", "a literal's type");
assert!(
deduced("from_a_cast").contains('T'),
"a cast names the type it casts to: {}",
deduced("from_a_cast")
);
{
let name = "no_initializer";
let fact = facts
.iter()
.find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto"))
.unwrap_or_else(|| panic!("`{name}` is declared `auto`"));
assert!(
matches!(
cpp_code_analysis::sema::deduce::deduced_type_of(
session.index(),
&view.scopes,
&view.root,
&view.path,
fact,
),
Known::Unknown(_)
),
"`{name}` has no initializer to read, so the answer is `Unknown` with a reason rather than a type"
);
}
}
#[test]
fn a_view_knows_the_macros_its_includes_define() {
let session = session_with(&[
(
"/p/ns.h",
"#define _MY_BEGIN namespace mine {\n#define _MY_END }\n",
),
(
"/p/a.cpp",
"#include \"ns.h\"\n_MY_BEGIN struct thing { int b; }; _MY_END\n",
),
]);
let view = session
.view("/p/a.cpp")
.expect("the file is held and the pump has read it");
fn names_in(table: &cpp_code_analysis::ScopeTree) -> Vec<String> {
fn walk(
table: &cpp_code_analysis::ScopeTree,
id: cpp_code_analysis::ScopeId,
prefix: &str,
out: &mut Vec<String>,
) {
let Some(scope) = table.scope(id) else {
return;
};
let here = match &scope.name {
Some(name) => format!("{prefix}{name}::"),
None => prefix.to_string(),
};
for binding in &scope.bindings {
out.push(format!("{here}{}", binding.name.text()));
}
for child in &scope.children {
walk(table, *child, &here, out);
}
}
let mut out = Vec::new();
if let Some(root) = table.root() {
walk(table, root, "", &mut out);
}
out
}
let names = names_in(&view.scopes);
assert!(
names.iter().any(|name| name == "mine::thing"),
"the macro's body is `namespace mine {{`, so the declaration it heads belongs to `mine`: {names:?}"
);
}
#[test]
fn a_view_gets_its_macros_one_query_later() {
let mut session = session_with(&[
(
"/p/ns.h",
"#define _MY_BEGIN namespace mine {\n#define _MY_END }\n",
),
(
"/p/a.cpp",
"#include \"ns.h\"\n_MY_BEGIN struct thing { int b; }; _MY_END\n",
),
]);
session.index_everything();
fn names_in(table: &cpp_code_analysis::ScopeTree) -> Vec<String> {
fn walk(
table: &cpp_code_analysis::ScopeTree,
id: cpp_code_analysis::ScopeId,
prefix: &str,
out: &mut Vec<String>,
) {
let Some(scope) = table.scope(id) else {
return;
};
let here = match &scope.name {
Some(name) => format!("{prefix}{name}::"),
None => prefix.to_string(),
};
for binding in &scope.bindings {
out.push(format!("{here}{}", binding.name.text()));
}
for child in &scope.children {
walk(table, *child, &here, out);
}
}
let mut out = Vec::new();
if let Some(root) = table.root() {
walk(table, root, "", &mut out);
}
out
}
let first = names_in(&session.view("/p/a.cpp").expect("held").scopes);
assert!(
first.iter().any(|name| name == "mine::thing"),
"the pump builds the closure's macros, so the declaration the macro heads is inside `mine`: {first:?}"
);
session.advance(8);
let second = names_in(&session.view("/p/a.cpp").expect("held").scopes);
assert!(
second.iter().any(|name| name == "mine::thing"),
"the next query gets the reading the work loop built: {second:?}"
);
}
#[test]
fn an_auto_written_through_a_macro_is_still_deduced() {
let session = session_with(&[(
"/p/a.cpp",
"int f();\n\
long g(int);\n\
template <class T> T h();\n\
void t() {\n\
auto plain_a = f();\n\
auto plain_b = g(1);\n\
auto plain_c = h<int>();\n\
auto a = _STD f();\n\
auto b = (_STD g) (1);\n\
auto c = _STD h<int>();\n\
}\n",
)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let facts: Vec<cpp_code_analysis::DeclFact> = session
.index()
.summaries()
.flat_map(|summary| summary.declarations.iter().cloned())
.collect();
let mut seen: Vec<String> = Vec::new();
for (name, expected) in [
("plain_a", "int"),
("plain_b", "long"),
("plain_c", "int"),
("a", "int"),
("b", "long"),
("c", "int"),
] {
let fact = facts
.iter()
.find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto"))
.unwrap_or_else(|| {
panic!(
"`{name}` is declared `auto`: {:?}",
facts
.iter()
.map(|fact| (&fact.name, &fact.type_of))
.collect::<Vec<_>>()
)
});
match cpp_code_analysis::sema::deduce::deduced_type_of(
session.index(),
&view.scopes,
&view.root,
&view.path,
fact,
) {
Known::Yes(type_of) => {
assert_eq!(type_of, expected, "`{name}`'s deduced type");
seen.push(format!("{name}={type_of}"));
}
other => seen.push(format!("{name}={other:?}")),
}
}
assert!(
seen.iter().any(|got| got == "a=int"),
"a macro-prefixed call is a call: {seen:?}"
);
}
#[test]
fn a_view_of_the_rendering_has_no_macros_left_to_guess_about() {
let session = session_with(&[
(
"/p/ns.h",
"#define _MY_BEGIN namespace mine {\n#define _MY_END }\n",
),
(
"/p/a.cpp",
"#include \"ns.h\"\n_MY_BEGIN struct thing { int b; }; _MY_END\n",
),
]);
let mut session = session;
session.add_project_files(["/p/a.cpp".into(), "/p/ns.h".into()]);
session.index_everything();
let file = session
.files()
.held("/p/a.cpp")
.expect("the file is held")
.clone();
let rendered = session
.rendering_of("/p/a.cpp")
.expect("the file's closure was read, so it renders");
assert!(
!rendered.text.contains("_MY_BEGIN"),
"the rendering has no invocation left: {}",
rendered.text
);
assert!(
rendered.text.contains("namespace mine"),
"…and what the macro stood for is written out: {}",
rendered.text
);
let view = cpp_code_analysis::FileView::parse_rendering(&file, &rendered);
let mut macro_calls = 0;
let mut stack = vec![view.root.clone()];
while let Some(node) = stack.pop() {
if cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::MacroCall {
macro_calls += 1;
}
stack.extend(node.children());
}
assert_eq!(
macro_calls, 0,
"a rendering has nothing for a macro rule to read: {macro_calls} MacroCall(s)"
);
let at_struct = rendered
.text
.find("struct thing")
.expect("the rendering has the declaration");
let in_the_file = view
.file_offset_of(cpp_code_analysis::file::coordinates::ReadingOffset::new(
at_struct,
))
.expect("a position in the rendering is a position in the file");
let written = view
.written_text()
.expect("a view of a rendering holds the file's own text");
assert!(
written[in_the_file.get()..].starts_with("struct thing"),
"the mapping points at the same spelling: file offset {in_the_file} is `{}`",
&written[in_the_file.get()..(in_the_file.get() + 12).min(written.len())]
);
assert!(
written.contains("_MY_BEGIN"),
"…and the text it points into is the one the reader wrote, macro and all"
);
}
#[test]
fn a_function_with_no_written_return_type_states_one_in_its_body() {
let session = session_with(&[(
"/p/a.cpp",
"struct beta { int* p; };\n\
auto a_literal() { return 1; }\n\
auto a_cast(int n) { return static_cast<unsigned long long>(n); }\n\
auto a_binary(int a, int b) { return a + b; }\n\
auto a_compare(int a, int b) { return a < b; }\n\
auto a_parameter(int* q) { return q; }\n\
auto a_member(beta b) { return b.p; }\n\
auto disagrees(int a, int* q) {\n\
if (a) { return reinterpret_cast<int*>(q); }\n\
return reinterpret_cast<const char*>(q);\n\
}\n",
)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let returns = |name: &str| -> Option<String> {
session
.index()
.summaries()
.flat_map(|summary| summary.declarations.iter())
.find(|fact| fact.name == name)
.unwrap_or_else(|| panic!("`{name}` is declared"))
.returns
.clone()
};
assert_eq!(
returns("a_literal").as_deref(),
Some("int"),
"a literal's type is its own"
);
assert_eq!(
returns("a_cast").as_deref(),
Some("unsigned long long"),
"a cast names the type it produces"
);
assert_eq!(
returns("a_binary").as_deref(),
Some("int"),
"two operands that agree need no conversion table"
);
assert_eq!(
returns("a_compare").as_deref(),
Some("bool"),
"a comparison is `bool` whatever its operands are"
);
assert_eq!(
returns("a_parameter").as_deref(),
Some("int*"),
"the parameter's own declaration is in the same tree"
);
let _ = &view;
assert_eq!(
returns("a_member"),
None,
"a member access needs the object's type, which is a lookup rather than a reading"
);
assert_eq!(
returns("disagrees"),
None,
"`if constexpr` makes one branch per instantiation, and this layer does not instantiate"
);
}
#[test]
fn a_conditional_has_the_type_its_arms_agree_on() {
let session = session_with(&[(
"/p/a.cpp",
"int a_value = 1;\n\
int b_value = 2;\n\
bool pick_it = true;\n\
int* p = nullptr;\n\
void f() {\n\
auto from_ints = pick_it ? a_value : b_value;\n\
auto from_a_pointer = pick_it ? p : p;\n\
auto from_mixed = pick_it ? a_value : p;\n\
}\n",
)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let facts: Vec<cpp_code_analysis::DeclFact> = session
.index()
.summaries()
.flat_map(|summary| summary.declarations.iter().cloned())
.collect();
let deduced = |name: &str| -> String {
let fact = facts
.iter()
.find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto"))
.unwrap_or_else(|| panic!("`{name}` is an `auto` the file writes"));
match session.type_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(fact.name_range.start_offset),
) {
cpp_code_analysis::Known::Yes(type_of) => type_of.type_of.clone(),
other => panic!("`{name}` has a type the file gives: {other:?}"),
}
};
assert_eq!(deduced("from_ints"), "int", "both arms are `int`");
assert_eq!(deduced("from_a_pointer"), "int*", "both arms are `int*`");
let mixed = facts
.iter()
.find(|fact| fact.name == "from_mixed" && fact.type_of.as_deref() == Some("auto"))
.expect("`from_mixed` is an `auto` the file writes");
assert!(
!matches!(
session.type_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(
mixed.name_range.start_offset
)
),
cpp_code_analysis::Known::Yes(_)
),
"the arms disagree, so the conversion decides — and this layer does not rank conversions"
);
}
#[test]
fn a_modifier_is_read_from_the_declarations_own_specifiers() {
use cpp_code_analysis::semantic::NameModifier;
let source = "namespace outer {\n\
struct Widget { static int count; };\n\
}\n\
const int limit = 3;\n\
static int file_scope = 0;\n\
int plain = 0;\n";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let names = session.classified_names(&view);
let modifiers_of = |spelling: &str| -> Vec<NameModifier> {
names
.iter()
.filter(|name| &source[name.range.start_offset..name.range.end_offset()] == spelling)
.flat_map(|name| name.modifiers.clone())
.collect()
};
assert!(
modifiers_of("limit").contains(&NameModifier::ReadOnly),
"`const int limit` is readonly"
);
assert!(
modifiers_of("file_scope").contains(&NameModifier::Static),
"`static int file_scope` is static"
);
assert!(
modifiers_of("plain").is_empty(),
"a plain `int` carries nothing"
);
assert!(
modifiers_of("Widget").is_empty(),
"a type is not readonly and not static — a modifier that cannot be true is a visible wrong claim"
);
}
#[test]
fn a_qualified_definition_is_a_fact() {
let session = session_with(&[(
"/p/a.cpp",
"class LuaSource {\npublic:\n void From(int depth);\n};\nvoid LuaSource::From(int depth) {\n (void)depth;\n}\n",
)]);
let summary = session
.index()
.summary(std::path::Path::new("/p/a.cpp"))
.expect("the file is indexed");
let names: Vec<(String, String)> = summary
.declarations
.iter()
.map(|fact| (fact.name.clone(), fact.qualified_name()))
.collect();
println!("facts: {names:?}");
assert!(
names
.iter()
.any(|(name, qualified)| name == "From" && qualified == "LuaSource::From"),
"the out-of-class definition is a fact of its own: {names:?}"
);
}
#[test]
fn the_three_shapes_of_the_real_file() {
let cases: &[(&str, &str, &str)] = &[
(
"a `std::size_t` return",
"class C {\npublic:\n unsigned long GetLine(unsigned long offset) const;\n};\nunsigned long C::GetLine(unsigned long offset) const {\n return offset;\n}\n",
"GetLine",
),
(
"a template return type",
"namespace std { template <class T> class shared_ptr { }; }\nclass C {\npublic:\n void From();\n};\nstd::shared_ptr<C> C::From() {\n return std::shared_ptr<C>();\n}\n",
"From",
),
(
"a constructor with an initialiser list",
"class C {\npublic:\n C(int n);\n};\nC::C(int n)\n : _n(n) {\n}\n",
"C",
),
(
"a static member with a template argument",
"namespace std { template <class T> class shared_ptr { }; }\nclass C {\npublic:\n void From();\n};\nstd::shared_ptr<C> C::From(int) {\n return std::shared_ptr<C>();\n}\n",
"From",
),
];
for (name, source, wanted) in cases {
let session = session_with(&[("/p/a.cpp", source)]);
let summary = session
.index()
.summary(std::path::Path::new("/p/a.cpp"))
.expect("indexed");
let found: Vec<String> = summary
.declarations
.iter()
.map(|fact| fact.qualified_name())
.collect();
println!("{name:<40} → {found:?}");
assert!(
found.iter().any(|qualified| qualified.ends_with(wanted)),
"{name} should be a fact: {found:?}"
);
}
}
#[test]
fn an_unresolved_include_does_not_erase_the_files_own_facts() {
let session = session_with(&[(
"/p/a.cpp",
"#include \"missing/Header.h\"\n#include \"missing/Other.h\"\n\nunsigned long C::GetLine(unsigned long offset) const {\n return offset;\n}\n",
)]);
let summary = session
.index()
.summary(std::path::Path::new("/p/a.cpp"))
.expect("indexed");
let found: Vec<String> = summary
.declarations
.iter()
.map(|fact| fact.qualified_name())
.collect();
println!("with unresolved includes: {found:?}");
if let Some(view) = session.view(std::path::Path::new("/p/a.cpp")) {
println!("rendering: {:?}", view.source);
} else {
println!("rendering: none");
}
assert!(
found.iter().any(|qualified| qualified.ends_with("GetLine")),
"the file's own definition survives an include nobody can resolve: {found:?}"
);
}
#[test]
fn a_template_parameter_is_not_a_declaration_at_file_scope() {
let session = session_with(&[(
"/p/a.cpp",
"template <class _Tp>\nstruct A {\n _Tp value;\n};\n",
)]);
let summary = session
.index()
.summary(std::path::Path::new("/p/a.cpp"))
.expect("indexed");
let names: Vec<&str> = summary
.declarations
.iter()
.map(|fact| &*fact.name)
.collect();
println!("facts: {names:?}");
assert!(
!names.contains(&"_Tp"),
"a template parameter is not a declaration a file-scope lookup can find: {names:?}"
);
assert!(names.contains(&"A"), "the class itself is still a fact");
assert!(
names.contains(&"value"),
"and its member is, with `_Tp` as its written type"
);
let class = summary
.declarations
.iter()
.find(|fact| fact.name == "A")
.expect("the class's own fact");
assert_eq!(
class.parameters,
["_Tp"],
"the parameters live on the fact, which is what substitution reads"
);
match session
.index()
.definitions("_Tp", std::path::Path::new("/p/a.cpp"))
{
Known::Unknown(reason) => println!("lookup `_Tp`: {reason:?}"),
Known::Yes(found) => panic!(
"`_Tp` is a template parameter, so no declaration is findable by that name: {:?}",
found
.found
.iter()
.map(|entry| entry.fact.qualified_name())
.collect::<Vec<_>>()
),
Known::No => panic!("`definitions` answers `Known`, not `No`"),
}
}
#[test]
fn a_qualified_definition_carries_its_parameter_list() {
let session = session_with(&[(
"/p/a.cpp",
"struct C {\n void f(int a, int b);\n};\nvoid C::f(int a, int b) { }\n",
)]);
let summary = session
.index()
.summary(std::path::Path::new("/p/a.cpp"))
.expect("indexed");
let found: Vec<(&str, Option<&str>)> = summary
.declarations
.iter()
.filter(|fact| fact.name == "f")
.map(|fact| (&*fact.name, fact.parameter_list.as_deref()))
.collect();
println!("facts for `f`: {found:?}");
assert!(
found.iter().any(|(_, parameters)| parameters.is_some()),
"the declaration has a list, and the definition's own is `(int a, int b)`: {found:?}"
);
}
#[test]
fn a_member_whose_return_type_a_directive_separates_is_a_member() {
let session = session_with(&[(
"/p/a.cpp",
"struct C {\n int x;\n CONSTEXPR\n iterator\n#if __cplusplus >= 201103L\n erase(const_iterator p)\n { return p; }\n#else\n erase(iterator p)\n { return p; }\n#endif\n int size();\n};\n",
)]);
let summary = session
.index()
.summary(std::path::Path::new("/p/a.cpp"))
.expect("indexed");
let found: Vec<(&str, Option<&str>, &str)> = summary
.declarations
.iter()
.filter(|fact| fact.name == "erase")
.map(|fact| {
(
&*fact.name,
fact.parameter_list.as_deref(),
fact.scope.as_deref().unwrap_or("<file scope>"),
)
})
.collect();
println!("facts for `erase`: {found:?}");
assert!(
found
.iter()
.any(|(_, parameters, scope)| parameters.is_some() && *scope == "C"),
"`erase` is a member of `C` with a parameter list: {found:?}"
);
}
#[test]
fn a_function_returning_a_reference_keeps_its_parameter_list() {
let session = session_with(&[(
"/p/a.cpp",
"struct S {\n __ostream_type& operator<<(long n) { return n; }\n Widget& value(int a, int b) { return a; }\n};\n",
)]);
let summary = session
.index()
.summary(std::path::Path::new("/p/a.cpp"))
.expect("indexed");
let found: Vec<(&str, Option<&str>)> = summary
.declarations
.iter()
.filter(|fact| matches!(fact.kind, cpp_code_analysis::DeclKind::Function))
.map(|fact| (&*fact.name, fact.parameter_list.as_deref()))
.collect();
println!("functions: {found:?}");
assert!(
found
.iter()
.any(|(name, parameters)| *name == "operator<<" && *parameters == Some("(long n)")),
"the operator keeps its list: {found:?}"
);
assert!(
found
.iter()
.any(|(name, parameters)| *name == "value" && parameters.is_some()),
"and so does the reference-returning member: {found:?}"
);
}
#[test]
fn a_return_type_a_directive_splits_is_the_branch_this_compilation_takes() {
let session = session_with(&[(
"/p/a.cpp",
"struct S {\n\
#if __cplusplus > 201402L\n\
\tWidget\n\
#else\n\
\tvoid\n\
#endif\n\
\tmake(int a);\n\
int plain(int a);\n\
};\n",
)]);
let summary = session
.index()
.summary(std::path::Path::new("/p/a.cpp"))
.expect("indexed");
let found: Vec<(&str, Option<&str>)> = summary
.declarations
.iter()
.filter(|fact| matches!(fact.kind, cpp_code_analysis::DeclKind::Function))
.map(|fact| (&*fact.name, fact.returns.as_deref()))
.collect();
println!("returns: {found:?}");
assert!(
found
.iter()
.any(|(name, returns)| *name == "make" && *returns == Some("void")),
"the `#else` branch is the one this configuration compiles, and one answer is named: {found:?}"
);
assert!(
found
.iter()
.any(|(name, returns)| *name == "plain" && *returns == Some("int")),
"and an unsplit one keeps its type: {found:?}"
);
}
#[test]
fn a_function_pointer_variable_is_drawn_as_a_function() {
let names = classified(
"\
typedef int (*binary_op)(int, int);
static int add(int a, int b) { return a + b; }
int g(binary_op callback) { return callback(1, 2); }
int f(void) { binary_op operation = add; int value = 1; return operation(value, 2); }
",
);
let kinds: Vec<(NameKind, bool)> = names
.iter()
.filter(|(text, _, _)| text == "operation")
.map(|(_, kind, declaration)| (*kind, *declaration))
.collect();
assert!(
!kinds.is_empty() && kinds.iter().all(|(kind, _)| *kind == NameKind::Function),
"a function pointer is drawn as a function, declared and used: {kinds:?}"
);
let callback: Vec<NameKind> = names
.iter()
.filter(|(text, _, _)| text == "callback")
.map(|(_, kind, _)| *kind)
.collect();
assert!(
!callback.is_empty() && callback.iter().all(|kind| *kind == NameKind::Parameter),
"a parameter stays a parameter: {callback:?}"
);
let value: Vec<NameKind> = names
.iter()
.filter(|(text, _, _)| text == "value")
.map(|(_, kind, _)| *kind)
.collect();
assert!(
!value.is_empty() && value.iter().all(|kind| *kind == NameKind::Variable),
"an ordinary variable stays a variable: {value:?}"
);
let alias: Vec<NameKind> = names
.iter()
.filter(|(text, _, _)| text == "binary_op")
.map(|(_, kind, _)| *kind)
.collect();
assert!(
!alias.is_empty() && alias.iter().all(|kind| *kind == NameKind::Type),
"and the typedef itself is still a type: {alias:?}"
);
}