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 type_of_use(source: &str, spelling: &str) -> Option<String> {
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let offset = last_word(source, spelling);
match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(found) => Some(found.type_of),
_ => None,
}
}
fn as_reading(
view: &cpp_code_analysis::FileView,
offset: usize,
) -> cpp_code_analysis::file::coordinates::ReadingOffset {
view.reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(
offset,
))
.expect("the cursor is in the rendering")
}
fn last_word(source: &str, spelling: &str) -> usize {
let is_word = |character: char| character.is_alphanumeric() || character == '_';
let mut found = None;
let mut from = 0usize;
while let Some(at) = source[from..].find(spelling) {
let start = from + at;
let end = start + spelling.len();
let before = source[..start].chars().next_back();
let after = source[end..].chars().next();
if !before.is_some_and(is_word) && !after.is_some_and(is_word) {
found = Some(start);
}
from = end;
}
found.unwrap_or_else(|| panic!("the fixture uses `{spelling}`"))
}
#[test]
fn a_using_alias_member_declares_the_type_after_the_equals() {
let source = "\
struct Widget {
using size_type = unsigned long;
size_type value;
int count;
char* name;
};
unsigned long use(Widget w) {
w.count;
w.name;
return w.value;
}
";
assert_eq!(
type_of_use(source, "count"),
Some("int".to_string()),
"the member declared after the alias keeps its own type"
);
assert_eq!(
type_of_use(source, "name"),
Some("char*".to_string()),
"and so does the one after that"
);
assert_eq!(
type_of_use(source, "value"),
Some("unsigned long".to_string()),
"the member declared *with* the alias is what the alias names"
);
}
#[test]
fn two_using_aliases_in_one_class_keep_their_own_targets() {
let source = "\
struct Widget {
using first = int;
using second = unsigned long;
first a;
second b;
};
int use(Widget w) {
w.b;
return w.a;
}
";
assert_eq!(type_of_use(source, "a"), Some("int".to_string()));
assert_eq!(type_of_use(source, "b"), Some("unsigned long".to_string()));
}
#[test]
fn an_auto_declaration_takes_the_type_of_its_initializer() {
let cases = [
(
"int count();\nint f() { auto n = count(); return n; }\n",
"n",
"int",
),
(
"struct Widget { int size; };\nint f() { auto w = Widget{}; return w.size; }\n",
"w",
"Widget",
),
(
"int f() { int base = 1; auto copy = base; return copy; }\n",
"copy",
"int",
),
(
"int f() { int base = 1; const auto& r = base; return r; }\n",
"r",
"const int&",
),
(
"int f() { int base = 1; auto p = &base; return *p; }\n",
"p",
"int*",
),
(
"template <class T> struct Box { T value; };\nint f() { auto boxed = new Box<int>(); return 0; }\n",
"boxed",
"Box<int>*",
),
(
"int f() { auto plain = new int; return 0; }\n",
"plain",
"int*",
),
(
"int f() { auto many = new int[10]; return 0; }\n",
"many",
"int*",
),
];
for (source, spelling, expected) in cases {
assert_eq!(
type_of_use(source, spelling).as_deref(),
Some(expected),
"in {source:?}"
);
}
}
#[test]
fn a_chain_of_auto_declarations_resolves() {
let source = "\
int count();
int f() {
auto first = count();
auto second = first;
const auto& third = second;
return third;
}
";
assert_eq!(type_of_use(source, "first").as_deref(), Some("int"));
assert_eq!(type_of_use(source, "second").as_deref(), Some("int"));
assert_eq!(type_of_use(source, "third").as_deref(), Some("const int&"));
}
#[test]
fn the_written_decoration_is_kept() {
let source = "\
int f() {
int base = 1;
const auto& kept = base;
auto* pointer = &base;
return kept;
}
";
assert_eq!(type_of_use(source, "kept").as_deref(), Some("const int&"));
assert_eq!(type_of_use(source, "pointer").as_deref(), Some("int*"));
}
#[test]
fn a_forwarding_reference_collapses() {
let from_a_value = "int f() { auto&& bound = 42; return bound; }\n";
assert_eq!(type_of_use(from_a_value, "bound").as_deref(), Some("int&&"));
let from_a_reference = "\
struct Widget { int size; };
Widget &the_widget();
int f() { auto&& bound = the_widget(); return bound.size; }
";
assert_eq!(
type_of_use(from_a_reference, "bound").as_deref(),
Some("Widget&")
);
let from_a_name = "int f() { int base = 1; auto&& bound = base; return bound; }\n";
assert_eq!(type_of_use(from_a_name, "bound").as_deref(), Some("int&"));
}
#[test]
fn auto_reference_on_a_reference_returns_one_reference() {
let source = "\
struct Widget { int size; };
Widget &the_widget();
int f() {
auto &widget = the_widget();
return widget.size;
}
";
assert_eq!(
type_of_use(source, "widget").as_deref(),
Some("Widget&"),
"a reference in the initializer never survives into `auto`"
);
}
#[test]
fn a_pointer_declaration_needs_a_pointer_initializer() {
let source = "int f() { int base = 1; auto* wrong = base; return base; }\n";
assert_eq!(type_of_use(source, "wrong"), None);
}
#[test]
fn a_declaration_that_refers_to_itself_is_refused_rather_than_looping() {
let source = "int f() { auto x = x; return 0; }\n";
assert_eq!(type_of_use(source, "x"), None);
}
#[test]
fn a_declaration_with_no_initializer_is_refused() {
let source = "int f() { auto n; return 0; }\n";
assert_eq!(type_of_use(source, "n"), None);
}
#[test]
fn an_auto_declaration_in_another_file_is_refused() {
let header = "int count();\nauto measured = count();\n";
let source = "#include \"b.h\"\nint f() { return measured; }\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 offset = last_word(source, "measured");
match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(found) => assert_ne!(
found.type_of, "auto",
"the placeholder is never reported as a type"
),
cpp_code_analysis::Known::Unknown(_) | cpp_code_analysis::Known::No => {}
}
}
#[test]
fn a_member_access_through_auto_lists_the_members() {
let source = "\
struct Widget { int size; int scaled(int factor) const; };
int f() {
auto w = Widget{};
w.
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let offset = source.rfind("w.").expect("the fixture writes the access") + 2;
match session.member_completions(
&view,
cpp_code_analysis::file::coordinates::FileOffset::new(offset),
) {
cpp_code_analysis::Known::Yes(found) => {
let names: Vec<String> = found
.members
.members
.iter()
.map(|member| member.fact.name.to_string())
.collect();
assert!(
names.contains(&"size".to_string()) && names.contains(&"scaled".to_string()),
"the members of the deduced class: {names:?}"
);
}
other => panic!("an `auto` object's members are listable now, got {other:?}"),
}
}
#[test]
fn a_declaration_that_names_its_type_keeps_it() {
assert_eq!(
type_of_use(
"struct Widget { int size; };\nint f() { const Widget* w = nullptr; return 0; }\n",
"w"
)
.as_deref(),
Some("const Widget*")
);
}
#[test]
fn a_member_of_a_class_behind_a_linkage_specification_resolves() {
let source = "\
namespace lib {
extern \"C++\" template <class _Elem>
class Stream {
public:
int member;
};
extern Stream<char> input;
}
int f() { return lib::input.member; }
";
assert_eq!(type_of_use(source, "member").as_deref(), Some("int"));
}
#[test]
fn a_name_declared_twice_with_one_type_still_has_that_type() {
let header = "struct Widget { int size; };\nextern Widget shared;\nextern Widget shared;\n";
let source = "#include \"lib.h\"\nint f() { return shared.size; }\n";
let session = session_with(&[("/p/a.cpp", source), ("/p/lib.h", header)]);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "shared").as_deref(),
Some("Widget"),
"the two declarations agree, so the type is not the ambiguous part"
);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "size").as_deref(),
Some("int"),
"and the member access through it works"
);
}
#[test]
fn two_declarations_that_disagree_about_the_type_are_still_unknown() {
let header =
"struct One { int a; };\nstruct Two { int b; };\nextern One shared;\nextern Two shared;\n";
let source = "#include \"lib.h\"\nint f() { return shared.a; }\n";
let session = session_with(&[("/p/a.cpp", source), ("/p/lib.h", header)]);
assert_eq!(type_of_use_in(&session, "/p/a.cpp", source, "shared"), None);
}
#[test]
fn a_deduction_cycle_answers_unknown_instead_of_overflowing_the_stack() {
let source = "\
struct Tokens { const char* text(const char* s) const; };
extern Tokens tokens;
const char* lookup(const char* key);
auto text_of(int file) { return lookup(tokens.text(text_of(file).content)); }
const char* g(int f) { return text_of(f).content; }
";
let session = session_with(&[("/p/cycle.cpp", source)]);
assert_eq!(
type_of_use_in(&session, "/p/cycle.cpp", source, "content"),
None,
"a question that needs its own answer is not answerable, and saying so is the whole point"
);
}
fn type_of_use_in(
session: &Session<MemoryFiles>,
path: &str,
source: &str,
spelling: &str,
) -> Option<String> {
let view = session.view(path).expect("the file is held");
let offset = last_word(source, spelling) + spelling.len() - 1;
match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(found) => Some(found.type_of),
_ => None,
}
}
#[test]
fn a_qualified_name_in_this_file_has_the_type_its_declaration_wrote() {
let source = "\
namespace lib {
struct Widget { int size; };
extern Widget global;
}
int f() { return lib::global.size; }
";
assert_eq!(type_of_use(source, "global").as_deref(), Some("Widget"));
assert_eq!(
type_of_use(source, "size").as_deref(),
Some("int"),
"and a member access through it reads the member's type"
);
}
#[test]
fn a_qualified_name_declared_in_a_header_has_its_type() {
let header = "namespace lib { struct Widget { int size; }; extern Widget shared; }\n";
let source = "#include \"lib.h\"\nint f() { return lib::shared.size; }\n";
let session = session_with(&[("/p/a.cpp", source), ("/p/lib.h", header)]);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "shared").as_deref(),
Some("Widget"),
"the declaration is in the header, so the answer comes from the index"
);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "size").as_deref(),
Some("int"),
"and the member access through it reads the member"
);
}
#[test]
fn a_member_of_a_class_declared_in_a_header_has_its_type_in_the_body() {
let header = "\
struct Token { int kind; };
struct Parser {
Token _token;
int Parse();
};
";
let source = "\
#include \"api.h\"
int Parser::Parse() { return _token.kind; }
";
let session = session_with(&[("/p/a.cpp", source), ("/p/api.h", header)]);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "_token").as_deref(),
Some("Token"),
);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "kind").as_deref(),
Some("int"),
"and the member access through it reads the member's own type"
);
}
#[test]
fn a_member_name_several_classes_declare_is_the_enclosing_class() {
let header = "\
struct Token { int kind; };
struct Lexer {
Token _token;
};
struct Parser {
Token _token;
int Parse();
};
";
let source = "\
#include \"api.h\"
int Parser::Parse() { return _token.kind; }
";
let session = session_with(&[("/p/a.cpp", source), ("/p/api.h", header)]);
eprintln!(
"definition(_token) = {:?}",
session
.index()
.definition("_token", std::path::Path::new("/p/a.cpp"))
);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "_token").as_deref(),
Some("Token"),
"the enclosing class's member, not an ambiguous name"
);
}
#[test]
fn a_member_of_an_unnamed_union_has_a_type_and_its_members_are_reachable() {
let source = "\
struct MarkEvent {
int Type;
union {
struct { int Parent; int Kind; } Start;
struct { int Index; } Token;
} U;
};
int f(MarkEvent e) { return e.U.Start.Kind; }
";
assert_eq!(type_of_use(source, "U").as_deref(), Some("MarkEvent::U"));
assert_eq!(
type_of_use(source, "Start").as_deref(),
Some("MarkEvent::U::Start")
);
assert_eq!(
type_of_use(source, "Kind").as_deref(),
Some("int"),
"the chain ends at the real member's type"
);
}
#[test]
fn a_member_of_a_class_template_takes_its_type_from_the_arguments() {
let header = "\
namespace std {
template <class _Ty, class _Alloc = int>
struct vector {
_Ty& front;
_Ty* data();
};
}
";
let source = "\
#include \"vector.h\"
int f() {
std::vector<int> v;
return *v.data() + v.front;
}
";
let session = session_with(&[("/p/a.cpp", source), ("/p/vector.h", header)]);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "v").as_deref(),
Some("std::vector<int>"),
"the declaration's own type is the type it was written with"
);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "data").as_deref(),
Some("int*"),
"`data` is declared `_Ty*`, and `_Ty` is `int` here"
);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "front").as_deref(),
Some("int&"),
"and `front` is declared `_Ty&`"
);
}
#[test]
fn a_member_function_inside_a_call_has_what_the_call_has() {
let header = "\
namespace std {
template <class _Ty>
struct vector { _Ty* data(); };
}
";
let source = "\
#include \"vector.h\"
int f() {
std::vector<int> v;
return *v.data();
}
";
let session = session_with(&[("/p/a.cpp", source), ("/p/vector.h", header)]);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "data").as_deref(),
Some("int*"),
"the callee inside a call has the return type, arguments substituted"
);
}
#[test]
fn a_member_function_that_is_not_called_has_no_type() {
let header = "\
namespace std {
template <class _Ty>
struct vector { _Ty* data(); };
}
";
let source = "\
#include \"vector.h\"
int f() {
std::vector<int> v;
v.data;
return 0;
}
";
let session = session_with(&[("/p/a.cpp", source), ("/p/vector.h", header)]);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "data"),
None,
"a function named on its own has no type"
);
}
#[test]
fn a_member_of_a_class_reached_through_an_alias_gets_the_aliass_arguments() {
let header = "\
namespace std {
template <class _Elem>
struct basic_string {
using value_type = _Elem;
using reference = value_type&;
reference back();
reference front;
};
using string = basic_string<char>;
}
";
let source = "\
#include \"string.h\"
int f() {
std::string s;
return s.front;
}
int g() {
std::string s;
auto& back = s.back();
return back;
}
";
let session = session_with(&[("/p/a.cpp", source), ("/p/string.h", header)]);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "front").as_deref(),
Some("char&"),
"`reference` is `value_type&` is `_Elem&`, and `string` says `_Elem` is `char`"
);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "back").as_deref(),
Some("char&"),
"and the same for a member that is *called*, when the declarator asks for a reference"
);
}
#[test]
fn a_member_whose_type_is_a_nested_alias_is_resolved() {
let header = "\
namespace std {
template <class _Ty>
struct vector {
typedef _Ty& reference;
reference front;
};
}
";
let source = "\
#include \"vector.h\"
int f() {
std::vector<int> v;
return v.front;
}
";
let session = session_with(&[("/p/a.cpp", source), ("/p/vector.h", header)]);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "front").as_deref(),
Some("int&"),
"`reference` is `_Ty&` and `_Ty` is `int`, one member lookup further in"
);
}
#[test]
fn a_chain_of_nested_types_resolves() {
let source = "\
namespace std {
template <class _Ty>
struct vector {
typedef unsigned long size_type;
typedef size_type difference_type;
difference_type count;
};
}
int f() {
std::vector<int> v;
return (int)v.count;
}
";
let session = session_with(&[("/p/a.cpp", source)]);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "count").as_deref(),
Some("unsigned long"),
"two members deep, and the name that ends the chain is the type"
);
}
#[test]
fn a_using_alias_resolves_like_a_typedef() {
let source = "\
namespace std {
template <class _Ty>
struct vector {
using size_type = unsigned long;
size_type count;
};
}
int f() {
std::vector<int> v;
return (int)v.count;
}
";
let session = session_with(&[("/p/a.cpp", source)]);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "count").as_deref(),
Some("unsigned long"),
"`using size_type = unsigned long;` is the same fact as `typedef unsigned long size_type;`"
);
}
#[test]
fn a_template_without_arguments_keeps_its_parameters() {
let source = "\
namespace std {
template <class _Ty>
struct vector { typedef _Ty& reference; };
}
int f() { std::vector v; return 0; }
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let names = session
.index()
.template_parameters_of("std::vector", &view.path);
assert_eq!(
names,
vec!["_Ty".to_string()],
"the parameter list is read out of the declaration"
);
}
#[test]
fn a_nested_class_template_declares_its_own_parameters() {
let source = "\
namespace std {
template <class _Ty>
struct outer {
template <class _Uty>
struct inner { _Uty u; };
};
}
int f() { return 0; }
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let names = session
.index()
.template_parameters_of("std::outer::inner", &view.path);
assert_eq!(
names,
vec!["_Uty".to_string()],
"the innermost template is the one that introduces the class"
);
}
#[test]
fn a_variable_template_takes_its_type_from_the_arguments() {
let header = "\
#pragma once
template <class T>
constexpr T pi = T(3.14159);
template <class T, class U = T>
constexpr U twice = U(2);
";
let source = "\
#include \"constants.h\"
double f() {
double a = pi<double>;
// A two-argument template-id is a separate question: measured, `ratio<float, double>` answers `None`, which is the
// shape of the oldest ambiguity in C++ — `a < b, c > d` — and it belongs to the expression reader, not here.
return a + b;
}
";
let session = session_with(&[("/p/a.cpp", source), ("/p/constants.h", header)]);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "pi").as_deref(),
Some("double"),
"`pi` is declared `T`, and `T` is `double` here"
);
}
#[test]
fn a_defaulted_template_parameter_of_a_variable_template_substitutes() {
let header = "\
#pragma once
template <class T, class U = T>
constexpr U twice = U(2);
";
let source = "\
#include \"constants.h\"
float f() {
float b = twice<float>;
return b;
}
";
let session = session_with(&[("/p/a.cpp", source), ("/p/constants.h", header)]);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "twice").as_deref(),
Some("float"),
"the second parameter defaults to `T`, which the use wrote as `float`"
);
}
#[test]
fn a_compiler_builtin_reads_as_a_bool_and_the_library_lookalike_does_not() {
use cpp_code_analysis::sema::types::parse_type_spelling;
for builtin in [
"__is_constructible(_Ty, _Args...)",
"__is_pointer(_Ty)",
"__is_same(_Ty, _Uty)",
"__is_trivially_copyable(_Ty)",
] {
assert_eq!(
parse_type_spelling(builtin),
parse_type_spelling("bool"),
"`{builtin}` is a question the compiler answers, and its answer is a bool"
);
}
assert_ne!(
parse_type_spelling("is_same<_Ty, _Uty>"),
parse_type_spelling("bool"),
"the library's own `is_same` is a class template, not an intrinsic"
);
}
#[test]
fn a_trait_a_builtin_decides_selects_the_right_specialization() {
let header = "\
#pragma once
template <bool _Test, class _Ty = void>
struct enable_if {};
template <class _Ty>
struct enable_if<true, _Ty> {
using type = _Ty;
};
template <bool _Test, class _Ty = void>
using enable_if_t = typename enable_if<_Test, _Ty>::type;
";
let source = "\
#include \"enable_if.h\"
struct Widget {
enable_if_t<__is_same(int, int), double> when_the_same;
enable_if_t<__is_pointer(int*), float> when_a_pointer;
};
void f(Widget& w) {
double a = w.when_the_same;
float b = w.when_a_pointer;
}
";
let session = session_with(&[("/p/a.cpp", source), ("/p/enable_if.h", header)]);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "when_the_same").as_deref(),
Some("double"),
"`__is_same(int, int)` is decided `true`, so the specialization with a `type` is the one that applies"
);
assert_eq!(
type_of_use_in(&session, "/p/a.cpp", source, "when_a_pointer").as_deref(),
Some("float"),
"and `__is_pointer(int*)` is decided `true` the same way"
);
}
#[test]
fn an_alias_target_is_substituted_by_whole_words() {
use cpp_code_analysis::sema::types::substituted_spelling;
let names = vec!["_Test".to_string(), "_Ty".to_string()];
let arguments = vec!["__is_same(int, int)".to_string(), "double".to_string()];
assert_eq!(
substituted_spelling("typename enable_if<_Test, _Ty>::type", &names, &arguments),
"typename enable_if<__is_same(int, int), double>::type",
"both parameters are replaced, and the names the alias did not write are left alone"
);
assert_eq!(
substituted_spelling("_Ty2", &names, &arguments),
"_Ty2",
"`_Ty` is a prefix of `_Ty2`, and a substring replacement would have rewritten it"
);
assert_eq!(
substituted_spelling(
"vector<_Ty>",
&names,
&["int".to_string(), "double".to_string()]
),
"vector<double>",
"an argument that mentions another parameter is not re-substituted"
);
}
#[test]
fn an_auto_variable_takes_the_templated_temporarys_type() {
let source = "\
namespace std {
template <class T>
class vector;
}
void f() {
auto z = std::vector<int>();
}
";
assert_eq!(
type_of_use(source, "z").as_deref(),
Some("std::vector<int>"),
"the argument is part of the type the declaration has"
);
}
#[test]
fn an_auto_variable_takes_the_calls_return_type() {
let source = "\
std::string g();
void f() {
auto y = g();
}
";
assert_eq!(type_of_use(source, "y").as_deref(), Some("std::string"));
}
#[test]
fn a_members_return_type_has_the_class_arguments_substituted() {
let source = "\
namespace std {
template <class Elem>
class basic_string {
public:
Elem& back();
};
using string = basic_string<char>;
}
void f() {
std::string x;
auto& y = x.back();
}
";
assert_eq!(
type_of_use(source, "y").as_deref(),
Some("char&"),
"`back()` on a `basic_string<char>` returns `char&`, and the declarator asked for a reference"
);
}
#[test]
fn a_member_return_type_is_substituted_through_a_template_id_use() {
let source = "\
namespace std {
template <class T>
class vector {
public:
T& front();
};
}
void f() {
std::vector<int> v;
auto& z = v.front();
}
";
assert_eq!(type_of_use(source, "z").as_deref(), Some("int&"));
}
#[test]
fn a_subscript_has_the_operators_return_type() {
use cpp_code_analysis::file::coordinates::FileOffset;
let source = "\
namespace std {
template <class T>
class vector {
public:
T& at(unsigned long index);
T& operator[](unsigned long index);
};
}
void f() {
std::vector<int> v;
int x = v[0];
(void)x;
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is cooked");
let at = source.find("v[0]").expect("the fixture subscripts") + 1;
let reading = view
.reading_offset_of(FileOffset::new(at))
.expect("the offset is in the file");
let answer = match session.type_at(&view, reading) {
cpp_code_analysis::Known::Yes(found) => Some(found.type_of),
other => {
println!("`v[0]` at file {at} → {other:?}");
None
}
};
println!("`v[0]` is {answer:?}");
assert_eq!(
answer.as_deref(),
Some("int&"),
"a subscript is `operator[]`, whose return type is the class's `T&` at `int`"
);
}
#[test]
fn a_subscript_whose_operator_returns_the_classs_own_reference() {
use cpp_code_analysis::file::coordinates::FileOffset;
let source = "\
template <class _CharT>
class basic_string {
public:
typedef _CharT& reference;
reference operator[](unsigned long index);
};
void f() {
basic_string<char> s;
char c = s[0];
(void)c;
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is cooked");
let at = source.find("s[0]").expect("the fixture subscripts") + 1;
let reading = view
.reading_offset_of(FileOffset::new(at))
.expect("the offset is in the file");
let answer = match session.type_at(&view, reading) {
cpp_code_analysis::Known::Yes(found) => Some(found.type_of),
other => {
println!("`s[0]` at file {at} → {other:?}");
None
}
};
assert_eq!(
answer.as_deref(),
Some("char&"),
"`reference` is the class's own alias for `_CharT&`, and `_CharT` is `char`"
);
}
#[test]
fn a_member_of_an_unnamed_union_and_of_an_unnamed_struct_inside_it() {
use cpp_code_analysis::file::coordinates::FileOffset;
const SOURCE: &str = "\
enum class Kind { None, Start };
struct MarkEvent {
int Type;
union {
struct { unsigned long Parent; Kind KindOf; } Start;
struct { unsigned long Index; Kind Token; } Token;
} U;
};
void f(MarkEvent &event) {
event.U.Start.KindOf = Kind::None;
unsigned long p = event.U.Start.Parent;
}
";
let session = session_with(&[("/p/a.cpp", SOURCE)]);
let view = session.view("/p/a.cpp").expect("cooked");
let answered = |needle: &str| {
let at = SOURCE.find(needle).expect("the fixture writes it") + needle.len() - 1;
let reading = view
.reading_offset_of(FileOffset::new(at))
.expect("the offset is in the file");
match session.type_at(&view, reading) {
cpp_code_analysis::Known::Yes(found) => Some(found.type_of),
cpp_code_analysis::Known::No => None,
cpp_code_analysis::Known::Unknown(reason) => {
println!("`{needle}` → unknown({reason:?})");
None
}
}
};
assert_eq!(
answered("event.U").as_deref(),
Some("MarkEvent::U"),
"the union is named after the scope it is written in"
);
assert_eq!(
answered("event.U.Start").as_deref(),
Some("MarkEvent::U::Start"),
"and so is the unnamed struct inside it"
);
assert_eq!(
answered("event.U.Start.KindOf").as_deref(),
Some("Kind"),
"a member of the unnamed struct is a member like any other"
);
assert_eq!(
answered("event.U.Start.Parent").as_deref(),
Some("unsigned long")
);
}
#[test]
fn a_containers_element_access_through_the_allocator_chain() {
use cpp_code_analysis::file::coordinates::FileOffset;
const SOURCE: &str = "\
namespace mine {
template <typename Tp>
class allocator {
public:
typedef Tp value_type;
template <typename Tp1>
struct rebind { typedef allocator<Tp1> other; };
};
template <typename Alloc>
struct allocator_traits {
typedef typename Alloc::value_type value_type;
template <typename Up>
using rebind_alloc = typename Alloc::template rebind<Up>::other;
};
}
namespace mygnu {
template <typename Alloc>
struct alloc_traits : mine::allocator_traits<Alloc> {
typedef mine::allocator_traits<Alloc> base_type;
typedef typename base_type::value_type value_type;
typedef value_type& reference;
template <typename Tp>
struct rebind { typedef typename base_type::template rebind_alloc<Tp> other; };
};
template <typename Tp, typename Alloc>
struct vector_base {
typedef typename mygnu::alloc_traits<Alloc>::template rebind<Tp>::other tp_alloc_type;
};
template <typename Tp, typename Alloc>
class vector : protected vector_base<Tp, Alloc> {
typedef vector_base<Tp, Alloc> base;
typedef typename base::tp_alloc_type tp_alloc_type;
typedef mygnu::alloc_traits<tp_alloc_type> alloc_traits_type;
public:
typedef typename alloc_traits_type::reference reference;
reference at(int i);
reference operator[](int i);
};
}
void f() {
mygnu::vector<int, mine::allocator<int>> v;
int x = v[0];
int y = v.at(1);
(void)x;
(void)y;
}
";
let session = session_with(&[("/p/a.cpp", SOURCE)]);
let view = session.view("/p/a.cpp").expect("cooked");
let answered = |needle: &str| {
let at = SOURCE.find(needle).expect("the fixture writes it") + 2;
let reading = view
.reading_offset_of(FileOffset::new(at))
.expect("the offset is in the file");
match session.type_at(&view, reading) {
cpp_code_analysis::Known::Yes(found) => Some(found.type_of),
cpp_code_analysis::Known::No => None,
cpp_code_analysis::Known::Unknown(reason) => {
println!("`{needle}` → unknown({reason:?})");
None
}
}
};
assert_eq!(
answered("v[0]").as_deref(),
Some("int"),
"a subscript on `vector<int, allocator<int>>` is `operator[]`'s `reference`, and `reference` is `int&` — \
answered here as its decayed value, which is what a cursor on `v[0]` is asking about"
);
assert_eq!(
answered("v.at(1)").as_deref(),
Some("int&"),
"and a call of `at` is the same alias chain, answered as the reference it is"
);
}
#[test]
fn a_structured_binding_in_a_range_for_has_the_paired_type() {
let source = "\
#include <map>
#include <string>
int f() {
std::map<int, std::string> myMap;
for (auto [key, value] : myMap) {
value.size();
int k = key;
(void)k;
}
return 0;
}
";
let header = "namespace std { template <class K, class V> struct map { }; template <class C> struct basic_string { }; }\n";
let files = MemoryFiles::new()
.with_file("/p/map", header)
.with_file("/p/string", header)
.with_file("/p/a.cpp", source);
let providers = SessionFiles::new(OpenDocuments::new(), files);
let mut session = Session::with_config(
"/p",
providers,
WatchFilter::new("/p"),
CompilerConfig::default(),
);
session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
let view = session.view("/p/a.cpp").expect("a view");
let type_of = |needle: &str| {
let at = source.find(needle).expect("the fixture writes it")
+ needle
.len()
.saturating_sub(needle.trim_start_matches(['=', ' ', '(', ')']).len());
let reading = view
.reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(at))
.expect("the cursor is in the rendering");
match session.type_at(&view, reading) {
cpp_code_analysis::Known::Yes(found) => found.type_of,
other => panic!("`{needle}` has a type: {other:?}"),
}
};
assert_eq!(
type_of("value.size"),
"std::string",
"the second component of `map<int, std::string>`"
);
assert_eq!(
type_of("= key"),
"const int",
"and the key is the first, `const` as a map's key is"
);
}
#[test]
fn a_range_for_variable_has_the_element_type() {
let source = "\
#include <vector>
#include <map>
#include <string>
int f() {
std::vector<int> values;
for (auto x : values) {
int k1 = x;
(void)k1;
}
std::map<int, std::string> myMap;
for (auto it : myMap) {
int k2 = it;
(void)k2;
}
return 0;
}
";
let vector = "namespace std { template <class T> struct vector { }; }\n";
let map = "namespace std { template <class K, class V> struct map { }; template <class A, class B> struct pair { }; }\n";
let string = "namespace std { template <class C> struct basic_string { }; typedef basic_string<char> string; }\n";
let files = MemoryFiles::new()
.with_file("/p/vector", vector)
.with_file("/p/map", map)
.with_file("/p/string", string)
.with_file("/p/a.cpp", source);
let providers = SessionFiles::new(OpenDocuments::new(), files);
let mut session = Session::with_config(
"/p",
providers,
WatchFilter::new("/p"),
CompilerConfig::default(),
);
session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
let view = session.view("/p/a.cpp").expect("a view");
let type_of = |needle: &str| {
let at = source.find(needle).expect("the fixture writes it") + needle.len();
let reading = view
.reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(at))
.expect("the cursor is in the rendering");
match session.type_at(&view, reading) {
cpp_code_analysis::Known::Yes(found) => found.type_of,
other => panic!("`{needle}` has a type: {other:?}"),
}
};
assert_eq!(type_of("k1 = "), "int", "the element of a `vector<int>`");
let pair = type_of("k2 = ");
assert!(
pair.contains("pair<const int, std::string>"),
"the element of a `map<int, std::string>` is that pair: {pair}"
);
}
#[test]
fn an_iterator_call_has_the_element_type() {
let source = "\
#include <map>
#include <string>
int f() {
std::map<int, std::string> myMap;
auto it = myMap.begin();
int k = it;
(void)k;
return 0;
}
";
let map = "namespace std { template <class K, class V> struct map { }; template <class A, class B> struct pair { }; }\n";
let string = "namespace std { template <class C> struct basic_string { }; typedef basic_string<char> string; }\n";
let files = MemoryFiles::new()
.with_file("/p/map", map)
.with_file("/p/string", string)
.with_file("/p/a.cpp", source);
let providers = SessionFiles::new(OpenDocuments::new(), files);
let mut session = Session::with_config(
"/p",
providers,
WatchFilter::new("/p"),
CompilerConfig::default(),
);
session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
let view = session.view("/p/a.cpp").expect("a view");
let at = source.find("k = it").expect("the fixture") + "k = ".len();
let reading = view
.reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(at))
.expect("the cursor is in the rendering");
match session.type_at(&view, reading) {
cpp_code_analysis::Known::Yes(found) => {
println!("it: {}", found.type_of);
assert!(
found.type_of.contains("pair<const int, std::string>"),
"`begin()` yields the map's element: {}",
found.type_of
);
}
other => panic!("`it` has a type: {other:?}"),
}
}
#[test]
fn dereferencing_an_iterator_yields_the_element() {
let source = "\
#include \"map.h\"
#include \"string.h\"
int f() {
std::map<int, std::string> myMap;
auto it = myMap.begin();
auto element = *it;
int k = element;
(void)k;
return 0;
}
";
let map = "namespace std { template <class K, class V> struct map { }; template <class A, class B> struct pair { A first; B second; }; }\n";
let string = "namespace std { template <class C> struct basic_string { }; typedef basic_string<char> string; }\n";
let files = MemoryFiles::new()
.with_file("/p/map.h", map)
.with_file("/p/string.h", string)
.with_file("/p/a.cpp", source);
let providers = SessionFiles::new(OpenDocuments::new(), files);
let mut session = Session::with_config(
"/p",
providers,
WatchFilter::new("/p"),
CompilerConfig::default(),
);
session.add_project_files([
std::path::PathBuf::from("/p/map.h"),
std::path::PathBuf::from("/p/string.h"),
std::path::PathBuf::from("/p/a.cpp"),
]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
let view = session.view("/p/a.cpp").expect("a view");
let at = source.find("k = element").expect("the fixture") + "k = ".len();
let reading = view
.reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(at))
.expect("the cursor is in the rendering");
match session.type_at(&view, reading) {
cpp_code_analysis::Known::Yes(found) => {
println!("element: {}", found.type_of);
assert!(
found.type_of.contains("pair<const int, std::string>"),
"`*it` is the element: {}",
found.type_of
);
}
other => panic!("`element` has a type: {other:?}"),
}
}
#[test]
fn a_class_own_operators_have_their_declared_return_type() {
let source = "\
struct Money {
int cents;
Money operator+(const Money& other) const;
int operator*() const;
int operator[](int at) const;
int operator()(int times) const;
Money operator-() const;
};
int f() {
Money a;
Money sum = a + a;
int deref = *a;
int at = a[0];
int times = a(3);
Money neg = -a;
(void)sum; (void)deref; (void)at; (void)times; (void)neg;
return 0;
}
";
let files = MemoryFiles::new().with_file("/p/a.cpp", source);
let providers = SessionFiles::new(OpenDocuments::new(), files);
let mut session = Session::with_config(
"/p",
providers,
WatchFilter::new("/p"),
CompilerConfig::default(),
);
session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
let view = session.view("/p/a.cpp").expect("a view");
let type_of = |needle: &str| {
let at = source.find(needle).expect("the fixture writes it") + needle.len();
let reading = view
.reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(at))
.expect("the cursor is in the rendering");
match session.type_at(&view, reading) {
cpp_code_analysis::Known::Yes(found) => found.type_of,
other => panic!("`{needle}` has a type: {other:?}"),
}
};
match session.members_of(&view, "Money") {
cpp_code_analysis::Known::Yes(list) => println!(
"members of Money: {:?}",
list.members
.iter()
.map(|member| (member.fact.name.to_string(), member.fact.returns.clone()))
.collect::<Vec<_>>()
),
other => println!("members of Money: {other:?}"),
}
assert_eq!(type_of("Money sum = "), "Money", "operator+ returns Money");
assert_eq!(type_of("int deref = "), "int", "operator* returns int");
assert_eq!(type_of("int at = a"), "int", "operator[] returns int");
assert_eq!(type_of("int times = a"), "int", "operator() returns int");
assert_eq!(
type_of("Money neg = "),
"Money",
"unary operator- returns Money"
);
}
#[test]
fn a_typedef_of_a_class_body_names_its_members() {
let source = "\
typedef struct { int a; int b; } Object;
typedef struct Tag { int d; } Alias;
struct Plain { int e; } plain;
int f(void) { Object o; return o.a; }
int g(void) { return plain.d; }
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let members = |class: &str| match session.members_of(&view, class) {
cpp_code_analysis::Known::Yes(list) => {
assert!(
list.unlisted.is_empty(),
"`{class}` is fully declared here: {:?}",
list.unlisted
);
list.members
.iter()
.map(|member| member.fact.name.to_string())
.collect::<Vec<_>>()
}
other => panic!("`{class}` has a member list: {other:?}"),
};
assert_eq!(
members("Object"),
["a", "b"],
"the unnamed body is `Object`"
);
assert_eq!(members("Alias"), ["d"], "the alias follows to its tag");
assert_eq!(members("Tag"), ["d"], "and the tag answers on its own");
assert_eq!(members("Plain"), ["e"], "a named body with a variable");
assert_eq!(
type_of_use(source, "plain").as_deref(),
Some("Plain"),
"a named body types its variable as the tag"
);
assert_eq!(
type_of_use(source, "o").as_deref(),
Some("Object"),
"an unnamed body behind a typedef types the variable as the typedef"
);
assert_eq!(
type_of_use(source, "a").as_deref(),
Some("int"),
"and `o.a` is the member the body declares"
);
}
#[test]
fn a_struct_defined_after_its_typedef_answers_for_the_alias() {
let source = "\
typedef char *(*LineGetter)(int, void *, int, bool);
typedef struct exarg exarg_T;
struct exarg { char *arg; int addr_count; struct { bool file; bool bar; } magic; };
struct exarg raw;
int f(void) { exarg_T eap; return eap.addr_count; }
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let members = |class: &str| match session.members_of(&view, class) {
cpp_code_analysis::Known::Yes(list) => list
.members
.iter()
.map(|member| member.fact.name.to_string())
.collect::<Vec<_>>(),
other => panic!("`{class}` has a member list: {other:?}"),
};
let tag = ["addr_count", "arg", "magic"];
assert_eq!(members("exarg"), tag, "the tag's own members");
assert_eq!(members("exarg_T"), tag, "and the alias reaches them");
assert_eq!(
type_of_use(source, "eap").as_deref(),
Some("exarg_T"),
"a variable declared with the alias keeps the alias"
);
assert_eq!(
type_of_use(source, "addr_count").as_deref(),
Some("int"),
"and its member access is typed through the tag's body"
);
assert_eq!(
type_of_use(source, "raw").as_deref(),
Some("exarg"),
"`struct exarg` spells the type `exarg`"
);
}
#[test]
fn an_anonymous_unions_members_are_facts_of_the_struct_it_is_declared_in() {
let header = "\
struct line {
char colour;
union {
long integer;
double real;
}; /* anonymous */
};
";
let source = "#include \"corpus.h\"\nint f(struct line *line) { return (int)line->integer; }\n";
let session = session_with(&[("/p/corpus.h", header), ("/p/a.c", source)]);
let view = session.view("/p/a.c").expect("the file is held");
let members = match session.members_of(&view, "line") {
cpp_code_analysis::Known::Yes(list) => list
.members
.iter()
.map(|member| member.fact.name.to_string())
.collect::<Vec<_>>(),
other => panic!("`line` has a member list: {other:?}"),
};
assert!(
members.iter().any(|name| name == "integer"),
"the union is anonymous, so `integer` is `line`'s member: {members:?}"
);
}
#[test]
fn an_unnamed_struct_type_is_keyed_by_the_variable_it_declares() {
let source = "int f(void) { struct { unsigned three : 3; unsigned four : 3; } bits = {5, 1}; return (int)bits.three; }\n";
let session = session_with(&[("/p/a.c", source)]);
let view = session.view("/p/a.c").expect("the file is held");
assert_eq!(
type_of_use(source, "bits").as_deref(),
Some("bits"),
"the query path keys the type by the variable's own name"
);
let members = match session.members_of(&view, "bits") {
cpp_code_analysis::Known::Yes(list) => list
.members
.iter()
.map(|member| member.fact.name.to_string())
.collect::<Vec<_>>(),
other => panic!("`bits` has a member list: {other:?}"),
};
assert!(
members.iter().any(|name| name == "three"),
"and its members are filed under that name: {members:?}"
);
}
#[test]
fn gnu_auto_type_is_deduced_from_its_initializer() {
let source = "int f(void) { __auto_type value = 41; return value; }\n";
assert_eq!(
type_of_use(source, "value").as_deref(),
Some("int"),
"the placeholder's type is the initialiser's"
);
}
#[test]
fn a_function_pointer_typedef_names_the_variable_it_types() {
let source = "\
typedef int (*binary_op)(int left, int right);
static int add(int left, int right) { return left + right; }
int f(void) { binary_op operation = add; return operation(1, 2); }
";
assert_eq!(
type_of_use(source, "operation").as_deref(),
Some("binary_op"),
"the alias's name is the type the file wrote"
);
}
#[test]
fn a_function_pointer_typedef_from_a_header_types_its_variable() {
let header = "\
typedef int (*binary_op)(int left, int right);
typedef int comparer(const void *left, const void *right);
";
let source = "\
#include \"corpus.h\"
#include <stddef.h>
#include <stdio.h>
static int add(int left, int right) { return left + right; }
int f(void) { binary_op operation = add; comparer *compare = 0; return operation(1, 2) + (compare != 0); }
";
let session = session_with(&[("/p/corpus.h", header), ("/p/a.c", source)]);
let view = session.view("/p/a.c").expect("the file is held");
let type_at = |needle: &str| {
let offset = source.find(needle).expect("the needle is written") + 1;
let reading = view
.reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(
offset,
))
.expect("the cursor is in the rendering");
match session.type_at(&view, reading) {
cpp_code_analysis::Known::Yes(found) => Some(found.type_of),
_ => None,
}
};
let operation = type_at("binary_op operation").expect("the variable has a type");
assert!(
operation.contains("int") && operation.contains("(int, int)"),
"a function-pointer typedef expands to the type it names: {operation}"
);
let compare = type_at("comparer *compare").expect("the pointer has a type");
assert!(
compare.contains("int") && compare.contains("void"),
"and so does the other typedef: {compare}"
);
}
#[test]
fn both_bitfields_of_a_bitint_struct_are_recorded() {
let source = "\
struct bits {
unsigned _BitInt(3) three : 3;
_BitInt(13) signed_wide : 13;
_BitInt(5) plain;
unsigned _BitInt(4) other : 2;
};
";
let session = session_with(&[("/p/a.c", source)]);
let summary = session
.parsed_summary(std::path::Path::new("/p/a.c"))
.expect("the file has a summary");
let names: Vec<&str> = summary
.declarations
.iter()
.map(|fact| fact.name.as_str())
.collect();
eprintln!("facts: {names:?}");
assert!(
names.contains(&"three") && names.contains(&"signed_wide") && names.contains(&"plain"),
"both bit-fields and the plain member are members: {names:?}"
);
}
#[test]
fn the_standards_own_macros_answer_from_the_language() {
let session = session_with(&[("/p/a.c", "int f(void) { return 0; }\n")]);
assert_eq!(
session.predefined_macro("__STDC_VERSION__", std::path::Path::new("/p/a.c")),
Some("202311L".to_string()),
"a permissive C reading takes the latest standard"
);
assert_eq!(
session.predefined_macro("__STDC__", std::path::Path::new("/p/a.c")),
Some("1".to_string()),
);
assert_eq!(
session.predefined_macro("__GNUC__", std::path::Path::new("/p/a.c")),
None,
"a compiler's own macro is not the standard's, and no compiler was asked here"
);
}
#[test]
fn a_class_templates_members_answer_through_its_instantiation() {
let source = "\
template <typename T>
class Box {
public:
explicit Box(T value) : value_(value) {}
T get() const { return value_; }
void set(T value) { value_ = value; }
private:
T value_;
};
int f() {
Box<int> box(7);
return box.get();
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let names = |class: &str| match session.members_of(&view, class) {
cpp_code_analysis::Known::Yes(list) => list
.members
.iter()
.map(|member| member.fact.name.to_string())
.collect::<Vec<_>>(),
other => panic!("`{class}` has a member list: {other:?}"),
};
assert!(
names("Box<int>").contains(&"get".to_string()),
"the instantiation has the template's members: {:?}",
names("Box<int>")
);
assert!(
names("Box").contains(&"get".to_string()),
"and so does the template's own name: {:?}",
names("Box")
);
}
#[test]
fn a_class_template_argument_is_deduced_from_the_initializer() {
let source = "\
template <typename T>
class Box {
public:
explicit Box(T value) : value_(value) {}
T get() const { return value_; }
private:
T value_;
};
int f() {
Box box(7);
return box.get();
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let offset = last_word(source, "box") + 2;
let found = match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(found) => found.type_of,
other => panic!("`box` has a type: {other:?}"),
};
assert!(
found.contains("Box<int>"),
"the argument is deduced from the initializer: {found}"
);
let names = match session.members_of(&view, "Box<int>") {
cpp_code_analysis::Known::Yes(list) => list
.members
.iter()
.map(|member| member.fact.name.to_string())
.collect::<Vec<_>>(),
other => panic!("`Box<int>` has a member list: {other:?}"),
};
assert!(
names.contains(&"get".to_string()),
"the deduced instantiation has the template's members: {names:?}"
);
}
#[test]
fn a_class_template_argument_is_deduced_through_a_namespace() {
let source = "\
namespace techniques {
template <typename T>
class Box {
public:
explicit Box(T value) : value_(value) {}
T get() const { return value_; }
private:
T value_;
};
} // namespace techniques
int f() {
techniques::Box box(7);
return box.get();
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let offset = last_word(source, "box") + 2;
let found = match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(found) => found.type_of,
other => panic!("`box` has a type: {other:?}"),
};
assert!(
found.contains("Box<int>"),
"the argument is deduced: {found}"
);
}
#[test]
fn a_class_template_argument_is_deduced_across_a_header() {
let header = "\
#pragma once
namespace techniques {
template <typename T>
class Box {
public:
explicit Box(T value) : value_(value) {}
T get() const { return value_; }
private:
T value_;
};
} // namespace techniques
";
let source = "\
#include \"techniques.h\"
int f() {
techniques::Box box(7);
return box.get();
}
";
let session = session_with(&[("/p/techniques.h", header), ("/p/a.cpp", source)]);
if let Some(summary) = session.parsed_summary(std::path::Path::new("/p/techniques.h")) {
for fact in &summary.declarations {
eprintln!(
"[fact] name={:?} scope={:?} kind={:?} params={:?}",
fact.name,
fact.scope,
fact.kind,
fact.parameter_list()
);
}
}
let view = session.view("/p/a.cpp").expect("the file is held");
let offset = last_word(source, "box") + 2;
let found = match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(found) => found.type_of,
other => panic!("`box` has a type: {other:?}"),
};
assert!(
found.contains("Box<int>"),
"the argument is deduced: {found}"
);
}
#[test]
fn a_hand_written_deduction_guide_is_read() {
let source = "\
#include <string>
template <typename T>
struct Wrap {
Wrap(std::string);
T get() const;
};
template <typename T>
Wrap(T) -> Wrap<T>;
int f() {
Wrap wrapped(7);
return wrapped.get();
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let offset = last_word(source, "wrapped") + 2;
let found = match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(found) => found.type_of,
other => panic!("`w` has a type: {other:?}"),
};
assert!(found.contains("Wrap<int>"), "the guide deduces it: {found}");
}
#[test]
fn an_enable_if_overload_is_chosen_by_its_condition() {
let source = "\
#include <type_traits>
#include <string>
template <typename T>
typename std::enable_if<std::is_integral<T>::value, std::string>::type describe(T value) {
return \"integral\";
}
template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, std::string>::type describe(T value) {
return \"floating\";
}
std::string f() {
describe(41);
return describe(1.5);
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let rendering = view.root.text().to_string();
let declaration_at = |which: usize| -> usize {
rendering
.match_indices("describe(T value)")
.nth(which)
.map(|(at, _)| at)
.expect("both declarations are in the rendering")
};
let floating_call = rendering
.find("describe(1.5)")
.expect("the call is written");
let one = match session.definition(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(floating_call + 3),
) {
cpp_code_analysis::Known::Yes(found) => found,
other => panic!("`describe(1.5)` resolves: {other:?}"),
};
assert_eq!(
one.fact.name_range.start_offset,
declaration_at(1),
"the condition picks the floating-point overload"
);
let integral_call = rendering.find("describe(41)").expect("the call is written");
let integral = match session.definition(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(integral_call + 3),
) {
cpp_code_analysis::Known::Yes(found) => found,
other => panic!("`describe(41)` resolves: {other:?}"),
};
assert_eq!(
integral.fact.name_range.start_offset,
declaration_at(0),
"the condition picks the integral overload"
);
}
#[test]
fn the_constraint_evaluator_decides_the_fundamental_traits() {
use cpp_code_analysis::sema::constraint::{satisfies, the_condition_of};
let bind = |spelling: &str| vec![("T".to_string(), spelling.to_string())];
let integral = the_condition_of(
"typename std::enable_if<std::is_integral<T>::value, std::string>::type describe(T value)",
)
.expect("the declaration carries a condition");
assert_eq!(integral, "std::is_integral<T>::value");
assert_eq!(satisfies(integral, &bind("int")), Some(true));
assert_eq!(satisfies(integral, &bind("double")), Some(false));
assert_eq!(
satisfies(integral, &bind("std::string")),
Some(false),
"a class is not integral"
);
let floating = the_condition_of(
"typename std::enable_if<std::is_floating_point<T>::value, int>::type describe(T value)",
)
.expect("the declaration carries a condition");
assert_eq!(satisfies(floating, &bind("double")), Some(true));
assert_eq!(satisfies(floating, &bind("int")), Some(false));
for spelling in [
"std::is_integral<T>::value",
"std::is_integral<T>{}",
"std::is_integral_v<T>",
"std::is_integral<T>()",
] {
assert_eq!(
satisfies(spelling, &bind("long")),
Some(true),
"{spelling} says a `long` is integral"
);
}
assert_eq!(
satisfies("!std::is_integral<T>::value", &bind("double")),
Some(true)
);
assert_eq!(
satisfies(
"std::is_integral<T>::value && !std::is_same<T, char>::value",
&bind("int")
),
Some(true)
);
assert_eq!(
satisfies(
"std::is_integral<T>::value || std::is_floating_point<T>::value",
&bind("float")
),
Some(true)
);
assert_eq!(
satisfies("std::is_user_defined<T>::value", &bind("int")),
None,
"a trait this layer does not know is *cannot tell*, never `false`"
);
assert_eq!(
satisfies("std::is_integral<U>::value", &bind("int")),
None,
"an unbound parameter is cannot-tell as well"
);
for (condition, spelling, expected) in [
("std::is_reference_v<T>", "int&", true),
("std::is_reference_v<T>", "int&&", true),
("std::is_reference_v<T>", "int", false),
("std::is_reference_v<T>", "std::string&", true),
("std::is_const_v<T>", "const int", true),
("std::is_const_v<T>", "int", false),
("std::is_const_v<T>", "const int*", false),
("std::is_volatile_v<T>", "volatile int", true),
("std::is_volatile_v<T>", "int", false),
("std::is_array_v<T>", "int[4]", true),
("std::is_array_v<T>", "int[]", true),
("std::is_array_v<T>", "int", false),
("std::is_function_v<T>", "int(int)", true),
("std::is_function_v<T>", "int", false),
("std::is_pointer_v<T>", "int*", true),
("std::is_pointer_v<T>", "int", false),
] {
assert_eq!(
satisfies(condition, &bind(spelling)),
Some(expected),
"{condition} of {spelling}"
);
}
assert_eq!(
satisfies("std::is_integral_v<T>", &bind("std::string")),
Some(false)
);
assert_eq!(satisfies("std::is_const_v<T>", &bind("U")), None);
assert_eq!(satisfies("std::is_class_v<T>", &bind("std::string")), None);
assert_eq!(
the_condition_of("void plain(int value)"),
None,
"an ordinary function carries no condition"
);
}
#[test]
fn dump_the_overload_bindings() {
let source = "\
#include <type_traits>
template <typename T>
typename std::enable_if<std::is_integral<T>::value, int>::type describe(T value) { return 1; }
template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, int>::type describe(T value) { return 2; }
int f() { return describe(1.5); }
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let inside = source.find("return describe").expect("the call");
let reading = as_reading(&view, inside);
let scope = view.scopes.scope_at(reading.get()).expect("a scope");
let mut at = Some(scope);
while let Some(current) = at {
let data = view.scopes.scope(current).expect("the scope");
let named: Vec<_> = data
.bindings
.iter()
.filter(|binding| binding.name.identifier_text() == Some("describe"))
.map(|binding| (binding.kind, binding.name_range.start_offset))
.collect();
eprintln!(
"[bindings] scope {:?} kind {:?}: {} describe {named:?}",
current,
data.kind,
named.len()
);
at = data.parent;
}
let all: Vec<_> = view
.scopes
.scope(scope)
.expect("the scope")
.bindings
.iter()
.map(|binding| (binding.kind, binding.name.identifier_text()))
.collect();
eprintln!("[all] {all:?}");
}
#[test]
fn dump_the_call_shape() {
let source = "int describe(double v) { return 1; }\nint f() { return describe(1.5); }\n";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let at = source.find("describe(1.5)").expect("the call") + 3;
let reading = as_reading(&view, at);
let node = cpp_code_analysis::sema::resolve::expression_at(&view.root, reading.get());
eprintln!("[call] expression={:?}", node.as_ref().map(|n| n.kind()));
let mut chain = Vec::new();
if let Some(node) = node {
for ancestor in node.ancestors() {
chain.push(format!("{:?}", ancestor.kind()));
}
}
eprintln!("[call] ancestors={chain:?}");
let call = cpp_code_analysis::sema::resolve::expression_at(&view.root, reading.get()).and_then(
|node| {
node.ancestors()
.find(|n| format!("{:?}", n.kind()).contains("Call"))
},
);
if let Some(call) = call {
eprintln!(
"[call] children={:?}",
call.children()
.map(|c| format!("{:?}", c.kind()))
.collect::<Vec<_>>()
);
}
}
#[test]
fn an_enable_if_in_a_template_parameter_is_read() {
let source = "\
#include <type_traits>
#include <string>
template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>>
std::string describe(T value) {
return \"integral\";
}
template <typename T, typename = std::enable_if_t<std::is_floating_point<T>::value>>
std::string describe(T value) {
return \"floating\";
}
std::string f() {
describe(41);
return describe(1.5);
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let rendering = view.root.text().to_string();
let declaration_at = |which: usize| -> usize {
rendering
.match_indices("describe(T value)")
.nth(which)
.map(|(at, _)| at)
.expect("both declarations are in the rendering")
};
let floating_call = rendering
.find("describe(1.5)")
.expect("the call is written");
let one = match session.definition(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(floating_call + 3),
) {
cpp_code_analysis::Known::Yes(found) => found,
other => panic!("`describe(1.5)` resolves: {other:?}"),
};
assert_eq!(
one.fact.name_range.start_offset,
declaration_at(1),
"the template parameter's condition picks the floating-point overload"
);
}
#[test]
fn a_requires_clause_is_read() {
let source = "\
#include <type_traits>
#include <string>
template <typename T> requires std::is_integral_v<T>
std::string describe(T value) {
return \"integral\";
}
template <typename T> requires std::is_floating_point_v<T>
std::string describe(T value) {
return \"floating\";
}
std::string f() {
describe(41);
return describe(1.5);
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let rendering = view.root.text().to_string();
let declaration_at = |which: usize| -> usize {
rendering
.match_indices("describe(T value)")
.nth(which)
.map(|(at, _)| at)
.expect("both declarations are in the rendering")
};
let floating_call = rendering
.find("describe(1.5)")
.expect("the call is written");
let one = match session.definition(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(floating_call + 3),
) {
cpp_code_analysis::Known::Yes(found) => found,
other => panic!("`describe(1.5)` resolves: {other:?}"),
};
assert_eq!(
one.fact.name_range.start_offset,
declaration_at(1),
"the `requires` clause picks the floating-point overload"
);
let integral_call = rendering.find("describe(41)").expect("the call is written");
let integral = match session.definition(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(integral_call + 3),
) {
cpp_code_analysis::Known::Yes(found) => found,
other => panic!("`describe(41)` resolves: {other:?}"),
};
assert_eq!(
integral.fact.name_range.start_offset,
declaration_at(0),
"and the integral overload for an int"
);
}
#[test]
fn a_named_concept_decides_the_overload() {
let source = "\
#include <type_traits>
#include <string>
template <typename T>
concept integral = std::is_integral_v<T>;
template <typename T>
concept floating = std::is_floating_point_v<T>;
template <integral T>
std::string describe(T value) {
return \"integral\";
}
template <floating T>
std::string describe(T value) {
return \"floating\";
}
std::string f() {
describe(41);
return describe(1.5);
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let rendering = view.root.text().to_string();
let declaration_at = |which: usize| -> usize {
rendering
.match_indices("describe(T value)")
.nth(which)
.map(|(at, _)| at)
.expect("both declarations are in the rendering")
};
let floating_call = rendering
.find("describe(1.5)")
.expect("the call is written");
let one = match session.definition(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(floating_call + 3),
) {
cpp_code_analysis::Known::Yes(found) => found,
other => panic!("`describe(1.5)` resolves: {other:?}"),
};
assert_eq!(
one.fact.name_range.start_offset,
declaration_at(1),
"the concept picks the floating-point overload"
);
}
#[test]
fn a_composed_concept_decides_the_overload() {
let source = "\
#include <type_traits>
#include <string>
template <typename T>
concept integral = std::is_integral_v<T>;
template <typename T>
concept signed_integral = integral<T> && std::is_signed_v<T>;
template <signed_integral T>
std::string describe(T value) {
return \"signed\";
}
template <typename T> requires std::is_floating_point_v<T>
std::string describe(T value) {
return \"floating\";
}
std::string f() {
describe(-3);
return describe(1.5);
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let rendering = view.root.text().to_string();
let declaration_at = |which: usize| -> usize {
rendering
.match_indices("describe(T value)")
.nth(which)
.map(|(at, _)| at)
.expect("both declarations are in the rendering")
};
let floating_call = rendering
.find("describe(1.5)")
.expect("the call is written");
let floating = match session.definition(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(floating_call + 3),
) {
cpp_code_analysis::Known::Yes(found) => found,
other => panic!("`describe(1.5)` resolves: {other:?}"),
};
assert_eq!(
floating.fact.name_range.start_offset,
declaration_at(1),
"the composed concept is false for a double"
);
let signed_call = rendering.find("describe(-3)").expect("the call is written");
let signed = match session.definition(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(signed_call + 3),
) {
cpp_code_analysis::Known::Yes(found) => found,
other => panic!("`describe(-3)` resolves: {other:?}"),
};
assert_eq!(
signed.fact.name_range.start_offset,
declaration_at(0),
"and true for a signed int"
);
}
#[test]
fn a_template_parameter_target_is_not_a_refusal() {
use cpp_code_analysis::sema::convert::{Conversion, conversion};
use cpp_code_analysis::sema::types::{Type, parse_type_spelling};
let an_int = Type::builtin("int");
assert_eq!(
conversion(&an_int, "_Ty2&&", |_| None),
Conversion::Unknown,
"an unread template parameter is cannot-tell, not a refusal"
);
assert_eq!(
conversion(&an_int, "T", |_| None),
Conversion::Unknown,
"and so is a bare `T`"
);
assert_eq!(
conversion(&an_int, "const Widget&", |_| Some(false)),
Conversion::Refused,
);
let a_string = parse_type_spelling("std::string");
assert_eq!(conversion(&a_string, "int", |_| None), Conversion::Unknown);
}
#[test]
fn a_members_deduced_return_type_is_read_through_a_header() {
let header = "\
template <typename T>
class Box {
public:
explicit Box(T value) : value_(value) {}
auto copy_of() const { return value_; }
auto doubled() const { return value_ + value_; }
private:
T value_;
};
";
let source = "\
#include \"a.h\"
int f() {
Box<int> box(7);
auto copied = box.copy_of();
auto doubled = box.doubled();
return copied + doubled;
}
";
let session = session_with(&[("/p/a.cpp", source), ("/p/a.h", header)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let offset = last_word(source, "copied");
match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(found) => {
assert_eq!(found.type_of, "int", "`copy_of` returns the field's type");
}
other => panic!("`copied` is typed: {other:?}"),
}
let offset = last_word(source, "doubled");
match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(found) => {
assert_eq!(found.type_of, "int", "`value_ + value_` is an `int`");
}
other => panic!("`doubled` is typed: {other:?}"),
}
}
#[test]
fn a_fold_expressions_type_is_the_widest_argument() {
let source = "\
namespace t {
template <typename... Values>
auto sum_of(Values... values) {
return (values + ...);
}
}
int f() {
auto total = t::sum_of(1, 2, 3, 4);
auto mixed = t::sum_of(1, 2.5);
return total + static_cast<int>(mixed);
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
for (name, expected) in [("total", "int"), ("mixed", "double")] {
let offset = last_word(source, name);
match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(found) => {
assert_eq!(found.type_of, expected, "{name}");
}
other => panic!("`{name}` is typed: {other:?}"),
}
}
}
#[test]
fn a_lambda_call_has_the_type_its_body_returns() {
let source = "\
int f() {
auto doubler = [](int value) { return value * 2; };
auto result = doubler(3);
return result;
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
for (name, _) in [("doubler", "closure"), ("result", "int")] {
let offset = last_word(source, name);
match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(found) => println!("{name} → {}", found.type_of),
other => println!("{name} → {other:?}"),
}
}
let offset = last_word(source, "result");
match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(found) => assert_eq!(found.type_of, "int"),
other => panic!("`result` is typed: {other:?}"),
}
}
#[test]
fn a_structured_binding_over_a_pair_has_the_components_types() {
let source = "\
#include <utility>
int f() {
std::pair<int, double> pair{1, 2.5};
auto [number, fraction] = pair;
return number + static_cast<int>(fraction);
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
for (name, expected) in [("number", "int"), ("fraction", "double")] {
let offset = last_word(source, name);
match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(found) => {
assert_eq!(found.type_of, expected, "{name}");
}
other => panic!("`{name}` is typed: {other:?}"),
}
}
}
#[test]
fn a_value_auto_drops_the_reference_its_initializer_had() {
let source = "\
namespace std {
template <class T> T&& move(T& value) noexcept;
}
struct Item { int size; };
int f() {
Item item;
auto moved = std::move(item);
return moved.size;
}
";
assert_eq!(
type_of_use(source, "moved").as_deref(),
Some("Item"),
"`auto` alone is a new object, so the reference is not part of its type"
);
}
#[test]
fn a_container_members_alias_is_substituted_with_its_element_type() {
let source = "\
namespace std {
template <class T> class vector {
public:
using value_type = T;
using reference = value_type&;
reference emplace_back();
};
}
int f() {
std::vector<int> values;
auto &result = values.emplace_back();
result = 3;
return result;
}
";
assert_eq!(
type_of_use(source, "result").as_deref(),
Some("int&"),
"`reference` is `value_type&`, and `value_type` is the argument the declaration wrote"
);
}
#[test]
fn a_dependent_alias_of_a_class_template_is_substituted() {
let source = "\
namespace std {
template <class T> struct allocator_traits { using value_type = T; };
template <class T> class vector {
public:
using value_type = T;
using reference = allocator_traits<value_type>::value_type&;
reference emplace_back();
};
}
int f() {
std::vector<int> values;
auto &result = values.emplace_back();
result = 3;
return result;
}
";
assert_eq!(
type_of_use(source, "result").as_deref(),
Some("int&"),
"`allocator_traits<value_type>::value_type` is `int` for `vector<int>`"
);
}
#[test]
fn a_class_the_index_does_not_hold_is_answered_from_the_rendering() {
const LIB_H: &str = "\
namespace std {
template <class T> struct allocator_traits { using value_type = T; };
template <class T> class vector {
public:
using value_type = T;
using reference = allocator_traits<value_type>::value_type&;
reference emplace_back();
};
}
";
let source = "\
#include \"lib.h\"
int f() {
std::vector<int> values;
auto &result = values.emplace_back();
return result;
}
";
let memory = MemoryFiles::new()
.with_file("/p/lib.h", LIB_H)
.with_file("/p/a.cpp", 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([std::path::PathBuf::from("/p/a.cpp")]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
let view = session.view("/p/a.cpp").expect("the file is held");
let offset = last_word(source, "result");
match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(found) => assert_eq!(
found.type_of, "int&",
"the class's member alias is in the rendering, even though the index has no `vector`"
),
_ => panic!("the rendering holds `std::vector`, so `result` has a type"),
}
}
#[test]
fn a_member_is_found_through_a_plain_class_and_through_a_template() {
const LIB_H: &str = "\
struct Plain { int emplace_back(); };
template <class T> class Temp { public: int emplace_back(); };
";
let source = "\
#include \"lib.h\"
int f() {
Plain plain;
auto a = plain.emplace_back();
Temp<int> temp;
auto b = temp.emplace_back();
return a + b;
}
";
let memory = MemoryFiles::new()
.with_file("/p/lib.h", LIB_H)
.with_file("/p/a.cpp", 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([
std::path::PathBuf::from("/p/lib.h"),
std::path::PathBuf::from("/p/a.cpp"),
]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
let view = session.view("/p/a.cpp").expect("the file is held");
for (spelling, expected) in [("a", "int"), ("b", "int")] {
let offset = last_word(source, spelling);
let found = session.type_at(&view, as_reading(&view, offset));
assert!(
matches!(&found, cpp_code_analysis::Known::Yes(known) if known.type_of == expected),
"`{spelling}` should be `{expected}`, got {found:?}"
);
}
}
#[test]
fn a_class_template_in_macro_opened_namespaces_is_the_standard_library_idiom() {
const LIB_H: &str = "\
#define _STD_BEGIN namespace std {
#define _STD_END }
#define _CONSTEXPR20
#define _NODISCARD [[nodiscard]]
_STD_BEGIN
template <class _Ty> class vector {
public:
using value_type = _Ty;
using reference = value_type&;
_NODISCARD _CONSTEXPR20 reference emplace_back();
};
_STD_END
";
let source = "\
#include \"lib.h\"
int f() {
std::vector<int> values;
auto &result = values.emplace_back();
result = 3;
return result;
}
";
let memory = MemoryFiles::new()
.with_file("/p/lib.h", LIB_H)
.with_file("/p/a.cpp", 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([
std::path::PathBuf::from("/p/lib.h"),
std::path::PathBuf::from("/p/a.cpp"),
]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
let view = session.view("/p/a.cpp").expect("the file is held");
let offset = last_word(source, "result");
let found = session.type_at(&view, as_reading(&view, offset));
assert!(
matches!(&found, cpp_code_analysis::Known::Yes(known) if known.type_of == "int&"),
"the standard library's idiom should answer `int&`, got {found:?}"
);
}
#[test]
fn a_member_is_found_two_includes_away_through_guards() {
const BASE_H: &str = "\
#ifndef BASE_H
#define BASE_H
namespace std {
template <class T> class vector {
public:
using value_type = T;
using reference = value_type&;
reference emplace_back();
};
}
#endif
";
const MID_H: &str = "\
#pragma once
#include \"base.h\"
";
let source = "\
#include \"mid.h\"
int f() {
std::vector<int> values;
auto &result = values.emplace_back();
result = 3;
return result;
}
";
let memory = MemoryFiles::new()
.with_file("/p/base.h", BASE_H)
.with_file("/p/mid.h", MID_H)
.with_file("/p/a.cpp", 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([
std::path::PathBuf::from("/p/base.h"),
std::path::PathBuf::from("/p/mid.h"),
std::path::PathBuf::from("/p/a.cpp"),
]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
let view = session.view("/p/a.cpp").expect("the file is held");
let offset = last_word(source, "result");
let found = session.type_at(&view, as_reading(&view, offset));
assert!(
matches!(&found, cpp_code_analysis::Known::Yes(known) if known.type_of == "int&"),
"two includes away, through a guard, is still `int&`, got {found:?}"
);
}
#[test]
fn a_partial_specialization_is_a_declaration_with_a_pattern() {
let source = "\
template <class T> struct A { };
template <class V> struct void_t { };
template <class T, class = void> struct B : A<T> { };
template <class T> struct B<A<T>, void_t<typename A<T>::From>> : A<T> {
using inner = int;
};
";
let session = session_with(&[("/p/a.cpp", source)]);
let facts: Vec<_> = session
.index()
.every_fact_named("B")
.into_iter()
.map(|(_, fact)| fact.clone())
.collect();
let patterns: Vec<Option<&str>> = facts.iter().map(|fact| fact.pattern()).collect();
assert!(
facts.len() >= 2,
"the principal and its specialization are two declarations: {patterns:?}"
);
assert!(
patterns.iter().any(Option::is_some),
"and the specialization records the pattern it matches: {patterns:?}"
);
let inner = session.index().every_fact_named("inner");
assert!(
!inner.is_empty(),
"the specialization's member is declared too"
);
}
#[test]
fn a_conditional_base_picks_the_branch_its_trait_selects() {
let source = "\
namespace std {
template <class T> struct false_type { static constexpr bool value = false; };
template <class T> struct true_type { static constexpr bool value = true; };
template <class T> struct allocator { using value_type = T; };
template <class T> struct _Is_default_allocator : false_type { };
template <class T> struct _Is_default_allocator<allocator<T>> : true_type { };
template <bool C, class A, class B> struct conditional;
template <class A, class B> struct conditional<true, A, B> { using type = A; };
template <class A, class B> struct conditional<false, A, B> { using type = B; };
template <bool C, class A, class B> using conditional_t = typename conditional<C, A, B>::type;
template <class T> struct _Default_allocator_traits { using size_type = unsigned long long; };
template <class T> struct _Normal_allocator_traits { using size_type = typename T::size_type; };
template <class A>
struct allocator_traits
: conditional_t<_Is_default_allocator<A>::value, _Default_allocator_traits<A>, _Normal_allocator_traits<A>> { };
template <class T, class A = allocator<T>> struct vector {
using size_type = typename allocator_traits<A>::size_type;
size_type size() const;
};
}
std::vector<int> events;
void f() {
auto pos = events.size();
(void)pos;
}
";
assert_eq!(
type_of_use(source, "pos").as_deref(),
Some("unsigned long long"),
"`_Is_default_allocator<allocator<int>>` is true, so the base is `_Default_allocator_traits`"
);
}
#[test]
fn an_alias_template_used_as_a_base_substitutes_its_arguments() {
let source = "\
template <class T> struct chosen { using size_type = unsigned long long; };
template <class T> struct other { using size_type = unsigned long long; };
template <class X, class Y> struct pick { using type = X; };
template <class X, class Y> using pick_t = typename pick<X, Y>::type;
template <class T> struct traits : pick_t<chosen<T>, other<T>> { };
struct User : traits<int> { };
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let list = cpp_code_analysis::index::project::members_of(
session.index(),
&view.scopes,
&view.root,
std::path::Path::new("/p/a.cpp"),
"User",
);
let cpp_code_analysis::Known::Yes(list) = list else {
panic!("`User` is a class: {list:?}");
};
let names: Vec<&str> = list
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect();
assert!(
names.contains(&"size_type"),
"the alias's target names `chosen<T>`, whose members are the base's: {names:?} (unlisted: {:?})",
list.unlisted
.iter()
.map(|one| one.spelling.as_str())
.collect::<Vec<_>>()
);
}
#[test]
fn a_class_template_forward_declared_then_defined_uses_the_definitions_bases() {
let source = "\
template <class T> struct traits;
template <class T> struct base {
using size_type = unsigned long long;
};
template <class T> struct traits : base<T> { };
struct User : traits<int> { };
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let list = cpp_code_analysis::index::project::members_of(
session.index(),
&view.scopes,
&view.root,
std::path::Path::new("/p/a.cpp"),
"User",
);
let cpp_code_analysis::Known::Yes(list) = list else {
panic!("`User` is a class: {list:?}");
};
let names: Vec<&str> = list
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect();
assert!(
names.contains(&"size_type"),
"the inherited member comes through the definition's base: {names:?} (unlisted: {:?})",
list.unlisted
.iter()
.map(|one| one.spelling.as_str())
.collect::<Vec<_>>()
);
}
#[test]
fn a_containers_size_called_on_an_object_is_its_size_type() {
const XMEMORY: &str = "\
namespace std {
template <class T> struct allocator { using value_type = T; using size_type = unsigned long long; };
template <class A> struct allocator_traits { using size_type = typename A::size_type; };
template <class A, class T> struct _Rebind_alloc { using type = A; };
template <class A, class T> using _Rebind_alloc_t = typename _Rebind_alloc<A, T>::type;
}
";
let source = "\
#include \"xmemory\"
namespace std {
template <class _Ty, class _Alloc = allocator<_Ty>> class vector {
using _Alty = _Rebind_alloc_t<_Alloc, _Ty>;
using _Alty_traits = allocator_traits<_Alty>;
public:
using size_type = typename _Alty_traits::size_type;
size_type size() const;
};
}
std::vector<int> events;
void f() {
auto pos = events.size();
(void)pos;
}
";
let session = session_with(&[("/p/xmemory", XMEMORY), ("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let offset = last_word(source, "pos");
let found = session.type_at(&view, as_reading(&view, offset));
assert!(
matches!(&found, cpp_code_analysis::Known::Yes(known) if known.type_of == "unsigned long long"),
"the chain ends at the size type, not at an alias of the allocator's: {found:?}"
);
}
#[test]
fn a_deduced_type_keeps_the_alias_the_source_wrote() {
let source = "\
namespace std {
template <class T> struct allocator { };
template <class C> struct char_traits { };
template <class C, class T, class A> struct basic_string { };
using string = basic_string<char, char_traits<char>, allocator<char>>;
}
struct Builder { std::string get(); };
void f(Builder b) {
auto text = b.get();
(void)text;
}
";
assert_eq!(
type_of_use(source, "text").as_deref(),
Some("std::string"),
"the spelling the header wrote, not what the alias stands for"
);
}
#[test]
fn a_range_written_as_a_reference_still_binds_its_element() {
let source = "\
#include <vector>
int f(const std::vector<int> &values) {
for (auto x : values) {
int k = x;
(void)k;
}
return 0;
}
";
let session = session_with(&[
(
"/p/vector",
"namespace std { template <class T> struct vector { }; }\n",
),
("/p/a.cpp", source),
]);
let view = session.view("/p/a.cpp").expect("the file is held");
let offset = last_word(source, "k");
let found = session.type_at(&view, as_reading(&view, offset));
assert!(
matches!(&found, cpp_code_analysis::Known::Yes(known) if known.type_of == "int"),
"the element of a `const std::vector<int>&` is `int`, got {found:?}"
);
}
#[test]
fn an_auto_declaration_in_a_range_for_body_is_deduced_from_its_own_initializer() {
let source = "\
namespace std { template <class T> struct vector { T &emplace_back(); }; }
struct Item { int size; };
struct Other { int size; };
void f(const std::vector<Other> &diagnostics) {
std::vector<Item> results;
for (auto &diagnostic : diagnostics) {
auto &result = results.emplace_back();
int k = result.size;
(void)k;
}
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let type_of = |offset: usize| match session.type_at(&view, as_reading(&view, offset)) {
cpp_code_analysis::Known::Yes(known) => known.type_of,
other => panic!("a type is expected at {offset}: {other:?}"),
};
let loop_variable = last_word(source, "diagnostic ");
assert_eq!(
type_of(loop_variable),
"Other",
"the loop variable is the range's element"
);
assert_eq!(
type_of(last_word(source, "result")),
"Item&",
"the declaration inside the body is not the loop variable"
);
}
#[test]
fn a_define_static_array_call_is_the_static_array_of_its_range() {
let source = "\
namespace std {
namespace meta { struct info {}; }
template <class T> struct vector {};
std::vector<std::meta::info> nonstatic_data_members_of(int);
template <class R> consteval auto define_static_array(R&& r);
}
auto members = std::define_static_array(std::nonstatic_data_members_of(1));
";
assert_eq!(
type_of_use(source, "members").as_deref(),
Some("std::meta::info[]"),
"the range is a `vector<std::meta::info>`, so the array's element is `std::meta::info`"
);
}
#[test]
fn a_deduced_type_does_not_carry_the_storage_specifiers() {
assert_eq!(
type_of_use("static constexpr auto count = 1;\n", "count").as_deref(),
Some("int")
);
assert_eq!(
type_of_use("inline constexpr auto ratio = 0.5;\n", "ratio").as_deref(),
Some("double")
);
assert_eq!(
type_of_use("static const auto fixed = 2;\n", "fixed").as_deref(),
Some("const int")
);
}
#[test]
fn a_function_whose_body_returns_a_call_is_typed_from_that_call() {
let called = "\
int g(int);
auto via(int x) { return g(x); }
auto result = via(3);
";
assert_eq!(
type_of_use(called, "result").as_deref(),
Some("int"),
"`g(x)` is an `int`, so `via` returns one"
);
let member = "\
struct Widget { int count; };
auto count_of(Widget w) { return w.count; }
auto result = count_of(Widget{1});
";
assert_eq!(
type_of_use(member, "result").as_deref(),
Some("int"),
"`w.count` is an `int`, so `count_of` returns one"
);
let chained = "\
int g(int);
auto via(int x) { return g(x); }
auto twice(int x) { return via(x) + via(x); }
auto result = twice(4);
";
assert_eq!(
type_of_use(chained, "result").as_deref(),
Some("int"),
"`via` is an `int` function, so `twice` is too"
);
let bare = "\
void note() { }
auto nothing(bool b) { if (b) { return; } note(); }
auto result = nothing(true);
";
assert_eq!(
type_of_use(bare, "result").as_deref(),
Some("void"),
"a bare `return;` makes the deduced type `void`"
);
}
#[test]
fn a_body_whose_returns_disagree_is_not_typed() {
let disagreeing = "\
auto bad(bool b) { if (b) { return 1; } return 2.5; }
auto result = bad(true);
";
assert_eq!(
type_of_use(disagreeing, "result"),
None,
"`int` and `double` do not agree, so there is no deduced type to report"
);
let mutual = "\
auto f();
auto g() { return f(); }
auto f() { return g(); }
auto result = f();
";
assert_eq!(
type_of_use(mutual, "result"),
None,
"a cycle is refused at the recursion bound rather than walked forever"
);
}
#[test]
fn a_braced_initialisation_of_a_standard_class_template_is_answered_without_walking_its_members() {
let source = "\
namespace std {
template <int N, typename... Elements> struct impl;
template <int N, typename Head, typename... Tail>
struct impl<N, Head, Tail...> : impl<N + 1, Tail...> {
Head head;
};
template <int N> struct impl<N> {};
template <typename... Elements> struct tuple : impl<0, Elements...> {
int own;
};
} // namespace std
void f() {
auto made = std::tuple{1, 2.5};
}
";
assert_eq!(
type_of_use(source, "made").as_deref(),
Some("std::tuple<int, double>"),
"the standard's own guide answers the deduction, and it is consulted before any member list is built"
);
}
#[test]
fn a_member_list_of_a_class_template_whose_base_is_its_pack_stops_and_says_so() {
let source = "\
namespace lib {
template <int N, typename... Elements> struct impl;
template <int N, typename Head, typename... Tail>
struct impl<N, Head, Tail...> : impl<N + 1, Tail...> {
Head head;
};
template <int N> struct impl<N> {};
template <typename... Elements> struct tuple : impl<0, Elements...> {
int own;
};
} // namespace lib
void f() {
lib::tuple<int, double> value{};
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session
.view_of_the_file(std::path::Path::new("/p/a.cpp"))
.expect("the file is held");
let bare = session.members_of(&view, "lib::tuple");
let cpp_code_analysis::Known::Yes(bare) = bare else {
panic!("a class this file declares answers a member list: {bare:?}");
};
assert!(
bare.members.iter().any(|member| member.fact.name == "own"),
"the class's own members are listed: {:?}",
bare.members
.iter()
.map(|member| member.fact.name.to_string())
.collect::<Vec<_>>()
);
assert_eq!(
bare.unlisted.len(),
1,
"the base it could not spell is named rather than silently dropped: {:?}",
bare.unlisted
);
assert!(
bare.unlisted[0].spelling.contains("Elements..."),
"the gap names the clause, which is the only way a reader can tell what is missing: {:?}",
bare.unlisted[0]
);
let instantiated = session.members_of(&view, "lib::tuple<int, double>");
let cpp_code_analysis::Known::Yes(instantiated) = instantiated else {
panic!("an instantiated class this file declares answers a member list: {instantiated:?}");
};
assert!(
!instantiated.members.is_empty(),
"the members of the first base level that could be spelled are listed: {instantiated:?}"
);
}
#[test]
fn a_partial_specializations_members_are_not_the_primary_templates() {
let files = [
(
"/p/vector.h",
"template <typename T> struct vector {\n T* begin();\n const T* begin() const;\n};\n",
),
(
"/p/bvector.h",
"template <> struct vector<bool> {\n void begin();\n void begin() const;\n};\n",
),
(
"/p/a.cpp",
"#include \"vector.h\"\n#include \"bvector.h\"\nvoid f() { vector<int> v; v.begin(); }\n",
),
];
let session = session_with(&files);
let view = session
.view_of_the_file(std::path::Path::new("/p/a.cpp"))
.expect("the file is held");
let members = session.members_of(&view, "vector<int>");
let cpp_code_analysis::Known::Yes(members) = members else {
panic!("a class these headers declare answers a member list: {members:?}");
};
let begins: Vec<(String, usize)> = members
.members
.iter()
.filter(|member| member.fact.name == "begin")
.map(|member| {
(
member.file.display().to_string(),
member.fact.range.start_offset,
)
})
.collect();
assert_eq!(
begins.len(),
2,
"the primary template declares `begin` twice and the specialization's two are someone else's: {begins:?}"
);
assert!(
begins.iter().all(|(file, _)| file.ends_with("vector.h")),
"and both are the primary's own body: {begins:?}"
);
}
#[test]
fn an_operators_qualified_return_type_does_not_lose_the_member() {
let source = "\
struct Hashed {
std::size_t operator()(std::string const& value) const;
bool operator<(const Hashed& other) const;
};
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session
.view_of_the_file(std::path::Path::new("/p/a.cpp"))
.expect("the file is held");
let members = session.members_of(&view, "Hashed");
let cpp_code_analysis::Known::Yes(members) = members else {
panic!("a class this file declares answers a member list: {members:?}");
};
let names: Vec<String> = members
.members
.iter()
.map(|member| member.fact.name.to_string())
.collect();
assert!(
names.iter().any(|name| name == "operator()"),
"the operator with the qualified return type is a member: {names:?}"
);
assert!(
names.iter().any(|name| name == "operator<"),
"and so is the one with a plain return type: {names:?}"
);
}
#[test]
fn a_declarations_own_readings() {
let source = "\
struct Hashed {
std::size_t operator()(std::string const& value) const;
};
void f(std::string const& text, std::string& plain) {
text.size();
plain.size();
}
";
let session = session_with(&[("/p/a.cpp", source)]);
let view = session
.view_of_the_file(std::path::Path::new("/p/a.cpp"))
.expect("the file is held");
let operator = source.find("operator()").expect("the operator is written") + 2;
assert_eq!(
session.the_name_declared_at(&view, operator).as_deref(),
Some("operator()"),
"an operator's name is composed from the keyword, not read as an identifier"
);
let text = source.find("text.size").expect("the const one is used");
assert_eq!(
session.the_object_is_const(&view, text),
Some(true),
"`text` is declared `std::string const&`"
);
let plain = source.find("plain.size").expect("the other one is used");
assert_eq!(
session.the_object_is_const(&view, plain),
Some(false),
"`plain` is declared `std::string&`, so every overload is callable"
);
assert_eq!(
session.the_object_is_const(&view, source.find("nothing").unwrap_or(0)),
None,
"an offset that is not a name answers nothing rather than `false`"
);
}