#[allow(dead_code)]
pub mod walk_cache;
pub mod walk_cache_codec;
use std::path::{Path, PathBuf};
use cpp_parser::{CppParser, CppSyntaxTree, ParserConfig};
pub mod environment;
mod names;
pub mod project;
pub mod references;
pub mod store;
pub mod walk_census;
pub mod watch;
pub mod worklist;
pub use environment::{MacrosHere, visibility_at};
pub use project::{
CookedFile, HeaderTarget, IncludeVisibility, MemberCompletions, MemberList, NameCompletions,
NameProvenance, OfferedName, ProjectDefinition, ProjectDefinitions, ProjectIndex, ProjectMacro,
ProjectMember, ProjectSymbol, UnlistedBase, VisibleDeclaration, definition_across_files,
definitions_across_files, header_at, macro_across_files, member_across_files,
member_completions_at, member_definitions_across_files, members_of, name_completions_at,
};
pub use references::{
FileReferences, MacroReferences, Reference, ReferenceBudget, ReferenceKind, Rename,
SymbolReferences, SymbolToFind, macro_references, symbol_references,
};
pub use store::{
IncludeBudget, IncludeIndex, NotIndexed, NotIndexedReason, StoreStats, SummaryStore,
UnresolvedEdge,
};
pub use watch::{ChangeBatch, EventKind, FileEvent, PathPattern, Response, WatchFilter};
pub use worklist::{Priority, Step, StepOutcome, Worklist, outcome_of};
use crate::cache::{SummaryKey, content_hash};
use crate::file::paths::{FileProvider, PathInterner};
use crate::include::IncludeResolver;
use crate::include::config::CompilerConfig;
use crate::preprocess::directive::{Directive, SpannedDirective};
use crate::sema::declarations::{assign_guards, build_facts, mark_settling_macro_facts};
use crate::sema::scopes::build_scopes_with;
use crate::summary::{FactGuard, FileSummary, IncludeFact, MacroFact};
use crate::summary_codec::DecodeError;
pub struct FileIndexer<'a, F: FileProvider> {
files: &'a F,
config: &'a CompilerConfig,
bodies: Option<&'a dyn cpp_parser::MacroBodies>,
macro_facts: Option<&'a dyn cpp_parser::MacroFacts>,
dead_macros: Vec<usize>,
seed: Option<&'a crate::Marked>,
scanned: Option<&'a ScannedIncludes>,
directives: Option<&'a FileSummary>,
}
#[derive(Debug, Default)]
pub struct ScannedIncludes {
found: std::collections::HashMap<
usize,
(
crate::preprocess::directive::IncludeForm,
Box<str>,
bool,
Option<PathBuf>,
),
>,
order: Vec<usize>,
}
impl ScannedIncludes {
pub fn targets(&self) -> Vec<PathBuf> {
self.order
.iter()
.filter_map(|at| self.found.get(at)?.3.clone())
.collect()
}
fn resolved(
&self,
at: usize,
include: &crate::preprocess::directive::Include,
) -> Option<Option<PathBuf>> {
let (form, target, is_next, resolved) = self.found.get(&at)?;
(*form == include.form && **target == *include.target && *is_next == include.is_next)
.then(|| resolved.clone())
}
}
impl<'a, F: FileProvider> FileIndexer<'a, F> {
pub fn new(files: &'a F, config: &'a CompilerConfig) -> Self {
FileIndexer {
files,
config,
bodies: None,
macro_facts: None,
dead_macros: Vec::new(),
seed: None,
scanned: None,
directives: None,
}
}
pub fn with_directives(mut self, directives: Option<&'a FileSummary>) -> Self {
self.directives = directives;
self
}
pub fn with_scanned_includes(mut self, scanned: &'a ScannedIncludes) -> Self {
self.scanned = Some(scanned);
self
}
pub fn with_scanned_includes_opt(mut self, scanned: Option<&'a ScannedIncludes>) -> Self {
self.scanned = scanned;
self
}
pub fn with_macro_bodies<T: cpp_parser::MacroFacts>(mut self, bodies: &'a T) -> Self {
self.bodies = Some(bodies);
self.macro_facts = Some(bodies);
self
}
pub fn with_seed(mut self, seed: &'a crate::Marked) -> Self {
self.seed = Some(seed);
self
}
pub fn without_these_macros(mut self, dead: &[usize]) -> Self {
self.dead_macros = dead.to_vec();
self
}
pub fn index(&self, path: &Path, source: &str, key: SummaryKey) -> FileSummary {
let config = ParserConfig::default()
.with_dialect(self.config.dialect())
.with_cuda(self.config.cuda())
.with_language(self.config.language_for(path));
let tree = { CppParser::parse(source, config) };
let summary = { self.index_tree(path, source, &tree, key, true) };
{
drop(tree);
}
summary
}
pub fn includes_of(&self, path: &Path, source: &str) -> Vec<PathBuf> {
self.scan_includes(path, source).targets()
}
pub fn scan_includes(&self, path: &Path, source: &str) -> ScannedIncludes {
let (mut tokens, _) = cpp_parser::lex(source, &cpp_parser::LexerConfig::default());
fold_quoted_header_names(source, &mut tokens);
let mut interner = PathInterner::new(cfg!(windows));
let per_file = self.config.for_file(path);
let resolver = IncludeResolver::new(self.files, &per_file);
let directory = path.parent().unwrap_or(Path::new("."));
let mut scanned = ScannedIncludes::default();
for spanned in crate::preprocess::directive::scan_directives(source, &tokens) {
let Directive::Include(include) = &spanned.directive else {
continue;
};
let Some(fact) = include_fact(
&spanned.directive,
spanned.line,
directory,
&resolver,
&mut interner,
None,
) else {
continue;
};
let at = spanned.range.start_offset;
scanned.found.insert(
at,
(
include.form,
include.target.clone(),
include.is_next,
fact.resolved,
),
);
scanned.order.push(at);
}
scanned
}
pub fn index_rendering(
&self,
path: &Path,
rendered: &crate::preprocess::cooked::RenderedCooked,
key: SummaryKey,
) -> crate::IndexedRendering {
if let Some(directory) = std::env::var_os(crate::probes::DUMP_RENDERING_DIR) {
let directory = std::path::PathBuf::from(directory);
let _ = std::fs::create_dir_all(&directory);
let name = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| "unit".to_string());
let _ = std::fs::write(directory.join(format!("{name}.rendering")), &rendered.text);
}
let config = ParserConfig::default()
.with_dialect(self.config.dialect())
.with_cuda(self.config.cuda())
.with_language(self.config.language_for(path));
let tree = { CppParser::parse(&rendered.text, config) };
let mut summary = { self.index_tree(path, &rendered.text, &tree, key, true) };
let report = { summary.map_into_the_file(rendered) };
let mut diagnostics = Vec::new();
let mut unplaced = 0usize;
for error in tree.get_errors() {
let range = cpp_parser::source_range(error.range);
let placed = rendered
.reported_span(range)
.or_else(|| rendered.reported_at(range.start_offset));
match placed {
Some(range) => diagnostics.push(crate::CookedDiagnostic {
range,
message: error.message.clone(),
}),
None => unplaced += 1,
}
}
crate::IndexedRendering {
summary,
rendered: std::sync::Arc::new(rendered.clone()),
mapped: report,
diagnostics,
unplaced,
}
}
pub fn index_the_readings(
&self,
path: &Path,
source: &str,
rendered: &crate::preprocess::cooked::RenderedCooked,
key: SummaryKey,
) -> crate::IndexedRendering {
let mut indexed = { self.index_rendering(path, rendered, key) };
let directed = match self.directives {
Some(directives) => directives.clone(),
None => self.directive_summary(path, source),
};
indexed.summary.take_the_directives_of(directed);
indexed.summary.key = key;
indexed.summary.key.content_hash = content_hash(source);
indexed
}
pub fn index_unit_rendering(
&self,
root: &Path,
stream: &crate::RenderedUnit,
key: SummaryKey,
) -> crate::IndexedUnit {
let config = || {
ParserConfig::default()
.with_dialect(self.config.dialect())
.with_cuda(self.config.cuda())
};
if let Some(directory) = std::env::var_os(crate::probes::DUMP_RENDERING_DIR) {
let directory = std::path::PathBuf::from(directory);
let _ = std::fs::create_dir_all(&directory);
let _ = std::fs::write(directory.join("unit.stream"), &stream.text);
let boundaries: Vec<String> = stream
.file_boundaries()
.iter()
.map(|at| at.to_string())
.collect();
let _ = std::fs::write(directory.join("unit.boundaries"), boundaries.join("\n"));
let files: Vec<String> = stream
.files
.iter()
.map(|path| path.to_string_lossy().into_owned())
.collect();
let _ = std::fs::write(directory.join("unit.files"), files.join("\n"));
}
let parsing = std::time::Instant::now();
let tree = {
CppParser::parse(
&stream.text,
config().with_file_boundaries(stream.file_boundaries()),
)
};
let parsed = parsing.elapsed();
#[cfg(feature = "perf-probe")]
crate::perf::mark("parse");
let indexing = std::time::Instant::now();
let summary = { self.index_tree(root, &stream.text, &tree, key, false) };
#[cfg(feature = "perf-probe")]
crate::perf::mark("index_tree");
if crate::probes::units() {
eprintln!(
"[unit] parse {:>6.1} ms facts {:>6.1} ms {} file(s), {} byte(s)",
parsed.as_secs_f64() * 1000.0,
indexing.elapsed().as_secs_f64() * 1000.0,
stream.files.len(),
stream.text.len()
);
}
let mut files: Vec<(std::path::PathBuf, crate::CookedFile)> = stream
.files
.iter()
.map(|path| (path.clone(), crate::CookedFile::default()))
.collect();
let mut unplaced = 0usize;
let errors = tree.get_errors().len();
file_what_was_found(
summary.declarations,
&tree,
stream,
&mut files,
&mut unplaced,
);
#[cfg(feature = "perf-probe")]
crate::perf::mark("files");
let mut merged: Vec<(std::path::PathBuf, crate::CookedFile)> =
Vec::with_capacity(files.len());
let mut where_to: std::collections::HashMap<std::path::PathBuf, usize> =
std::collections::HashMap::new();
for (path, cooked) in files {
match where_to.get(&path) {
Some(&index) => {
let held = &mut merged[index].1;
held.declarations.extend(cooked.declarations);
held.macros.extend(cooked.macros);
held.diagnostics.extend(cooked.diagnostics);
held.unplaced += cooked.unplaced;
}
None => {
where_to.insert(path.clone(), merged.len());
merged.push((path, cooked));
}
}
}
let files = merged;
crate::IndexedUnit {
files,
unplaced,
tokens: stream.len(),
files_with_tokens: stream.files_with_tokens(),
missing: stream.missing,
unbalanced: stream.unbalanced.clone(),
braces: stream.braces,
errors,
}
}
pub fn index_tree(
&self,
path: &Path,
source: &str,
tree: &CppSyntaxTree,
key: SummaryKey,
keep_locals: bool,
) -> FileSummary {
if let Some(directory) = std::env::var_os(crate::probes::DUMP_RENDERING_DIR) {
let directory = std::path::PathBuf::from(directory);
let _ = std::fs::create_dir_all(&directory);
let name = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| "unit".to_string());
let _ = std::fs::write(directory.join(format!("{name}.parsed")), source);
}
let key = SummaryKey::new(content_hash(source), key.context_hash);
let root = tree.get_red_root();
let preprocessing = {
match self.seed {
Some(seed) => {
crate::preprocess::preprocess_with_a_seed(source, tree.get_tokens(), seed)
}
None => crate::preprocess::preprocess(source, tree.get_tokens()),
}
};
let evidence: &dyn cpp_parser::MacroBodies = match self.bodies {
Some(bodies) => bodies,
None => &crate::sema::scopes::NoMacroBodies,
};
let scoping = std::time::Instant::now();
let scopes = {
let built = build_scopes_with(&root, evidence, keep_locals);
#[cfg(feature = "perf-probe")]
crate::perf::mark("scopes");
built
};
let scopes_ms = scoping.elapsed().as_secs_f64() * 1000.0;
let errors: Vec<cpp_parser::SourceRange> = tree
.get_errors()
.iter()
.map(|error| cpp_parser::source_range(error.range))
.collect();
let making = std::time::Instant::now();
let (mut declarations, mut guards) =
{ build_facts(&scopes, &preprocessing, &root, &errors, keep_locals) };
if crate::probes::units() {
eprintln!(
"[unit] scopes {:>6.1} ms facts {:>6.1} ms ({} fact(s))",
scopes_ms,
making.elapsed().as_secs_f64() * 1000.0,
declarations.len()
);
}
let mut interner = PathInterner::new(cfg!(windows));
let per_file = self.config.for_file(path);
let resolver = IncludeResolver::new(self.files, &per_file);
let directory = path.parent().unwrap_or(Path::new("."));
let (mut macros, mut includes) = {
let macros: Vec<MacroFact> = preprocessing
.directives
.iter()
.filter_map(macro_fact)
.collect();
let includes: Vec<IncludeFact> = preprocessing
.directives
.iter()
.filter_map(|spanned| {
include_fact(
&spanned.directive,
spanned.line,
directory,
&resolver,
&mut interner,
self.scanned,
)
})
.collect();
(macros, includes)
};
if !self.dead_macros.is_empty() {
macros.retain(|fact| !self.dead_macros.contains(&fact.range.start_offset));
}
macros.sort_by_key(|fact| fact.range.start_offset);
includes.sort_by_key(|fact| fact.range.start_offset);
let mut guarded: Vec<(&mut FactGuard, usize)> = macros
.iter_mut()
.map(|fact| (&mut fact.guard, fact.range.start_offset))
.chain(
includes
.iter_mut()
.map(|fact| (&mut fact.guard, fact.range.start_offset)),
)
.collect();
guarded.sort_by_key(|(_, at)| *at);
let own_guard = {
assign_guards(&mut guarded, &preprocessing, &mut guards);
let own_guard = own_guard_region_from_tokens(&preprocessing, tree.get_tokens());
guards.own_guard = own_guard.map(|region| region as u32);
guards.visit_once = preprocessing.directives.iter().any(|spanned| {
matches!(
&spanned.directive,
crate::directive::Directive::Pragma { tokens }
if tokens.first().is_some_and(|token| token.text() == "once")
)
});
if let Some(region) = own_guard {
let mut all: Vec<&mut FactGuard> = declarations
.iter_mut()
.map(|fact| &mut fact.guard)
.chain(macros.iter_mut().map(|fact| &mut fact.guard))
.chain(includes.iter_mut().map(|fact| &mut fact.guard))
.collect();
deguard_the_files_own_guard(&mut all, region);
}
own_guard
};
{
mark_settling_macro_facts(&preprocessing, own_guard, &mut macros);
}
let modules = { modules_of(&root, directory, &resolver, &mut interner) };
FileSummary {
path: path.to_path_buf(),
key,
declarations,
macros,
includes,
guards,
macro_readings: scopes.macro_readings,
use_filter: crate::summary::use_filter_of(&root),
modules,
}
}
pub fn directive_summary(&self, path: &Path, source: &str) -> FileSummary {
let (mut tokens, _) = cpp_parser::lex(source, &cpp_parser::LexerConfig::default());
fold_quoted_header_names(source, &mut tokens);
let preprocessing = match self.seed {
Some(seed) => crate::preprocess::preprocess_with_a_seed(source, &tokens, seed),
None => crate::preprocess::preprocess(source, &tokens),
};
let mut interner = PathInterner::new(cfg!(windows));
let per_file = self.config.for_file(path);
let resolver = IncludeResolver::new(self.files, &per_file);
let directory = path.parent().unwrap_or(Path::new("."));
let (mut macros, mut includes) = {
let macros: Vec<MacroFact> = preprocessing
.directives
.iter()
.filter_map(macro_fact)
.collect();
let includes: Vec<IncludeFact> = preprocessing
.directives
.iter()
.filter_map(|spanned| {
include_fact(
&spanned.directive,
spanned.line,
directory,
&resolver,
&mut interner,
self.scanned,
)
})
.collect();
(macros, includes)
};
if !self.dead_macros.is_empty() {
macros.retain(|fact| !self.dead_macros.contains(&fact.range.start_offset));
}
macros.sort_by_key(|fact| fact.range.start_offset);
includes.sort_by_key(|fact| fact.range.start_offset);
let mut guards = crate::summary::SummaryGuards::default();
let mut guarded: Vec<(&mut FactGuard, usize)> = macros
.iter_mut()
.map(|fact| (&mut fact.guard, fact.range.start_offset))
.chain(
includes
.iter_mut()
.map(|fact| (&mut fact.guard, fact.range.start_offset)),
)
.collect();
guarded.sort_by_key(|(_, at)| *at);
assign_guards(&mut guarded, &preprocessing, &mut guards);
let own_guard = own_guard_region_from_tokens(&preprocessing, &tokens);
guards.own_guard = own_guard.map(|region| region as u32);
guards.visit_once = preprocessing.directives.iter().any(|spanned| {
matches!(
&spanned.directive,
crate::directive::Directive::Pragma { tokens }
if tokens.first().is_some_and(|token| token.text() == "once")
)
});
if let Some(region) = own_guard {
let mut all: Vec<&mut FactGuard> = macros
.iter_mut()
.map(|fact| &mut fact.guard)
.chain(includes.iter_mut().map(|fact| &mut fact.guard))
.collect();
deguard_the_files_own_guard(&mut all, region);
}
mark_settling_macro_facts(&preprocessing, own_guard, &mut macros);
FileSummary {
path: path.to_path_buf(),
key: SummaryKey::new(0, 0),
declarations: Vec::new(),
macros,
includes,
guards,
macro_readings: Vec::new(),
use_filter: crate::summary::use_filter_of_tokens(source, &tokens),
modules: crate::ModuleReading::default(),
}
}
}
fn modules_of<F: FileProvider>(
root: &cpp_parser::CppSyntaxNode,
including: &Path,
resolver: &IncludeResolver<'_, F>,
interner: &mut PathInterner,
) -> crate::ModuleReading {
let info = crate::ModuleInfo::from_tree(root);
let header_units: Vec<std::path::PathBuf> = info
.imports
.iter()
.filter_map(|declaration| match &declaration.target {
crate::ImportTarget::HeaderUnit { name, is_angle } => {
let include = crate::directive::Include {
target: name.to_string().into(),
form: if *is_angle {
crate::directive::IncludeForm::Angle
} else {
crate::directive::IncludeForm::Quote
},
is_next: false,
};
resolver
.resolve(&include, including, None, interner)
.resolved()
.map(|resolved| resolved.path.clone())
}
_ => None,
})
.collect();
let partitions: Vec<std::path::PathBuf> = match info.module_name.as_deref() {
Some(module) if info.has_an_imported_partition() => {
let mut scanner = crate::ModuleScanner::new(resolver.files(), resolver.config());
let mut found = Vec::new();
for declaration in &info.imports {
let Some(name) = declaration.target.partition_name() else {
continue;
};
if let crate::ImportOutcome::Resolved(unit) =
scanner.resolve_partition(Some(module), name, including, interner)
&& let Some(entry) = scanner.units().iter().find(|entry| entry.file == unit)
{
found.push(entry.path.clone());
}
}
found
}
_ => Vec::new(),
};
crate::ModuleReading {
module: info.module_name,
partition: info.partition_name,
is_interface: info.unit.is_some_and(crate::ModuleUnit::is_interface),
imports: info
.imports
.iter()
.filter_map(|declaration| declaration.target.module_name().map(Box::from))
.collect(),
header_units,
partitions,
}
}
pub fn summarize(path: &Path, source: &str, key: SummaryKey) -> FileSummary {
struct NoFiles;
impl FileProvider for NoFiles {
fn read(&self, _path: &Path) -> Option<String> {
None
}
fn exists(&self, _path: &Path) -> bool {
false
}
}
FileIndexer::new(&NoFiles, &CompilerConfig::default()).index(path, source, key)
}
fn macro_fact(spanned: &SpannedDirective) -> Option<MacroFact> {
match &spanned.directive {
Directive::Define(define) => {
let definition = define.macro_def.as_ref()?;
Some(MacroFact {
name: definition.name.to_string(),
kind: crate::summary::MacroKind::Definition,
function_like: definition.is_function_like(),
body: macro_body_shape(definition),
value: macro_value(definition),
alias: macro_alias(definition),
range: definition.name_range,
guard: crate::summary::FactGuard::Unconditional,
body_range: body_range_of(definition),
settles_the_name: false,
})
}
Directive::Undef { name: Some(name) } => Some(MacroFact {
name: name.to_string(),
kind: crate::summary::MacroKind::Undefinition,
function_like: false,
body: cpp_parser::MacroBody::Unknown,
value: None,
alias: None,
range: spanned.line,
body_range: None,
guard: crate::summary::FactGuard::Unconditional,
settles_the_name: false,
}),
_ => None,
}
}
fn macro_value(definition: &crate::preprocess::macros::MacroDef) -> Option<Box<str>> {
if definition.is_function_like() {
return None;
}
let mut significant = definition.body.significant();
let only = significant.next()?;
if significant.next().is_some() {
return None;
}
(only.kind == cpp_parser::CppTokenKind::IntegerLiteral).then(|| only.text.as_str().into())
}
fn macro_alias(definition: &crate::preprocess::macros::MacroDef) -> Option<Box<str>> {
if definition.is_function_like() {
return None;
}
let mut significant = definition.body.significant();
let only = significant.next()?;
if significant.next().is_some() {
return None;
}
(only.kind == cpp_parser::CppTokenKind::Identifier).then(|| Box::from(only.text()))
}
fn own_guard_region_from_tokens(
preprocessing: &crate::FilePreprocessing,
tokens: &[cpp_parser::CppTokenData],
) -> Option<usize> {
match crate::guards::detect_guard_from_tokens(&preprocessing.directives, tokens) {
crate::guards::Guard::Macro(_) => Some(0),
crate::guards::Guard::PragmaOnce => {
crate::guards::has_a_macro_guard_from_tokens(&preprocessing.directives, tokens)
.then_some(0)
}
crate::guards::Guard::None => None,
}
}
fn deguard_the_files_own_guard(facts: &mut [&mut FactGuard], region: usize) {
for fact in facts {
if **fact == FactGuard::Region(region as u32) {
**fact = FactGuard::Unconditional;
}
}
}
fn body_range_of(
definition: &crate::preprocess::macros::MacroDef,
) -> Option<cpp_parser::SourceRange> {
let first = definition.body.tokens.first()?;
let start = first.range.start_offset;
let end = match definition.body.significant().last() {
Some(last) => last.range.start_offset + last.range.length,
None => start,
};
Some(cpp_parser::SourceRange::new(
start,
end.saturating_sub(start),
))
}
fn macro_body_shape(definition: &crate::preprocess::macros::MacroDef) -> cpp_parser::MacroBody {
use cpp_parser::CppTokenKind;
use cpp_parser::MacroBody;
let tokens: Vec<CppTokenKind> = definition
.body
.significant()
.map(|token| token.kind)
.collect();
let Some(first) = tokens.first().copied() else {
return MacroBody::Unknown;
};
if first == CppTokenKind::LeftBrace && tokens.last().copied() == Some(CppTokenKind::RightBrace)
{
return MacroBody::Block;
}
if matches!(
first,
CppTokenKind::IfKeyword
| CppTokenKind::ForKeyword
| CppTokenKind::WhileKeyword
| CppTokenKind::SwitchKeyword
| CppTokenKind::DoKeyword
| CppTokenKind::ReturnKeyword
| CppTokenKind::ThrowKeyword
| CppTokenKind::TryKeyword
| CppTokenKind::BreakKeyword
| CppTokenKind::ContinueKeyword
| CppTokenKind::GotoKeyword
) {
return MacroBody::Statement;
}
if is_specifier_like(tokens[0])
|| is_compiler_specifier_macro(&tokens, first_spelling(definition))
{
return MacroBody::Specifier;
}
if tokens.iter().all(|kind| is_type_word(*kind)) {
return MacroBody::Type;
}
if is_one_parenthesised_group(&tokens) {
return MacroBody::Expression;
}
MacroBody::Unknown
}
fn is_specifier_like(kind: cpp_parser::CppTokenKind) -> bool {
use cpp_parser::CppTokenKind as K;
matches!(
kind,
K::ExternKeyword
| K::StaticKeyword
| K::InlineKeyword
| K::ConstexprKeyword
| K::VirtualKeyword
| K::ExplicitKeyword
| K::MutableKeyword
| K::ThreadLocalKeyword
| K::TypedefKeyword
| K::FriendKeyword
)
}
fn is_type_word(kind: cpp_parser::CppTokenKind) -> bool {
use cpp_parser::CppTokenKind as K;
matches!(
kind,
K::VoidKeyword
| K::BoolLiteral
| K::CharKeyword
| K::ShortKeyword
| K::IntKeyword
| K::LongKeyword
| K::FloatKeyword
| K::DoubleKeyword
| K::SignedKeyword
| K::UnsignedKeyword
)
}
fn is_compiler_specifier_macro(tokens: &[cpp_parser::CppTokenKind], spelling: &str) -> bool {
use cpp_parser::CppTokenKind as K;
if tokens.first().copied() != Some(K::Identifier)
|| tokens.get(1).copied() != Some(K::LeftParen)
|| tokens.last().copied() != Some(K::RightParen)
{
return false;
}
matches!(
spelling,
"__declspec" | "__attribute__" | "__attribute" | "__cdecl" | "__stdcall" | "__fastcall"
)
}
fn first_spelling(definition: &crate::preprocess::macros::MacroDef) -> &str {
definition
.body
.significant()
.next()
.map(|token| token.text.as_ref())
.unwrap_or("")
}
fn is_one_parenthesised_group(tokens: &[cpp_parser::CppTokenKind]) -> bool {
use cpp_parser::CppTokenKind as K;
if tokens.first().copied() != Some(K::LeftParen)
|| tokens.last().copied() != Some(K::RightParen)
{
return false;
}
let mut depth = 0isize;
for (index, kind) in tokens.iter().enumerate() {
match kind {
K::LeftParen => depth += 1,
K::RightParen => {
depth -= 1;
if depth == 0 {
return index == tokens.len() - 1;
}
}
_ => {}
}
}
false
}
fn file_what_was_found(
declarations: Vec<crate::DeclFact>,
tree: &CppSyntaxTree,
stream: &crate::RenderedUnit,
files: &mut [(std::path::PathBuf, crate::CookedFile)],
unplaced: &mut usize,
) {
let tracing = std::env::var("CPPLS_TRACE_ATTRIBUTION").is_ok();
let interested = |name: &str| matches!(name, "cout" | "map" | "wcout" | "multimap");
if tracing {
eprintln!("[attr] {} declaration(s) to place", declarations.len());
}
for mut fact in declarations {
if tracing && interested(&fact.name) {
eprintln!(
"[attr] {} kind {:?} range {}..{}",
fact.name,
fact.kind,
fact.range.start_offset,
fact.range.end_offset()
);
}
let Some((file, range)) = stream.written_span(fact.range) else {
if tracing && interested(&fact.name) {
eprintln!("[attr] {} -> no written span", fact.name);
}
*unplaced += 1;
continue;
};
let Some((name_file, name_range)) = stream.written_span(fact.name_range) else {
*unplaced += 1;
continue;
};
if name_file != file {
if tracing && interested(&fact.name) {
eprintln!(
"[attr] {} -> the name is in file {name_file}, the declaration in {file}",
fact.name
);
}
*unplaced += 1;
continue;
}
if !stream.span_lands_in(file, range) || !stream.span_lands_in(name_file, name_range) {
*unplaced += 1;
continue;
}
if tracing && interested(&fact.name) {
eprintln!(
"[attr] {} -> file {file} {:?}",
fact.name,
files.get(file as usize).map(|(path, _)| path.file_name())
);
}
fact.range = range;
fact.name_range = name_range;
if let Some((_, cooked)) = files.get_mut(file as usize) {
cooked.declarations.push(fact);
}
}
for error in tree.get_errors() {
let range = cpp_parser::source_range(error.range);
match stream.written_span(range) {
Some((file, range)) => {
if let Some((_, cooked)) = files.get_mut(file as usize) {
cooked.diagnostics.push(crate::CookedDiagnostic {
range,
message: error.message.clone(),
});
}
}
None => *unplaced += 1,
}
}
}
use crate::preprocess::directive::fold_quoted_header_names;
fn include_fact<F: FileProvider>(
directive: &Directive,
range: cpp_parser::SourceRange,
including: &Path,
resolver: &IncludeResolver<'_, F>,
interner: &mut PathInterner,
scanned: Option<&ScannedIncludes>,
) -> Option<IncludeFact> {
let Directive::Include(include) = directive else {
return None;
};
let resolved: Option<PathBuf> =
match scanned.and_then(|scanned| scanned.resolved(range.start_offset, include)) {
Some(resolved) => resolved,
None => resolver
.resolve(include, including, None, interner)
.resolved()
.map(|resolved| resolved.path.clone()),
};
Some(IncludeFact {
form: include.form,
spelling: include.target.to_string(),
resolved,
is_next: include.is_next,
range,
guard: crate::summary::FactGuard::Unconditional,
})
}
#[allow(dead_code)]
pub fn write_summary(summary: &FileSummary, cache_directory: &Path) -> std::io::Result<PathBuf> {
let path = summary.key.path_under(cache_directory);
let bytes = crate::summary_codec::encode(summary);
if let Some(directory) = path.parent() {
std::fs::create_dir_all(directory)?;
}
static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let temporary = path.with_extension(format!(
"{}.{}.tmp",
std::process::id(),
WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
));
std::fs::write(&temporary, &bytes)?;
std::fs::rename(&temporary, &path)?;
Ok(path)
}
#[allow(dead_code)]
pub fn read_summary(path: &Path) -> Result<FileSummary, SummaryReadError> {
let bytes = std::fs::read(path).map_err(SummaryReadError::Io)?;
crate::summary_codec::decode(&bytes).map_err(SummaryReadError::Decode)
}
#[derive(Debug)]
pub enum SummaryReadError {
Io(std::io::Error),
Decode(DecodeError),
}
impl std::fmt::Display for SummaryReadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SummaryReadError::Io(error) => write!(f, "cannot read the summary: {error}"),
SummaryReadError::Decode(error) => write!(f, "{error}"),
}
}
}
impl std::error::Error for SummaryReadError {}
#[cfg(test)]
mod tests {
use super::{FileIndexer, include_fact, macro_body_shape, summarize, write_summary};
use crate::cache::SummaryKey;
use crate::file::paths::{FileProvider, MemoryFiles, PathInterner};
use crate::include::IncludeResolver;
use crate::include::config::CompilerConfig;
use crate::preprocess::directive::{Directive, IncludeForm};
use crate::preprocess::macros::MacroTable;
use crate::summary::{DeclKind, FactGuard, MacroKind};
use cpp_parser::{CppParser, MacroBody, ParserConfig};
use std::path::{Path, PathBuf};
fn key() -> SummaryKey {
SummaryKey::new(0, 0)
}
fn summary(source: &str) -> crate::summary::FileSummary {
summarize(Path::new("/p/widget.cpp"), source, key())
}
#[test]
fn a_summary_is_read_for_the_compiler_it_was_configured_with() {
let files = MemoryFiles::new();
let names = |dialect: cpp_parser::Dialect| {
let config = CompilerConfig::default().with_dialect(dialect);
let summary = FileIndexer::new(&files, &config).index(
Path::new("/p/a.cpp"),
"int __int128;\n",
key(),
);
summary
.declarations
.iter()
.map(|fact| fact.name.clone())
.collect::<Vec<_>>()
};
assert_eq!(
names(cpp_parser::Dialect::Gnu),
Vec::<String>::new(),
"under GNU `__int128` is a type, so `int __int128;` has no declarator"
);
assert_eq!(
names(cpp_parser::Dialect::Msvc),
vec!["__int128".to_string()],
"and under MSVC the same text declares a variable called `__int128`"
);
}
fn region_shapes(source: &str) -> Vec<Vec<String>> {
let summary = summary(source);
summary
.guards
.conditionals
.iter()
.map(|conditional| {
conditional
.branches
.iter()
.map(|branch| {
format!(
"{:?} {} {}..{}",
branch.kind,
branch.condition.as_deref().unwrap_or("-"),
branch.body.start_offset,
branch.body.end_offset()
)
})
.collect()
})
.collect()
}
#[test]
fn a_summary_stores_what_each_conditional_asks() {
let shapes = region_shapes(
"#if defined(_WIN32)\n#include <a.h>\n#elif __cplusplus >= 201703L\n#include <b.h>\n#else\n#include <c.h>\n#endif\n",
);
assert_eq!(shapes.len(), 1, "one conditional, three branches");
let branches = &shapes[0];
assert_eq!(branches.len(), 3);
assert!(
branches[0].starts_with("If defined(_WIN32)"),
"the expression's tokens, spelled as the source wrote them: {}",
branches[0]
);
assert!(
branches[1].starts_with("Elif __cplusplus >= 201703L"),
"a version test is stored as the text a value can be compared against: {}",
branches[1]
);
assert!(
branches[2].starts_with("Else -"),
"`#else` asks nothing: {}",
branches[2]
);
let source = "#ifdef A\n#include <a.h>\n#endif\n";
let shapes = region_shapes(source);
assert_eq!(
shapes[0][0],
format!(
"Ifdef A {}..{}",
source.find("#ifdef").expect("the directive") + "#ifdef A\n".len(),
source.find("#endif").expect("the #endif")
),
"the `#ifdef` branch guards everything between its directive and the `#endif`"
);
}
#[test]
fn a_regions_parent_is_the_conditional_it_is_written_inside() {
let nested = summary("#ifdef A\n#ifdef B\nint x;\n#endif\n#endif\n");
let parents: Vec<Option<u32>> = nested
.guards
.conditionals
.iter()
.map(|conditional| conditional.parent)
.collect();
assert_eq!(parents, [None, Some(0)]);
let chained =
summary("#ifdef A\nint a;\n#elif defined(B)\nint b;\n#else\nint c;\n#endif\n");
assert_eq!(chained.guards.conditionals.len(), 1);
assert_eq!(chained.guards.conditionals[0].branches.len(), 3);
assert!(chained.guards.conditionals[0].exhaustive());
}
#[test]
fn the_code_a_position_is_in_is_found_by_walking_outwards() {
let source = "#ifdef A\n#ifdef B\nint x;\n#endif\n#endif\n";
let summary = summary(source);
let x = source.find("int x;").expect("the declaration");
let chain = summary.guards.conditions_at(x);
assert_eq!(
chain.iter().map(|at| at.region).collect::<Vec<_>>(),
[1, 0],
"innermost first"
);
assert!(
chain.iter().all(|at| at.condition_at < x),
"and each condition is evaluated at its *own* offset, which is above the code: {chain:?}"
);
let source = "int x;\n#ifdef A\nint y;\n#endif\n";
assert!(
summary
.guards
.conditions_at(source.find("int x;").expect("the declaration"))
.is_empty()
);
}
#[test]
fn a_position_is_looked_up_in_the_branch_it_sits_in() {
let source = "#ifdef A\nint taken;\n#else\nint not_taken;\n#endif\n";
let summary = summary(source);
let region = summary.guards.conditionals.first().expect("one region");
let first = source.find("int taken").expect("the first branch");
let second = source.find("int not_taken").expect("the second branch");
assert_eq!(region.branch_at(first), Some(0));
assert_eq!(region.branch_at(second), Some(1));
}
#[test]
fn the_chain_a_guard_names_is_the_chain_the_position_is_in() {
for source in [
"#ifdef A\nint x;\n#endif\n",
"#ifdef A\n#ifdef B\nint x;\n#endif\n#endif\n",
"#ifdef A\nint a;\n#elif defined(B)\nint b;\n#else\nint c;\n#endif\n",
"#ifndef GUARD\n#define GUARD\n#ifdef A\nint x;\n#endif\n#endif\n",
"int early;\n#if defined(A) && defined(B)\n#ifdef C\nint x;\n#else\nint y;\n#endif\n#endif\n",
] {
let summary = summary(source);
for (region, conditional) in summary.guards.conditionals.iter().enumerate() {
for branch in &conditional.branches {
if branch.body.length == 0 {
continue;
}
let at = branch.body.start_offset;
assert_eq!(
summary.guards.conditions_at(at),
summary.guards.conditions_of(region as u32),
"{source:?} at {at} (region {region})"
);
}
}
}
}
#[test]
fn a_definition_carries_a_value_exactly_when_a_condition_could_read_one() {
let value_of = |source: &str, name: &str| {
summary(source)
.macros
.iter()
.find(|fact| fact.name == name)
.and_then(|fact| fact.value.clone())
};
assert_eq!(value_of("#define ABI 1\n", "ABI").as_deref(), Some("1"));
assert_eq!(
value_of("#define WIDE 0x10UL\n", "WIDE").as_deref(),
Some("0x10UL"),
"the spelling is kept as written: the evaluator is what reads it"
);
assert_eq!(value_of("#define NAME other\n", "NAME"), None);
assert_eq!(value_of("#define EXPR 1 + 2\n", "EXPR"), None);
assert_eq!(value_of("#define EMPTY\n", "EMPTY"), None);
assert_eq!(value_of("#define CALL(x) x\n", "CALL"), None);
assert_eq!(
value_of("#undef GONE\n", "GONE"),
None,
"an `#undef` says the name stops being a macro, which is all it says"
);
}
fn macro_facts(source: &str, name: &str) -> Vec<(crate::summary::MacroKind, FactGuard, bool)> {
summary(source)
.macros
.iter()
.filter(|fact| fact.name == name)
.map(|fact| (fact.kind, fact.guard, fact.settles_the_name))
.collect()
}
#[test]
fn a_define_inside_ifndef_settles_the_name_whatever_the_branch() {
assert_eq!(
macro_facts("int early;\n#ifndef NAME\n#define NAME 1\n#endif\n", "NAME"),
[(MacroKind::Definition, FactGuard::Region(0), true)]
);
}
#[test]
fn the_files_own_guard_is_not_a_condition_and_neither_is_a_define_inside_it() {
assert_eq!(
macro_facts(
"#ifndef WIDGET_H\n#define WIDGET_H\n#ifndef NAME\n#define NAME 1\n#endif\n#endif\n",
"NAME"
),
[(MacroKind::Definition, FactGuard::Region(1), true)]
);
assert_eq!(
macro_facts("#ifndef WIDGET_H\n#define WIDGET_H\n#endif\n", "WIDGET_H"),
[(MacroKind::Definition, FactGuard::Unconditional, false)]
);
}
#[test]
fn a_region_whose_every_branch_agrees_settles_the_name() {
assert_eq!(
macro_facts(
"int early;\n#if defined(A)\n#define NAME 1\n#else\n#define NAME 2\n#endif\n",
"NAME"
),
[
(MacroKind::Definition, FactGuard::Region(0), true),
(MacroKind::Definition, FactGuard::Region(0), true)
]
);
assert_eq!(
macro_facts("int early;\n#ifdef NAME\n#undef NAME\n#endif\n", "NAME"),
[(MacroKind::Undefinition, FactGuard::Region(0), true)]
);
}
#[test]
fn a_region_that_does_not_settle_the_name_marks_nothing() {
for source in [
"int early;\n#if defined(A)\n#define NAME 1\n#endif\n",
"int early;\n#if defined(A)\n#define NAME 1\n#else\n#undef NAME\n#endif\n",
"int early;\n#ifndef NAME\n#define NAME 1\n#undef NAME\n#endif\n",
"int early;\n#ifndef OTHER\n#define NAME 1\n#endif\n",
"int early;\n#if defined(A)\n#define NAME 1\n#else\n#define OTHER 2\n#endif\n",
] {
let facts = macro_facts(source, "NAME");
assert!(
facts.iter().all(|(_, _, settles)| !settles),
"{source:?} must settle nothing, got {facts:?}"
);
}
}
#[test]
fn a_settling_region_inside_a_plain_conditional_settles_nothing() {
assert_eq!(
macro_facts(
"int early;\n#if defined(A)\n#ifndef NAME\n#define NAME 1\n#endif\n#endif\n",
"NAME"
),
[(MacroKind::Definition, FactGuard::Region(1), false)]
);
}
#[test]
fn a_settling_region_reached_through_an_if_defined_settles_the_name() {
for condition in ["!defined(NAME)", "!defined NAME", "(!defined(NAME))"] {
let source = format!("int early;\n#if {condition}\n#define NAME 1\n#endif\n");
assert_eq!(
macro_facts(&source, "NAME"),
[(MacroKind::Definition, FactGuard::Region(0), true)],
"{condition} should settle the name"
);
}
}
#[test]
fn a_file_whose_conditionals_do_not_balance_settles_nothing() {
for source in [
"int early;\n#if defined(A)\n#ifndef NAME\n#define NAME 1\n#endif\n",
"int early;\n#endif\n#ifndef NAME\n#define NAME 1\n#endif\n",
] {
let facts = macro_facts(source, "NAME");
assert!(
facts.iter().all(|(_, _, settles)| !settles),
"{source:?} must settle nothing, got {facts:?}"
);
}
}
#[test]
fn a_file_with_declarations_and_macros_summarizes_both() {
let summary = summary(
"#define MY_API\n#define MAX(a, b) ((a) > (b) ? (a) : (b))\nstruct Widget { int size; };\n",
);
assert_eq!(summary.declarations.len(), 2, "the class and its member");
assert_eq!(summary.macros.len(), 2, "both macros");
let api = summary
.macros
.iter()
.find(|fact| fact.name == "MY_API")
.expect("the object-like macro is a fact");
assert!(!api.function_like);
assert_eq!(api.body, MacroBody::Unknown, "an empty body has no shape");
let max = summary
.macros
.iter()
.find(|fact| fact.name == "MAX")
.expect("the function-like macro is a fact");
assert!(max.function_like);
assert_eq!(
max.body,
MacroBody::Expression,
"the body is one parenthesised group"
);
}
#[test]
fn a_declaration_inside_the_files_own_guard_is_unconditional() {
let summary = summary(
"#ifndef H\n#define H\nstruct Widget { int size; };\n#include \"other.h\"\n#endif\n",
);
let widget = summary
.declarations
.iter()
.find(|fact| fact.name == "Widget")
.expect("the guarded declaration is a fact");
assert_eq!(
widget.guard,
FactGuard::Unconditional,
"the file's own guard is entered by including the file at all"
);
let include = summary
.includes
.iter()
.find(|fact| fact.spelling == "other.h")
.expect("the include is a fact");
assert_eq!(
include.guard,
FactGuard::Unconditional,
"and so is an `#include` written inside it"
);
assert_eq!(
summary.guards.regions.len(),
1,
"the region is still recorded: the `#if` is a fact about the text either way"
);
}
#[test]
fn a_conditional_that_is_not_the_files_guard_still_guards() {
let summary = summary("#if defined(A)\nint inside;\n#endif\n");
let fact = summary
.declarations
.iter()
.find(|fact| fact.name == "inside")
.expect("the declaration is a fact");
assert_eq!(fact.guard, FactGuard::Region(0));
}
#[test]
fn a_header_that_declares_something_before_its_guard_is_not_guarded_by_it() {
let summary = summary("int early;\n#ifndef H\n#define H\nint inside;\n#endif\n");
let early = summary
.declarations
.iter()
.find(|fact| fact.name == "early")
.expect("the declaration before the guard is a fact");
assert_eq!(
early.guard,
FactGuard::Unconditional,
"it is outside every region, which is a different answer from the guard's"
);
let inside = summary
.declarations
.iter()
.find(|fact| fact.name == "inside")
.expect("the declaration inside is a fact");
assert_eq!(
inside.guard,
FactGuard::Region(0),
"a guard that does not wrap the file does not de-guard what it does contain"
);
}
#[test]
fn a_declaration_in_a_conditional_keeps_its_region_through_the_builder() {
let summary = summary("#if defined(A)\nint inside;\n#endif\n");
assert_eq!(summary.guards.regions.len(), 1);
let fact = summary
.declarations
.iter()
.find(|fact| fact.name == "inside")
.expect("the guarded declaration is a fact");
assert_eq!(fact.guard, FactGuard::Region(0));
}
#[test]
fn an_include_that_cannot_be_resolved_keeps_its_spelling() {
let summary = summary("#include <vector>\n#include \"local.h\"\n");
assert_eq!(summary.includes.len(), 2);
let vector = &summary.includes[0];
assert_eq!(vector.form, IncludeForm::Angle);
assert_eq!(vector.spelling, "vector");
assert_eq!(
vector.resolved, None,
"with nothing to search, the include is unresolved rather than dropped"
);
assert_eq!(summary.includes[1].form, IncludeForm::Quote);
assert_eq!(summary.includes[1].spelling, "local.h");
}
#[test]
fn an_include_resolves_against_the_provider() {
let files = MemoryFiles::new()
.with_file("/p/local.h", "int x;\n")
.with_file("/usr/include/vector", "// the real one\n");
let mut config = CompilerConfig::default();
config.include_paths = vec![crate::include::config::IncludePath::system("/usr/include")];
let indexer = FileIndexer::new(&files, &config);
let summary = indexer.index(
Path::new("/p/widget.cpp"),
"#include <vector>\n#include \"local.h\"\n",
key(),
);
let vector = summary
.includes
.iter()
.find(|fact| fact.spelling == "vector")
.expect("the angle include is a fact");
assert_eq!(
vector.resolved.as_deref(),
Some(Path::new("/usr/include/vector")),
"an angle include searched the configured path"
);
let local = summary
.includes
.iter()
.find(|fact| fact.spelling == "local.h")
.expect("the quoted include is a fact");
assert_eq!(
local.resolved.as_deref(),
Some(Path::new("/p/local.h")),
"a quoted include looks beside the including file first"
);
}
#[test]
fn every_summary_survives_being_written_and_read_back() {
let directory = std::env::temp_dir().join("cppls-summary-round-trip");
let _ = std::fs::remove_dir_all(&directory);
let summary = summary(
"#define MY_API\n#if defined(A)\nstruct Widget { int size; };\n#endif\n#include <vector>\n",
);
let written = write_summary(&summary, &directory).expect("the write must succeed");
assert!(
written.starts_with(&directory),
"the summary lands under the project root: {written:?}"
);
let read = super::read_summary(&written).expect("what was written must be readable");
assert_eq!(read, summary);
let _ = std::fs::remove_dir_all(&directory);
}
#[test]
fn the_macro_body_classifier_reads_each_shape() {
let cases = [
("#define A __declspec(dllexport)", MacroBody::Specifier),
("#define A extern \"C\"", MacroBody::Specifier),
("#define A do { } while (false)", MacroBody::Statement),
("#define A if (x) { }", MacroBody::Statement),
("#define A return", MacroBody::Statement),
("#define A ((a) > (b) ? (a) : (b))", MacroBody::Expression),
("#define A (a)", MacroBody::Expression),
("#define A int", MacroBody::Type),
("#define A unsigned long", MacroBody::Type),
("#define A { }", MacroBody::Block),
("#define A", MacroBody::Unknown),
("#define A something_else + 1", MacroBody::Unknown),
];
for (source, expected) in cases {
let tree = CppParser::parse(source, ParserConfig::default());
let preprocessing = crate::preprocess::preprocess(source, tree.get_tokens());
let Directive::Define(define) = &preprocessing.directives[0].directive else {
panic!("{source:?} must be a define");
};
let definition = define.macro_def.as_ref().expect("a readable definition");
assert_eq!(
macro_body_shape(definition),
expected,
"{source:?} should be {expected:?}"
);
}
}
#[test]
fn a_body_that_is_not_one_parenthesised_group_is_not_an_expression() {
let tree = CppParser::parse("#define A (a) + (b)", ParserConfig::default());
let preprocessing = crate::preprocess::preprocess("#define A (a) + (b)", tree.get_tokens());
let Directive::Define(define) = &preprocessing.directives[0].directive else {
panic!("must be a define");
};
let definition = define.macro_def.as_ref().expect("a readable definition");
assert_eq!(macro_body_shape(definition), MacroBody::Unknown);
}
#[test]
fn an_unresolved_include_does_not_stop_the_other_facts() {
let tree = CppParser::parse(
"#include <nonexistent_xyz>\nstruct W { int a; };\n",
ParserConfig::default(),
);
let preprocessing = crate::preprocess::preprocess(
"#include <nonexistent_xyz>\nstruct W { int a; };\n",
tree.get_tokens(),
);
let files = MemoryFiles::new();
let config = CompilerConfig::default();
let mut interner = PathInterner::new(cfg!(windows));
let resolver = IncludeResolver::new(&files, &config);
let facts: Vec<_> = preprocessing
.directives
.iter()
.filter_map(|spanned| {
include_fact(
&spanned.directive,
spanned.line,
Path::new("/p"),
&resolver,
&mut interner,
None,
)
})
.collect();
assert_eq!(facts.len(), 1);
assert_eq!(facts[0].spelling, "nonexistent_xyz");
assert_eq!(facts[0].resolved, None);
}
#[test]
fn a_macro_fact_points_at_the_name_not_the_directive() {
let summary = summary(" #define MY_API int\n");
let fact = summary
.macros
.iter()
.find(|fact| fact.name == "MY_API")
.expect("the macro is a fact");
let text = " #define MY_API int\n";
assert_eq!(
&text[fact.range.start_offset..fact.range.end_offset()],
"MY_API"
);
}
#[test]
fn a_summary_carries_no_resolved_conclusions() {
let summary = summary("namespace ns { struct Widget { int member; }; }\n");
let widget = summary
.declarations
.iter()
.find(|fact| fact.name == "Widget")
.expect("the class is a fact");
assert_eq!(widget.kind, DeclKind::Type);
assert_eq!(
widget.scope.as_deref(),
Some("ns"),
"the scope is the spelling the file used, not a resolved identity"
);
assert_eq!(widget.qualified_name(), "ns::Widget");
}
struct OneFile(PathBuf, String);
impl FileProvider for OneFile {
fn read(&self, path: &Path) -> Option<String> {
(path == self.0).then(|| self.1.clone())
}
fn exists(&self, path: &Path) -> bool {
path == self.0
}
}
#[test]
fn a_provider_that_has_one_file_still_answers_for_it() {
let files = OneFile(PathBuf::from("/p/only.h"), "int x;\n".to_string());
let table = MacroTable::new();
let _ = table;
assert_eq!(
files.read(Path::new("/p/only.h")).as_deref(),
Some("int x;\n")
);
assert_eq!(files.read(Path::new("/p/other.h")), None);
}
}