use std::path::Path;
use crate::Marked;
use crate::cache::SummaryKey;
use crate::guard::{Branch, Region, Visibility};
use crate::index::environment::a_guard_is_in_force;
use crate::macros::MacroDef;
fn frame_key(path: &std::path::Path) -> String {
crate::paths::normalize_path(path, cfg!(windows))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct DeclModifiers(u32);
impl DeclModifiers {
pub const VIRTUAL: Self = Self(1 << 0);
pub const OVERRIDE: Self = Self(1 << 1);
pub const FINAL: Self = Self(1 << 2);
pub const CONSTEXPR: Self = Self(1 << 3);
pub const CONSTEVAL: Self = Self(1 << 4);
pub const CONSTINIT: Self = Self(1 << 5);
pub const STATIC: Self = Self(1 << 6);
pub const INLINE: Self = Self(1 << 7);
pub const EXPLICIT: Self = Self(1 << 8);
pub const MAYBE_UNUSED: Self = Self(1 << 9);
pub const NODISCARD: Self = Self(1 << 10);
pub const VARIADIC: Self = Self(1 << 11);
pub const DELETED: Self = Self(1 << 12);
pub const DEFAULTED: Self = Self(1 << 13);
pub const fn bits(self) -> u32 {
self.0
}
pub const fn from_bits(bits: u32) -> Self {
Self(bits)
}
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
}
pub const fn contains(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
pub const fn is_empty(self) -> bool {
self.0 == 0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeclFact {
pub name: String,
pub scope: Option<String>,
pub local: bool,
pub in_namespace: Option<String>,
pub kind: DeclKind,
pub modifiers: DeclModifiers,
pub frees: u64,
pub type_of: Option<String>,
pub returns: Option<String>,
pub split_by_a_directive: bool,
pub bases: Vec<String>,
pub parameters: Vec<String>,
pub constraints: Vec<String>,
pub parameter_defaults: Vec<String>,
pub pattern: Option<String>,
pub parameter_list: Option<String>,
pub range: cpp_parser::SourceRange,
pub name_range: cpp_parser::SourceRange,
pub clean: bool,
pub guard: FactGuard,
pub access: Option<Access>,
pub exported: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Access {
Public,
Protected,
Private,
}
impl Access {
pub fn words(self) -> &'static str {
match self {
Access::Public => "public",
Access::Protected => "protected",
Access::Private => "private",
}
}
pub fn is_open_to_everyone(self) -> bool {
matches!(self, Access::Public)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ModuleReading {
pub module: Option<Box<str>>,
pub partition: Option<Box<str>>,
pub is_interface: bool,
pub imports: Vec<Box<str>>,
pub header_units: Vec<std::path::PathBuf>,
pub partitions: Vec<std::path::PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MacroScopeReading {
pub range: cpp_parser::SourceRange,
pub name: String,
pub body: String,
pub opens: Option<Vec<String>>,
}
impl MacroScopeReading {
pub fn opens_a_scope(&self) -> bool {
self.opens.is_some()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutlineSymbol {
pub fact: DeclFact,
pub children: Vec<OutlineSymbol>,
}
impl FileSummary {
pub fn outline(&self) -> Vec<OutlineSymbol> {
outline_of(&self.declarations)
}
}
pub fn outline_of(facts: &[DeclFact]) -> Vec<OutlineSymbol> {
let mut facts: Vec<&DeclFact> = facts.iter().filter(|fact| !fact.local).collect();
facts.sort_by_key(|fact| (fact.range.start_offset, fact.range.end_offset()));
let mut roots: Vec<OutlineSymbol> = Vec::new();
let mut placed: std::collections::HashMap<String, Vec<usize>> =
std::collections::HashMap::new();
for fact in facts {
let qualified = fact.qualified_name();
let symbol = OutlineSymbol {
fact: fact.clone(),
children: Vec::new(),
};
let path = match fact.scope.as_ref().and_then(|scope| placed.get(scope)) {
Some(parent) => {
let parent = parent.clone();
let mut path = parent.clone();
path.push(symbol_at(&mut roots, &parent).children.len());
symbol_at(&mut roots, &parent).children.push(symbol);
path
}
None => {
roots.push(symbol);
vec![roots.len() - 1]
}
};
placed.insert(qualified, path);
}
roots
}
fn symbol_at<'a>(roots: &'a mut [OutlineSymbol], path: &[usize]) -> &'a mut OutlineSymbol {
let (first, rest) = path.split_first().expect("a path has at least one index");
let mut node = &mut roots[*first];
for index in rest {
node = &mut node.children[*index];
}
node
}
impl DeclFact {
pub fn qualified_name(&self) -> String {
match &self.scope {
Some(scope) if !self.name.is_empty() => format!("{scope}::{}", self.name),
Some(scope) => scope.clone(),
None => self.name.clone(),
}
}
pub fn qualified_segments(&self) -> Vec<&str> {
let mut segments: Vec<&str> = Vec::new();
if let Some(scope) = &self.scope {
segments.extend(scope.split("::"));
}
if !self.name.is_empty() {
segments.push(&self.name);
}
segments
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DeclKind {
Type,
Function,
Variable,
Namespace,
MacroLike,
Other,
}
fn parameters_before(source: &str, body_start: usize) -> Option<&str> {
let before = source.get(..body_start)?.trim_end();
let bytes = before.as_bytes();
if bytes.last() != Some(&b')') {
return None;
}
let mut depth = 0usize;
let mut at = bytes.len();
while at > 0 {
at -= 1;
match bytes[at] {
b')' => depth += 1,
b'(' => {
depth -= 1;
if depth == 0 {
return Some(&before[at..]);
}
}
_ => {}
}
}
None
}
pub type ConditionalBody = (Box<str>, bool, Option<Box<str>>, Box<str>);
fn definition_written_at(event: &TuEvent, body: &str) -> Option<crate::macros::MacroDef> {
let mut tokens: Vec<crate::token::Token> = Vec::new();
let name_at = cpp_parser::SourceRange::new(event.at, event.name.len());
tokens.push(crate::token::Token::new(
cpp_parser::CppTokenKind::Identifier,
&*event.name,
name_at,
));
if let Some(parameters) = event.parameters.as_deref() {
let at = event.at + event.name.len();
tokens.extend(lex_in_place(parameters, at));
}
let body_range = event.body_range?;
tokens.push(crate::token::Token::new(
cpp_parser::CppTokenKind::Whitespace,
" ",
cpp_parser::SourceRange::new(body_range.start_offset, 0),
));
tokens.extend(lex_in_place(body, body_range.start_offset));
let range =
cpp_parser::SourceRange::new(event.at, body_range.end_offset().saturating_sub(event.at));
let mut definition = crate::macros::parse_define(&tokens, range)?;
definition.written_in = Some(crate::macros::MacroFile::Frame(event.frame));
Some(definition)
}
fn lex_in_place(text: &str, at: usize) -> Vec<crate::token::Token> {
let (tokens, _) = cpp_parser::lex(text, &cpp_parser::LexerConfig::default());
tokens
.iter()
.map(|token| {
crate::token::Token::new(
token.kind,
&text[token.range.start_offset..token.range.end_offset()],
cpp_parser::SourceRange::new(at + token.range.start_offset, token.range.length),
)
})
.collect()
}
type ConditionalBodyValue = (bool, Option<Box<str>>, Box<str>);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MacroFact {
pub name: String,
pub kind: MacroKind,
pub function_like: bool,
pub body: cpp_parser::MacroBody,
pub body_range: Option<cpp_parser::SourceRange>,
pub value: Option<Box<str>>,
pub alias: Option<Box<str>>,
pub range: cpp_parser::SourceRange,
pub guard: FactGuard,
pub settles_the_name: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MacroKind {
Definition,
Undefinition,
}
impl MacroKind {
pub fn is_definition(self) -> bool {
matches!(self, MacroKind::Definition)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncludeFact {
pub form: IncludeForm,
pub spelling: String,
pub resolved: Option<std::path::PathBuf>,
pub is_next: bool,
pub range: cpp_parser::SourceRange,
pub guard: FactGuard,
}
impl IncludeFact {
pub fn as_include(&self) -> crate::preprocess::directive::Include {
crate::preprocess::directive::Include {
form: self.form,
target: Box::from(self.spelling.as_str()),
is_next: self.is_next,
}
}
}
pub fn macros_from_direct_includes_with_bodies<'a>(
summary: &FileSummary,
mut look_up: impl FnMut(&std::path::Path) -> Option<(&'a FileSummary, &'a str)>,
) -> Vec<cpp_parser::IncludedMacro> {
let mut entries = Vec::new();
for include in &summary.includes {
let Some((included, source)) = include.resolved.as_deref().and_then(&mut look_up) else {
continue;
};
let from_offset = include.range.start_offset + include.range.length;
for fact in &included.macros {
if !matches!(fact.guard, FactGuard::Unconditional) {
continue;
}
let body_text = fact.body_range.and_then(|range| {
source.get(range.start_offset..range.start_offset + range.length)
});
entries.push(if fact.kind.is_definition() {
cpp_parser::IncludedMacro::defined_with_body_and_parameters(
from_offset,
&fact.name,
fact.function_like,
fact.body,
body_text,
fact.body_range
.and_then(|range| parameters_before(source, range.start_offset)),
)
} else {
cpp_parser::IncludedMacro::undefined_at(from_offset, &fact.name)
});
}
}
entries
}
pub struct ClosureEvidence {
pub macros: Vec<cpp_parser::IncludedMacro>,
pub conditional_bodies: Vec<ConditionalBody>,
pub conditional_facts: usize,
pub facts_in_force: usize,
}
struct UnitState {
definitions: std::collections::HashMap<Box<str>, Binding>,
generation: u64,
}
struct Binding {
definition: std::sync::Arc<MacroDef>,
defined_in: Box<std::path::Path>,
defined_at: usize,
}
impl UnitState {
fn define(
&mut self,
name: &str,
definition: std::sync::Arc<MacroDef>,
file: &std::path::Path,
at: usize,
) {
self.definitions.insert(
name.into(),
Binding {
definition,
defined_in: Box::from(file),
defined_at: at,
},
);
self.generation += 1;
}
fn undefine(&mut self, name: &str) {
if self.definitions.remove(name).is_some() {
self.generation += 1;
}
}
}
#[derive(Default)]
pub struct MacroDefinitions {
parsed: std::collections::HashMap<
(std::sync::Arc<std::path::Path>, usize),
Option<std::sync::Arc<MacroDef>>,
>,
bytes: usize,
}
pub const MAX_DEFINITION_BYTES: usize = 32 * 1024 * 1024;
impl DeclFact {
pub fn heap_bytes(&self) -> usize {
std::mem::size_of::<DeclFact>()
+ self.name.len()
+ self.scope.as_ref().map_or(0, String::len)
+ self.in_namespace.as_ref().map_or(0, String::len)
}
}
impl MacroFact {
pub fn heap_bytes(&self) -> usize {
std::mem::size_of::<MacroFact>()
+ self.name.len()
+ self.value.as_ref().map_or(0, |text| text.len())
+ self.alias.as_ref().map_or(0, |text| text.len())
}
}
impl IncludeFact {
pub fn heap_bytes(&self) -> usize {
std::mem::size_of::<IncludeFact>()
+ self.spelling.len()
+ self
.resolved
.as_ref()
.map_or(0, |path| path.as_os_str().len())
}
}
impl FileSummary {
pub fn heap_bytes(&self) -> usize {
std::mem::size_of::<FileSummary>()
+ self.path.as_os_str().len()
+ self
.declarations
.iter()
.map(DeclFact::heap_bytes)
.sum::<usize>()
+ self.macros.iter().map(MacroFact::heap_bytes).sum::<usize>()
+ self
.includes
.iter()
.map(IncludeFact::heap_bytes)
.sum::<usize>()
+ self.guards.regions.len() * std::mem::size_of::<cpp_parser::SourceRange>()
+ self
.macro_readings
.iter()
.map(|reading| {
std::mem::size_of::<MacroScopeReading>()
+ reading.name.len()
+ reading.body.len()
})
.sum::<usize>()
+ self.use_filter.len()
+ self.modules.module.as_ref().map_or(0, |name| name.len())
+ self.modules.partition.as_ref().map_or(0, |name| name.len())
+ self
.modules
.imports
.iter()
.map(|name| name.len())
.sum::<usize>()
+ (self.modules.header_units.len() + self.modules.partitions.len())
* std::mem::size_of::<std::path::PathBuf>()
}
}
impl MacroDefinitions {
pub fn accounting(&self) -> (usize, usize) {
let mut bytes = 0usize;
for (key, definition) in &self.parsed {
bytes += std::mem::size_of::<(
(std::path::PathBuf, usize),
Option<std::sync::Arc<MacroDef>>,
)>();
bytes += key.0.as_os_str().len();
if let Some(definition) = definition {
bytes += std::mem::size_of::<MacroDef>() + definition.name.len();
if let Some(params) = &definition.params {
bytes +=
params.len() * std::mem::size_of::<crate::preprocess::macros::Parameter>();
}
}
}
(self.parsed.len(), bytes)
}
}
impl MacroDefinitions {
fn definition_of(
&mut self,
path: &std::path::Path,
source: &str,
fact: &MacroFact,
) -> Option<std::sync::Arc<MacroDef>> {
let key = (std::sync::Arc::from(path), fact.range.start_offset);
if let Some(known) = self.parsed.get(&key) {
return known.clone();
}
let definition = read_back_a_define(source, fact).map(std::sync::Arc::new);
if self.bytes > MAX_DEFINITION_BYTES {
self.parsed.clear();
self.bytes = 0;
}
self.bytes += std::mem::size_of::<(
(std::sync::Arc<std::path::Path>, usize),
Option<std::sync::Arc<MacroDef>>,
)>();
self.bytes += std::mem::size_of::<MacroDef>();
if let Some(definition) = &definition {
self.bytes += definition.name.len();
}
self.parsed.insert(key, definition.clone());
definition
}
pub fn forget(&mut self, path: &std::path::Path) {
let before = self.parsed.len();
self.parsed.retain(|(held, _), _| held.as_ref() != path);
if self.parsed.len() != before {
self.bytes = self.parsed.len() * 96;
}
}
pub fn len(&self) -> usize {
self.parsed.len()
}
pub fn is_empty(&self) -> bool {
self.parsed.is_empty()
}
fn get_or_read(
&mut self,
path: &std::path::Path,
source: &str,
fact: &MacroFact,
) -> Option<std::sync::Arc<MacroDef>> {
self.definition_of(path, source, fact)
}
}
fn read_back_a_define(source: &str, fact: &MacroFact) -> Option<MacroDef> {
let raw = source.get(fact.range.start_offset..)?;
let rest = match raw.strip_prefix('#') {
Some(after_the_hash) => {
let after_the_hash = after_the_hash.trim_start();
match after_the_hash.strip_prefix("define") {
Some(after_the_keyword) => after_the_keyword.trim_start(),
None => raw,
}
}
None => raw,
};
let bytes = rest.as_bytes();
let mut logical = String::new();
let mut index = 0;
while index < bytes.len() {
match bytes[index] {
b'\\' if bytes.get(index + 1) == Some(&b'\n') => index += 2,
b'\\'
if bytes.get(index + 1) == Some(&b'\r') && bytes.get(index + 2) == Some(&b'\n') =>
{
index += 3;
}
b'\n' => break,
_ => {
let character = rest[index..].chars().next()?;
logical.push(character);
index += character.len_utf8();
}
}
}
let line = format!("#define {logical}");
let mut errors = Vec::new();
let mut lexer =
cpp_parser::CppLexer::new(&line, cpp_parser::LexerConfig::default(), &mut errors);
let tokens: Vec<crate::token::Token> = lexer
.tokenize()
.into_iter()
.map(|token| {
let text = &line[token.range.start_offset..token.range.end_offset()];
crate::token::Token::new(token.kind, text, token.range)
})
.collect();
let mut significant = 0usize;
let mut from = 0usize;
for (index, token) in tokens.iter().enumerate() {
if crate::token::is_trivia(token.kind) {
continue;
}
significant += 1;
from = index + 1;
if significant == 2 {
break;
}
}
crate::macros::parse_define(tokens.get(from..)?, fact.range)
}
#[derive(Clone, Copy)]
struct UnitMacros<'a> {
seed: &'a Marked,
state: &'a UnitState,
here: Option<(&'a std::path::Path, usize)>,
}
impl crate::condition::MacroValues for UnitMacros<'_> {
fn lookup(&self, name: &str) -> crate::condition::Lookup<'_> {
if let Some(wanted) = crate::probes::lookup_name()
&& wanted == name
{
let from_state = self.state.definitions.get(name).map(|binding| {
let params = match &binding.definition.params {
None => "object-like".to_string(),
Some(list) => format!(
"fn-like({:?})",
list.iter()
.map(|held| held.name.as_ref())
.collect::<Vec<_>>()
),
};
let body: Vec<&str> = binding
.definition
.body
.significant()
.map(|token| token.text())
.collect();
format!(
"state(defined_in={} at={} {params} body={:?})",
binding.defined_in.display(),
binding.defined_at,
body.join(" ")
)
});
let from_seed = match self.seed.lookup(name) {
crate::condition::Lookup::Defined(_) => "seed:Defined".to_string(),
crate::condition::Lookup::DefinedWithoutAValue => {
"seed:DefinedWithoutAValue".to_string()
}
crate::condition::Lookup::Undefined => "seed:Undefined".to_string(),
crate::condition::Lookup::Unanswered => "seed:Unanswered".to_string(),
};
println!(
"cppls-lookup: {name} state={} {from_seed}",
from_state.as_deref().unwrap_or("none")
);
}
if let Some(binding) = self.state.definitions.get(name) {
let written_below = self
.here
.is_some_and(|(file, at)| &*binding.defined_in == file && binding.defined_at >= at);
if !written_below {
return crate::condition::Lookup::Defined(&binding.definition);
}
}
match self.seed.lookup(name) {
crate::condition::Lookup::Unanswered => crate::condition::Lookup::Undefined,
other => other,
}
}
fn builtin_operator(&self, name: &str, operand: &str) -> Option<crate::condition::Value> {
self.seed.builtin_operator(name, operand)
}
}
pub fn macros_from_the_closure_with_bodies<'a>(
summary: &'a FileSummary,
look_up: impl FnMut(&std::path::Path) -> Option<(&'a FileSummary, &'a str)>,
seed: &Marked,
definitions: &mut MacroDefinitions,
) -> ClosureEvidence {
{
let cache = crate::index::walk_cache::WalkCache::new();
walk_the_translation_unit(summary, None, None, look_up, seed, definitions, &cache)
}
}
pub fn macros_in_force_before_the_include<'a>(
includer: &'a FileSummary,
before: usize,
look_up: impl FnMut(&std::path::Path) -> Option<(&'a FileSummary, &'a str)>,
seed: &Marked,
definitions: &mut MacroDefinitions,
) -> ClosureEvidence {
{
let cache = crate::index::walk_cache::WalkCache::new();
walk_the_translation_unit(
includer,
Some(before),
Some(0),
look_up,
seed,
definitions,
&cache,
)
}
}
fn walk_the_translation_unit<'a>(
summary: &'a FileSummary,
only_before: Option<usize>,
all_from: Option<usize>,
mut look_up: impl FnMut(&std::path::Path) -> Option<(&'a FileSummary, &'a str)>,
seed: &Marked,
definitions_of: &mut MacroDefinitions,
cache: &crate::index::walk_cache::WalkCache,
) -> ClosureEvidence {
let mut walked = Walked::default();
let mut unit = UnitState {
definitions: std::collections::HashMap::new(),
generation: 0,
};
for include in &summary.includes {
if only_before.is_some_and(|limit| include.range.start_offset >= limit) {
break;
}
let Some(root) = include.resolved.as_deref() else {
continue;
};
let from_offset = all_from.unwrap_or(include.range.start_offset + include.range.length);
let mut seen: std::collections::HashSet<&std::path::Path> =
std::collections::HashSet::new();
walk_one_file(
root,
from_offset,
None,
0,
0,
&mut seen,
&mut look_up,
seed,
definitions_of,
&mut unit,
&mut walked,
false,
cache,
);
}
walked.into_evidence()
}
pub struct TranslationUnit {
pub(crate) events: Vec<TuEvent>,
pub(crate) frames: Vec<TuFrame>,
pub(crate) by_name: std::collections::HashMap<std::sync::Arc<str>, Vec<u32>>,
definitions_cache: std::sync::OnceLock<std::sync::Arc<UnitDefinitions>>,
pub(crate) paths: Vec<Vec<(u32, usize)>>,
entered: std::collections::HashMap<String, u32>,
pub conditional_facts: usize,
pub facts_in_force: usize,
pub(crate) dead_macros: std::collections::HashMap<std::path::PathBuf, Vec<usize>>,
}
#[derive(Clone, Debug)]
pub(crate) struct TuEvent {
pub(crate) name: std::sync::Arc<str>,
pub(crate) function_like: Option<bool>,
pub(crate) body: Option<cpp_parser::MacroBody>,
pub(crate) body_text: Option<std::sync::Arc<str>>,
pub(crate) parameters: Option<std::sync::Arc<str>>,
pub(crate) body_range: Option<cpp_parser::SourceRange>,
pub(crate) frame: u32,
pub(crate) at: usize,
pub(crate) unconditional: bool,
}
#[derive(Clone, Debug)]
pub(crate) struct TuFrame {
pub(crate) file: std::path::PathBuf,
pub(crate) parent: Option<u32>,
pub(crate) from_in_parent: usize,
pub(crate) entry_seq: u32,
pub(crate) tout: u32,
pub(crate) visit_once: bool,
}
#[derive(Default)]
struct TimelineBuilder {
events: Vec<TuEvent>,
frames: Vec<TuFrame>,
entered: std::collections::HashMap<String, u32>,
}
impl TimelineBuilder {
fn enter(
&mut self,
file: &std::path::Path,
parent: Option<u32>,
from_in_parent: usize,
visit_once: bool,
) -> u32 {
let id = self.frames.len() as u32;
self.frames.push(TuFrame {
file: file.to_path_buf(),
parent,
from_in_parent,
visit_once,
entry_seq: self.events.len() as u32,
tout: u32::MAX,
});
self.entered.entry(frame_key(file)).or_insert(id);
id
}
fn leave(&mut self, frame: u32) {
self.frames[frame as usize].tout = self.frames.len() as u32;
}
fn record(&mut self, frame: u32, fact: &MacroFact, source: &str, unconditional: bool) {
let body_text = fact
.body_range
.and_then(|range| source.get(range.start_offset..range.start_offset + range.length))
.map(std::sync::Arc::from);
let parameters = fact
.body_range
.and_then(|range| parameters_before(source, range.start_offset))
.map(std::sync::Arc::from);
self.events.push(TuEvent {
name: std::sync::Arc::from(&*fact.name),
function_like: fact.kind.is_definition().then_some(fact.function_like),
body: fact.kind.is_definition().then_some(fact.body),
body_text,
parameters,
body_range: fact.body_range,
frame,
at: fact.range.start_offset,
unconditional,
});
}
}
impl TranslationUnit {
pub fn heap_bytes(&self) -> usize {
let mut bytes = std::mem::size_of::<TranslationUnit>();
for frame in &self.frames {
bytes += std::mem::size_of::<TuFrame>() + frame.file.as_os_str().len();
}
for event in &self.events {
bytes += std::mem::size_of::<TuEvent>()
+ event.name.len()
+ event.body_text.as_ref().map_or(0, |text| text.len())
+ event.parameters.as_ref().map_or(0, |text| text.len());
}
for key in self.entered.keys() {
bytes += key.len() + std::mem::size_of::<u32>();
}
if let Some(definitions) = self.definitions_cache.get() {
bytes += definitions.heap_bytes();
}
bytes
}
pub fn walk<'a>(
root: &'a FileSummary,
mut look_up: impl FnMut(&std::path::Path) -> Option<(&'a FileSummary, &'a str)>,
seed: &Marked,
definitions_of: &mut MacroDefinitions,
share: bool,
cache: &crate::index::walk_cache::WalkCache,
) -> Self {
let mut walked = Walked {
timeline: Some(TimelineBuilder::default()),
..Walked::default()
};
let mut unit = UnitState {
definitions: std::collections::HashMap::new(),
generation: 0,
};
let mut seen: std::collections::HashSet<&std::path::Path> =
std::collections::HashSet::new();
let _root_key = walk_one_file(
&root.path,
0,
None,
0,
0,
&mut seen,
&mut look_up,
seed,
definitions_of,
&mut unit,
&mut walked,
share,
cache,
);
let timeline = walked.timeline.take().expect("just built");
let mut built = TranslationUnit::from_parts(
timeline.events,
timeline.frames,
walked.conditional_facts,
walked.facts_in_force,
);
built.dead_macros = walked.dead_macros;
built
}
pub(crate) fn from_parts(
events: Vec<TuEvent>,
frames: Vec<TuFrame>,
conditional_facts: usize,
facts_in_force: usize,
) -> Self {
let mut entered: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
for (index, frame) in frames.iter().enumerate() {
entered
.entry(frame_key(&frame.file))
.or_insert(index as u32);
}
let mut by_name: std::collections::HashMap<std::sync::Arc<str>, Vec<u32>> =
std::collections::HashMap::new();
for (index, event) in events.iter().enumerate() {
by_name
.entry(std::sync::Arc::clone(&event.name))
.or_default()
.push(index as u32);
}
let mut paths: Vec<Vec<(u32, usize)>> = Vec::with_capacity(frames.len());
for frame in &frames {
let mut path = Vec::new();
let mut offset = frame.from_in_parent;
let mut parent = frame.parent;
while let Some(ancestor) = parent {
path.push((ancestor, offset));
let reached = &frames[ancestor as usize];
offset = reached.from_in_parent;
parent = reached.parent;
}
paths.push(path);
}
TranslationUnit {
events,
frames,
by_name,
paths,
entered,
conditional_facts,
facts_in_force,
dead_macros: std::collections::HashMap::new(),
definitions_cache: std::sync::OnceLock::new(),
}
}
pub fn len(&self) -> usize {
self.events.len()
}
pub fn definitions_cached(&self) -> std::sync::Arc<UnitDefinitions> {
self.definitions_cache
.get_or_init(|| std::sync::Arc::new(self.definitions()))
.clone()
}
pub fn definitions(&self) -> UnitDefinitions {
let mut by_event: Vec<Option<std::sync::Arc<crate::macros::MacroDef>>> =
vec![None; self.events.len()];
let mut counted = UnitDefinitions::default();
for (index, event) in self.events.iter().enumerate() {
let Some(body) = event.body_text.as_ref() else {
if event.unconditional && event.function_like.is_some() {
counted.without_a_body += 1;
}
continue;
};
if !event.unconditional {
match event.function_like {
Some(false) => {}
Some(true) if event.parameters.is_some() => {}
_ => {
counted.in_force_without_a_parameter_list += 1;
continue;
}
}
} else {
match (event.function_like, event.body) {
(Some(true), _) if event.parameters.is_none() => {
counted.function_like_without_parameters += 1;
continue;
}
(Some(_), Some(_)) => {}
_ => continue,
}
}
match definition_written_at(event, body) {
Some(definition) => by_event[index] = Some(std::sync::Arc::new(definition)),
None => counted.unreadable += 1,
}
}
UnitDefinitions {
by_event,
..counted
}
}
pub fn frame_file(&self, frame: u32) -> Option<&std::path::Path> {
self.frames
.get(frame as usize)
.map(|frame| frame.file.as_path())
}
pub fn bodies(&self) -> (usize, usize) {
let with_a_body = self
.events
.iter()
.filter(|event| {
event
.body_text
.as_deref()
.is_some_and(|text| !text.trim().is_empty())
})
.count();
let in_force = self
.events
.iter()
.filter(|event| !event.unconditional)
.count();
(with_a_body, in_force)
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub fn files(&self) -> impl Iterator<Item = &std::path::Path> {
self.frames.iter().map(|frame| frame.file.as_path())
}
pub fn facts_of<'unit>(
&'unit self,
path: &'unit std::path::Path,
) -> impl Iterator<Item = (&'unit str, usize)> {
let frame = self
.frames
.iter()
.position(|frame| frame.file == path)
.map(|index| index as u32);
self.events
.iter()
.filter(move |event| Some(event.frame) == frame)
.map(|event| (&*event.name, event.at))
}
pub fn environment_of(&self, path: &std::path::Path) -> Option<MacroView<'_>> {
let &frame = self.entered.get(&frame_key(path))?;
Some(self.environment_at(frame))
}
pub fn root_environment(&self) -> MacroView<'_> {
self.environment_at(0)
}
fn environment_at(&self, frame: u32) -> MacroView<'_> {
MacroView { unit: self, frame }
}
fn offset_in(&self, frame: u32, consumer: u32) -> usize {
self.paths[frame as usize]
.iter()
.find(|(ancestor, _)| *ancestor == consumer)
.map(|(_, offset)| *offset)
.unwrap_or(0)
}
pub fn cook_the_unit(
&self,
sources: &dyn crate::preprocess::macros::UnitSources,
definitions: &UnitDefinitions,
seed: Option<&crate::macros::MacroTable>,
use_in_force_bodies: bool,
search: Option<&dyn crate::preprocess::cooked::HeaderSearch>,
) -> RenderedUnit {
let mut out = RenderedUnit {
files: self.frames.iter().map(|frame| frame.file.clone()).collect(),
file_lengths: self
.frames
.iter()
.map(|frame| {
sources
.source_of(&frame.file)
.map(|text| text.len())
.unwrap_or_default()
})
.collect(),
..RenderedUnit::default()
};
let cook = UnitCook {
unit: self,
sources,
definitions,
seed,
use_in_force_bodies,
search,
children: {
let mut children: Vec<Vec<u32>> = vec![Vec::new(); self.frames.len()];
for (index, frame) in self.frames.iter().enumerate() {
if let Some(parent) = frame.parent {
children[parent as usize].push(index as u32);
}
}
children
},
};
if !self.frames.is_empty() {
cook.stitch(0, &mut out);
}
out
}
}
struct UnitCook<'unit> {
unit: &'unit TranslationUnit,
sources: &'unit dyn crate::preprocess::macros::UnitSources,
definitions: &'unit UnitDefinitions,
seed: Option<&'unit crate::macros::MacroTable>,
use_in_force_bodies: bool,
search: Option<&'unit dyn crate::preprocess::cooked::HeaderSearch>,
children: Vec<Vec<u32>>,
}
impl UnitCook<'_> {
fn stitch(&self, frame: u32, out: &mut RenderedUnit) {
let included = &self.children[frame as usize];
let Some(text) = self
.sources
.source_of(&self.unit.frames[frame as usize].file)
else {
out.missing += 1;
self.stitch_included(included, 0, out);
return;
};
let (tokens, _) = cpp_parser::lex(text, &cpp_parser::LexerConfig::default());
let cook = crate::preprocess::cooked::cook_with_search(
text,
&tokens,
&crate::preprocess::cooked::FileMacros::new(
self.unit.environment_at(frame),
self.definitions,
self.seed,
self.use_in_force_bodies,
),
self.search,
self.unit.frames[frame as usize]
.file
.parent()
.unwrap_or_else(|| Path::new(".")),
);
for (kind, message, at) in &cook.messages {
out.messages.push(UnitMessage {
file: self.unit.frames[frame as usize].file.clone(),
fatal: matches!(kind, crate::DirectiveKind::Error),
message: message.clone(),
at: *at,
});
}
let mut next = 0usize;
let mut depth = 0i64;
for token in &cook.tokens {
match token.text() {
"{" => depth += 1,
"}" => depth -= 1,
_ => {}
}
}
if depth != 0 {
out.unbalanced
.push(self.unit.frames[frame as usize].file.clone());
}
if self.unit.frames[frame as usize].visit_once && cook.tokens.is_empty() {
let here = cpp_parser::SourceRange::new(0, 0);
out.break_line_before_next();
for spelling in ["#", "pragma", "once"] {
out.push(spelling, frame, here);
}
out.break_line_before_next();
}
let mut lines = cook.pragma_lines.iter().peekable();
for (index, token) in cook.tokens.iter().enumerate() {
let at = token.diagnostic_range();
while next < included.len()
&& self.unit.frames[included[next] as usize].from_in_parent <= at.start_offset
{
self.stitch(included[next], out);
next += 1;
}
while lines.next_if(|line| line.end <= index).is_some() {}
if lines.peek().is_some_and(|line| line.start == index) {
out.break_line_before_next();
}
out.push(token.text(), frame, at);
if lines.peek().is_some_and(|line| line.end == index + 1) {
out.break_line_before_next();
}
}
self.stitch_included(included, next, out);
}
fn stitch_included(&self, included: &[u32], from: usize, out: &mut RenderedUnit) {
for &child in &included[from..] {
self.stitch(child, out);
}
}
}
#[derive(Default)]
pub struct UnitDefinitions {
by_event: Vec<Option<std::sync::Arc<crate::macros::MacroDef>>>,
pub function_like_without_parameters: usize,
pub without_a_body: usize,
pub unreadable: usize,
pub in_force_without_a_parameter_list: usize,
}
impl UnitDefinitions {
pub fn heap_bytes(&self) -> usize {
let mut bytes = std::mem::size_of::<UnitDefinitions>()
+ self.by_event.capacity()
* std::mem::size_of::<Option<std::sync::Arc<crate::macros::MacroDef>>>();
for definition in self.by_event.iter().flatten() {
bytes += std::mem::size_of::<crate::macros::MacroDef>() + definition.name.len();
if let Some(params) = &definition.params {
bytes += params.len() * std::mem::size_of::<crate::preprocess::macros::Parameter>();
}
}
bytes
}
pub(crate) fn of(&self, index: u32) -> Option<&std::sync::Arc<crate::macros::MacroDef>> {
self.by_event.get(index as usize)?.as_ref()
}
pub fn len(&self) -> usize {
self.by_event.iter().filter(|it| it.is_some()).count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[derive(Clone, Copy)]
pub struct MacroView<'unit> {
unit: &'unit TranslationUnit,
frame: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MacroAt {
pub defined: bool,
pub body: Option<cpp_parser::MacroBody>,
pub body_text: Option<String>,
pub function_like: bool,
pub written_in: Option<std::path::PathBuf>,
pub written_at_line: Option<usize>,
}
impl TranslationUnit {
pub fn macro_at(&self, file: &std::path::Path, name: &str, offset: usize) -> Option<MacroAt> {
let frame = *self.entered.get(&frame_key(file))?;
let view = self.environment_at(frame);
let own = self
.by_name
.get(name)
.into_iter()
.flatten()
.rev()
.map(|index| &self.events[*index as usize])
.find(|event| view.applies_here(frame, offset, event));
let inherited = view.the_binding(name);
let event: &TuEvent = match (own, inherited) {
(Some(own), None) => own,
(None, Some((at, event))) if at <= offset => event,
(None, Some(_)) => {
return Some(MacroAt {
defined: false,
body: None,
body_text: None,
function_like: false,
written_in: None,
written_at_line: None,
});
}
(Some(own), Some(_)) => own,
(None, None) => {
if !self.events.iter().any(|event| event.frame == frame) {
return None;
}
return Some(MacroAt {
defined: false,
body: None,
body_text: None,
function_like: false,
written_in: None,
written_at_line: None,
});
}
};
let defined = event.body.is_some() || event.function_like.is_some();
Some(MacroAt {
defined,
body: event.body,
body_text: event.body_text.as_ref().map(|text| text.to_string()),
function_like: event.function_like.is_some_and(|held| held),
written_in: Some(self.frames[event.frame as usize].file.clone()),
written_at_line: None,
})
}
}
impl<'unit> MacroView<'unit> {
pub fn file(&self) -> &'unit std::path::Path {
&self.unit.frames[self.frame as usize].file
}
fn applies_here(&self, frame: u32, offset: usize, event: &TuEvent) -> bool {
let held = &self.unit.frames[frame as usize];
if event.frame == frame {
return event.at <= offset;
}
if event.frame > frame && event.frame < held.tout {
return self.unit.offset_in(event.frame, frame) <= offset;
}
false
}
fn offset_of(&self, index: usize, event: &TuEvent) -> Option<usize> {
let frame = &self.unit.frames[self.frame as usize];
if event.frame == self.frame {
None
} else if event.frame > self.frame && event.frame < frame.tout {
Some(self.unit.offset_in(event.frame, self.frame))
} else if (index as u32) < frame.entry_seq {
Some(0)
} else {
None
}
}
fn last_visible(
&self,
indices: &[u32],
wanted: impl Fn(&TuEvent) -> bool,
) -> Option<(usize, u32)> {
indices.iter().rev().find_map(|&index| {
let event = &self.unit.events[index as usize];
if !wanted(event) {
return None;
}
self.offset_of(index as usize, event).map(|at| (at, index))
})
}
fn last_visible_of(
&self,
name: &str,
wanted: impl Fn(&TuEvent) -> bool,
) -> Option<(usize, u32)> {
self.last_visible(self.unit.by_name.get(name)?, wanted)
}
fn the_binding(&self, name: &str) -> Option<(usize, &'unit TuEvent)> {
let (at, index) =
self.last_visible_of(name, |event| event.unconditional || event.body.is_some())?;
Some((at, &self.unit.events[index as usize]))
}
fn the_body_in_force(&self, name: &str) -> Option<&'unit TuEvent> {
let (_, index) = self.last_visible_of(name, |event| event.body_text.is_some())?;
Some(&self.unit.events[index as usize])
}
pub(crate) fn visible_binding(&self, name: &str) -> Option<(usize, u32)> {
self.last_visible_of(name, |event| event.unconditional || event.body.is_some())
}
pub(crate) fn visible_body_in_force(&self, name: &str) -> Option<u32> {
self.last_visible_of(name, |event| {
!event.unconditional && event.body_text.is_some()
})
.map(|(_, index)| index)
}
}
impl cpp_parser::MacroFacts for MacroView<'_> {
fn kind_of(&self, name: &str, offset: usize) -> Option<cpp_parser::SymbolKind> {
let (at, event) = self.the_binding(name)?;
if at > offset {
return None;
}
match (event.function_like, event.body) {
(Some(function_like), Some(body)) => Some(cpp_parser::SymbolKind::Macro {
function_like,
body,
}),
_ => None,
}
}
fn body_text_of(&self, name: &str, offset: usize) -> Option<&str> {
let (at, event) = self.the_binding(name)?;
match (at <= offset, event.function_like, event.body) {
(true, Some(_), Some(_)) => event.body_text.as_deref(),
_ => None,
}
}
fn parameters_of(&self, name: &str, offset: usize) -> Option<&std::sync::Arc<str>> {
let (at, event) = self.the_binding(name)?;
match (at <= offset, event.function_like, event.body) {
(true, Some(_), Some(_)) => event.parameters.as_ref(),
_ => None,
}
}
fn body_text_in_force(&self, name: &str) -> Option<&str> {
self.the_body_in_force(name)
.and_then(|event| event.body_text.as_deref())
}
fn parameters_in_force(&self, name: &str) -> Option<&str> {
self.the_body_in_force(name)
.and_then(|event| event.parameters.as_deref())
}
fn body_in_force_is_object_like(&self, name: &str) -> bool {
matches!(
self.the_body_in_force(name)
.map(|event| event.function_like),
Some(Some(false))
)
}
fn knows(&self, name: &str) -> bool {
self.the_binding(name).is_some()
}
fn is_empty(&self) -> bool {
self.unit.by_name.values().all(|indices| {
self.last_visible(indices, |event| event.unconditional)
.is_none()
&& self
.last_visible(indices, |event| {
!event.unconditional && event.body_text.is_some()
})
.is_none()
})
}
fn len(&self) -> usize {
self.unit
.by_name
.values()
.filter(|indices| {
self.last_visible(indices, |event| event.unconditional)
.is_some()
})
.count()
}
fn for_each_definition<'s>(&'s self, visit: &mut dyn FnMut(cpp_parser::DefinitionFacts<'s>)) {
for (name, indices) in &self.unit.by_name {
let Some((at, index)) = self.last_visible(indices, |event| event.unconditional) else {
continue;
};
let event = &self.unit.events[index as usize];
let (Some(function_like), Some(_)) = (event.function_like, event.body) else {
continue;
};
visit(cpp_parser::DefinitionFacts {
name,
at,
function_like,
parameters: event.parameters.as_ref(),
body_text: event.body_text.as_ref(),
});
}
}
fn for_each_body_in_force<'s>(&'s self, visit: &mut dyn FnMut(cpp_parser::BodyFacts<'s>)) {
for (name, indices) in &self.unit.by_name {
let Some((_, index)) = self.last_visible(indices, |event| {
!event.unconditional && event.body_text.is_some()
}) else {
continue;
};
let event = &self.unit.events[index as usize];
let Some(body) = event.body_text.as_ref() else {
continue;
};
visit(cpp_parser::BodyFacts {
name,
function_like: event.function_like,
parameters: event.parameters.as_ref(),
body,
});
}
}
}
#[derive(Debug, Clone, Default)]
pub struct RenderedUnit {
pub text: String,
pub dead_macros: std::collections::HashMap<std::path::PathBuf, Vec<usize>>,
pub messages: Vec<UnitMessage>,
pub spans: Vec<UnitSpan>,
pub files: Vec<std::path::PathBuf>,
pub file_lengths: Vec<usize>,
pub braces: i64,
pub missing: usize,
pub unbalanced: Vec<std::path::PathBuf>,
pub(crate) pending_break: bool,
pub(crate) previous: Option<(u32, cpp_parser::SourceRange)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnitMessage {
pub file: std::path::PathBuf,
pub fatal: bool,
pub message: String,
pub at: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnitSpan {
pub cooked: cpp_parser::SourceRange,
pub file: u32,
pub written: cpp_parser::SourceRange,
}
impl RenderedUnit {
pub fn file_boundaries(&self) -> Vec<usize> {
let mut boundaries = Vec::new();
let mut seen = vec![false; self.files.len()];
for span in &self.spans {
if let Some(slot) = seen.get_mut(span.file as usize)
&& !*slot
{
*slot = true;
if span.cooked.start_offset != 0 {
boundaries.push(span.cooked.start_offset);
}
}
}
boundaries
}
pub fn written_at(&self, cooked_offset: usize) -> Option<(u32, cpp_parser::SourceRange)> {
let index = self
.spans
.partition_point(|span| span.cooked.end_offset() <= cooked_offset);
self.spans.get(index).map(|span| (span.file, span.written))
}
pub fn file_at(&self, cooked_offset: usize) -> Option<&std::path::Path> {
let (file, _) = self.written_at(cooked_offset)?;
self.file_of(file)
}
pub fn file_standing_at(&self, cooked_offset: usize) -> Option<u32> {
let index = self
.spans
.partition_point(|span| span.cooked.end_offset() <= cooked_offset);
self.spans.get(index).map(|span| span.file)
}
pub fn written_span(
&self,
range: cpp_parser::SourceRange,
) -> Option<(u32, cpp_parser::SourceRange)> {
let (file, first) = self.written_at(range.start_offset)?;
let (last_file, last) = self.written_at(range.end_offset().saturating_sub(1))?;
if last_file != file || last.end_offset() <= first.start_offset {
return Some((file, first));
}
Some((
file,
cpp_parser::SourceRange {
start_offset: first.start_offset,
length: last.end_offset() - first.start_offset,
},
))
}
pub fn span_lands_in(&self, file: u32, written: cpp_parser::SourceRange) -> bool {
match self.file_lengths.get(file as usize) {
Some(&length) => written.end_offset() <= length,
None => false,
}
}
pub fn file_of(&self, file: u32) -> Option<&std::path::Path> {
self.files
.get(file as usize)
.map(std::path::PathBuf::as_path)
}
pub fn len(&self) -> usize {
self.spans.len()
}
pub fn is_empty(&self) -> bool {
self.spans.is_empty()
}
pub fn files_with_tokens(&self) -> usize {
let mut seen = vec![false; self.files.len()];
for span in &self.spans {
if let Some(slot) = seen.get_mut(span.file as usize) {
*slot = true;
}
}
seen.into_iter().filter(|it| *it).count()
}
pub(crate) fn push(&mut self, text: &str, file: u32, written: cpp_parser::SourceRange) {
if !self.text.is_empty() {
let touching = self.previous.is_some_and(|(previous_file, previous)| {
previous_file == file && previous.end_offset() == written.start_offset
});
if self.pending_break {
self.text.push('\n');
} else if !touching {
self.text.push(' ');
}
}
self.previous = Some((file, written));
self.pending_break = false;
match text {
"{" => self.braces += 1,
"}" => self.braces -= 1,
_ => {}
}
let start = self.text.len();
self.text.push_str(text);
self.spans.push(UnitSpan {
cooked: cpp_parser::SourceRange::new(start, self.text.len() - start),
file,
written,
});
}
pub(crate) fn break_line_before_next(&mut self) {
self.pending_break = true;
}
pub fn without(&self, left_out: &std::collections::BTreeSet<u32>) -> RenderedUnit {
let mut out = self.empty_like();
let mut bytes = self.text.as_bytes().to_vec();
for span in &self.spans {
if !left_out.contains(&span.file) {
continue;
}
for byte in &mut bytes[span.cooked.start_offset..span.cooked.end_offset()] {
*byte = b' ';
}
}
out.text = String::from_utf8(bytes).expect("only spaces replaced bytes of a UTF-8 stream");
out.spans = self.spans.clone();
out
}
pub fn only(&self, file: u32) -> RenderedUnit {
let mut out = self.empty_like();
for span in &self.spans {
if span.file == file {
if span.cooked.start_offset > 0
&& self.text.as_bytes()[span.cooked.start_offset - 1] == b'\n'
{
out.break_line_before_next();
}
out.push(
&self.text[span.cooked.start_offset..span.cooked.end_offset()],
span.file,
span.written,
);
}
}
out
}
fn empty_like(&self) -> RenderedUnit {
RenderedUnit {
files: self.files.clone(),
file_lengths: self.file_lengths.clone(),
missing: self.missing,
unbalanced: self.unbalanced.clone(),
..RenderedUnit::default()
}
}
}
#[derive(Default)]
struct Walked<'a> {
entries: Vec<(usize, &'a MacroFact, &'a str)>,
changes: Vec<crate::index::walk_cache::StateChange>,
conditional_by_frame: Vec<usize>,
spliced: std::collections::HashSet<std::path::PathBuf>,
conditional_bodies: std::collections::BTreeMap<Box<str>, ConditionalBodyValue>,
conditional_facts: usize,
facts_in_force: usize,
dead_macros: std::collections::HashMap<std::path::PathBuf, Vec<usize>>,
includes_skipped: usize,
timeline: Option<TimelineBuilder>,
}
impl<'a> Walked<'a> {
fn into_evidence(self) -> ClosureEvidence {
let mut by_name: std::collections::BTreeMap<&str, (usize, &MacroFact, &str)> =
std::collections::BTreeMap::new();
for (from_offset, fact, source) in self.entries {
by_name.insert(&fact.name, (from_offset, fact, source));
}
let macros = by_name
.into_values()
.map(|(from_offset, fact, source)| {
let body_text = fact.body_range.and_then(|range| {
source.get(range.start_offset..range.start_offset + range.length)
});
if fact.kind.is_definition() {
cpp_parser::IncludedMacro::defined_with_body_and_parameters(
from_offset,
&fact.name,
fact.function_like,
fact.body,
body_text,
fact.body_range
.and_then(|range| parameters_before(source, range.start_offset)),
)
} else {
cpp_parser::IncludedMacro::undefined_at(from_offset, &fact.name)
}
})
.collect();
ClosureEvidence {
macros,
conditional_bodies: self
.conditional_bodies
.into_iter()
.map(|(name, (function_like, parameters, body))| {
(name, function_like, parameters, body)
})
.collect(),
conditional_facts: self.conditional_facts,
facts_in_force: self.facts_in_force,
}
}
}
#[allow(clippy::too_many_arguments)]
struct Bases {
key: u64,
events: usize,
changes: usize,
dead: usize,
}
fn guard_name_of(file: &FileSummary, region: u32) -> Option<&str> {
let conditional = file.guards.conditionals.get(region as usize)?;
let first = conditional.branches.first()?;
if !matches!(
first.kind,
crate::DirectiveKind::Ifdef | crate::DirectiveKind::Ifndef
) {
return None;
}
let name = first.condition.as_deref()?.trim();
(!name.is_empty() && !name.contains(char::is_whitespace)).then_some(name)
}
const MAX_INCLUDE_DEPTH: usize = 200;
fn walk_one_file<'a>(
path: &'a std::path::Path,
from_offset: usize,
parent: Option<u32>,
from_in_parent: usize,
depth: usize,
seen: &mut std::collections::HashSet<&'a std::path::Path>,
look_up: &mut impl FnMut(&std::path::Path) -> Option<(&'a FileSummary, &'a str)>,
seed: &Marked,
definitions_of: &mut MacroDefinitions,
unit: &mut UnitState,
walked: &mut Walked<'a>,
share: bool,
cache: &crate::index::walk_cache::WalkCache,
) -> Option<u64> {
if walked.spliced.contains(path) {
if crate::probes::splice() {
eprintln!("leave early (already spliced): {}", path.display());
}
return None;
}
let already_read = !seen.insert(path);
if crate::probes::splice() {
eprintln!(
"enter: {} | already seen {}, depth {depth}, spliced {}, timeline {}",
path.display(),
already_read,
walked.spliced.contains(path),
walked.timeline.is_some(),
);
}
if depth >= MAX_INCLUDE_DEPTH {
walked.includes_skipped += 1;
return None;
}
let Some((file, source)) = look_up(path) else {
return None;
};
if already_read && file.guards.visit_once {
return None;
}
if already_read
&& let Some(own) = file.guards.own_guard
&& let Some(name) = guard_name_of(file, own)
&& unit.definitions.contains_key(name)
{
return None;
}
let defined_in_force = |name: &str| unit.definitions.contains_key(name);
crate::index::walk_census::entered(path, source, defined_in_force);
let sharing = (share && walked.timeline.is_some()).then(|| {
crate::index::walk_cache::key(
path,
crate::index::walk_census::hash(source.as_bytes()),
crate::index::walk_census::projection_digest(path, source, defined_in_force),
)
});
if let Some(key) = sharing
&& cache.lookup(key).is_some()
&& !walked.spliced.contains(path)
{
crate::index::walk_census::a_splice();
if splice_a_contribution(
key,
from_offset,
parent,
from_in_parent,
seen,
look_up,
unit,
walked,
0,
cache,
) {
return Some(key);
}
}
let bases = sharing.map(|key| Bases {
key,
events: walked
.timeline
.as_ref()
.map_or(0, |timeline| timeline.events.len()),
changes: walked.changes.len(),
dead: walked.dead_macros.get(path).map_or(0, Vec::len),
});
let mut edges: Vec<(usize, u64)> = Vec::new();
let frame = walked
.timeline
.as_mut()
.map(|timeline| timeline.enter(path, parent, from_in_parent, file.guards.visit_once));
if let Some(frame) = frame
&& walked.conditional_by_frame.len() <= frame as usize
{
walked.conditional_by_frame.resize(frame as usize + 1, 0);
}
let mut decided: std::collections::HashMap<(u32, u32), bool> = std::collections::HashMap::new();
let mut decided_at = unit.generation;
let mut macros = file.macros.iter().peekable();
let mut includes = file.includes.iter().peekable();
loop {
let next_is_a_macro = match (macros.peek(), includes.peek()) {
(Some(fact), Some(include)) => fact.range.start_offset <= include.range.start_offset,
(Some(_), None) => true,
(None, _) => false,
};
if next_is_a_macro {
let fact = macros.next().expect("peeked just above");
let in_force = if matches!(fact.guard, FactGuard::Unconditional) {
true
} else {
walked.conditional_facts += 1;
if let Some(at) = frame.map(|frame| frame as usize) {
if walked.conditional_by_frame.len() <= at {
walked.conditional_by_frame.resize(at + 1, 0);
}
walked.conditional_by_frame[at] += 1;
}
let branch = match fact.guard {
crate::summary::FactGuard::Region(region) => file
.guards
.conditionals
.get(region as usize)
.and_then(|conditional| conditional.branch_at(fact.range.start_offset))
.map(|branch| (region, branch as u32)),
crate::summary::FactGuard::Unconditional => None,
};
if unit.generation != decided_at {
decided.clear();
decided_at = unit.generation;
}
let taken = match branch.and_then(|key| decided.get(&key).copied()) {
Some(answer) => answer,
None => {
let answer = a_guard_is_in_force(file, fact, |at| UnitMacros {
seed,
state: unit,
here: Some((path, at)),
});
if let Some(key) = branch {
decided.insert(key, answer);
}
answer
}
};
if taken {
walked.facts_in_force += 1;
}
taken
};
if !in_force {
walked
.dead_macros
.entry(path.to_path_buf())
.or_default()
.push(fact.range.start_offset);
continue;
}
if fact.kind.is_definition() {
if let Some(definition) = definitions_of.get_or_read(path, source, fact) {
walked
.changes
.push(crate::index::walk_cache::StateChange::Defined {
name: Box::from(&*fact.name),
definition: definition.clone(),
file: path.to_path_buf(),
at: fact.range.start_offset,
});
unit.define(&fact.name, definition, path, fact.range.start_offset);
} else {
}
} else {
walked
.changes
.push(crate::index::walk_cache::StateChange::Undefined {
name: Box::from(&*fact.name),
file: path.to_path_buf(),
at: fact.range.start_offset,
});
unit.undefine(&fact.name);
}
if matches!(fact.guard, FactGuard::Unconditional) {
walked.entries.push((from_offset, fact, source));
} else if fact.kind.is_definition()
&& let Some(text) = fact.body_range.and_then(|range| {
source.get(range.start_offset..range.start_offset + range.length)
})
{
let parameters = fact
.body_range
.and_then(|range| parameters_before(source, range.start_offset))
.map(Box::from);
walked.conditional_bodies.insert(
Box::from(&*fact.name),
(fact.function_like, parameters, Box::from(text)),
);
}
if let (Some(frame), Some(timeline)) = (frame, walked.timeline.as_mut()) {
timeline.record(
frame,
fact,
source,
matches!(fact.guard, FactGuard::Unconditional),
);
}
continue;
}
let Some(include) = includes.next() else {
break;
};
let include_is_in_force = {
crate::index::environment::a_guard_holds(
file,
include.guard,
include.range.start_offset,
|at| UnitMacros {
seed,
state: unit,
here: Some((path, at)),
},
)
};
if !include_is_in_force {
walked.includes_skipped += 1;
continue;
}
let child_key = include.resolved.as_deref().and_then(|nested| {
walk_one_file(
nested,
include.range.start_offset + include.range.length,
frame,
include.range.start_offset + include.range.length,
depth + 1,
seen,
look_up,
seed,
definitions_of,
unit,
walked,
share,
cache,
)
});
if let Some(child) = child_key {
edges.push((include.range.start_offset + include.range.length, child));
}
}
if let (Some(frame), Some(timeline)) = (frame, walked.timeline.as_mut()) {
timeline.leave(frame);
}
let resolvable = !file
.includes
.iter()
.any(|include| include.resolved.is_none());
if let (true, Some(bases), Some(frame), Some(timeline)) =
(resolvable, bases, frame, walked.timeline.as_ref())
{
let mut contribution = crate::index::walk_cache::Contribution {
file: path.to_path_buf(),
visit_once: file.guards.visit_once,
edges,
..crate::index::walk_cache::Contribution::default()
};
for event in timeline.events[bases.events..]
.iter()
.filter(|event| event.frame == frame)
{
let mut carried = event.clone();
carried.frame = 0;
if !carried.unconditional
&& carried.function_like.is_some()
&& let Some(body) = carried.body_text.clone()
{
contribution
.bodies
.push(crate::index::walk_cache::ConditionalBody {
name: carried.name.to_string().into_boxed_str(),
function_like: carried.function_like.unwrap_or(false),
parameters: carried
.parameters
.as_ref()
.map(|p| p.to_string().into_boxed_str()),
body: body.to_string().into_boxed_str(),
});
}
contribution.facts_in_force += 1;
contribution.events.push(carried);
}
contribution.changes = walked.changes[bases.changes..]
.iter()
.filter(|change| change.file() == path)
.cloned()
.collect();
contribution.dead = walked
.dead_macros
.get(path)
.map(|decided| decided[bases.dead.min(decided.len())..].to_vec())
.unwrap_or_default();
contribution.conditional_facts = walked
.conditional_by_frame
.get(frame as usize)
.copied()
.unwrap_or(0);
crate::index::walk_census::a_fresh_walk();
cache.store(bases.key, contribution);
return Some(bases.key);
}
None
}
#[allow(clippy::too_many_arguments)]
fn splice_a_contribution<'a>(
key: u64,
from_offset: usize,
parent: Option<u32>,
from_in_parent: usize,
seen: &std::collections::HashSet<&'a std::path::Path>,
look_up: &mut impl FnMut(&std::path::Path) -> Option<(&'a FileSummary, &'a str)>,
unit: &mut UnitState,
walked: &mut Walked<'a>,
depth: usize,
cache: &crate::index::walk_cache::WalkCache,
) -> bool {
const MAX_SPLICE_DEPTH: usize = 256;
if depth > MAX_SPLICE_DEPTH {
return false;
}
let Some(contribution) = cache.lookup(key) else {
return false;
};
let Some(timeline) = walked.timeline.as_mut() else {
return false;
};
let frame = timeline.frames.len() as u32;
let event_base = timeline.events.len() as u32;
let (built, events) =
crate::index::walk_cache::rebased(&contribution, frame, event_base, parent, from_in_parent);
let file = built.file.clone();
timeline.entered.entry(frame_key(&file)).or_insert(frame);
timeline.frames.push(built);
timeline.events.extend(events);
for body in &contribution.bodies {
walked.conditional_bodies.insert(
body.name.clone(),
(
body.function_like,
body.parameters.clone(),
body.body.clone(),
),
);
}
walked
.dead_macros
.entry(file.clone())
.or_default()
.extend(contribution.dead.iter().copied());
walked.conditional_facts += contribution.conditional_facts;
walked.facts_in_force += contribution.facts_in_force;
let summary = look_up(&file);
let mut next_event = 0usize;
let mut next_change = 0usize;
let mut next_edge = 0usize;
loop {
let next = [
contribution.events.get(next_event).map(|event| event.at),
contribution
.changes
.get(next_change)
.map(|change| change.at()),
contribution.edges.get(next_edge).map(|(at, _)| *at),
]
.into_iter()
.flatten()
.min();
let Some(next) = next else {
break;
};
while contribution
.changes
.get(next_change)
.is_some_and(|change| change.at() == next)
{
match &contribution.changes[next_change] {
crate::index::walk_cache::StateChange::Defined {
name,
definition,
file,
at,
} => unit.define(name, definition.clone(), file, *at),
crate::index::walk_cache::StateChange::Undefined { name, .. } => {
unit.undefine(name)
}
}
next_change += 1;
}
while contribution
.events
.get(next_event)
.is_some_and(|event| event.at == next)
{
let event = &contribution.events[next_event];
if event.unconditional
&& let Some((summary, source)) = summary
&& let Ok(found) = summary
.macros
.binary_search_by_key(&event.at, |fact| fact.range.start_offset)
{
walked
.entries
.push((from_offset, &summary.macros[found], source));
}
next_event += 1;
}
while contribution
.edges
.get(next_edge)
.is_some_and(|(at, _)| *at == next)
{
let (at, child) = contribution.edges[next_edge];
let already_entered = cache.lookup(child).is_some_and(|child| {
seen.contains(child.file.as_path()) || walked.spliced.contains(&child.file)
});
if !already_entered {
splice_a_contribution(
child,
at,
Some(frame),
at,
seen,
look_up,
unit,
walked,
depth + 1,
cache,
);
}
next_edge += 1;
}
}
for change in &contribution.changes {
match change {
crate::index::walk_cache::StateChange::Defined {
name,
definition,
file,
at,
} => unit.define(name, definition.clone(), file, *at),
crate::index::walk_cache::StateChange::Undefined { name, .. } => unit.undefine(name),
}
}
if let Some((summary, source)) = look_up(&file) {
for event in &contribution.events {
if !event.unconditional {
continue;
}
let Ok(at) = summary
.macros
.binary_search_by_key(&event.at, |fact| fact.range.start_offset)
else {
continue;
};
walked
.entries
.push((from_offset, &summary.macros[at], source));
}
}
for body in &contribution.bodies {
walked.conditional_bodies.insert(
body.name.clone(),
(
body.function_like,
body.parameters.clone(),
body.body.clone(),
),
);
}
walked
.dead_macros
.entry(file.clone())
.or_default()
.extend(contribution.dead.iter().copied());
walked.conditional_facts += contribution.conditional_facts;
walked.facts_in_force += contribution.facts_in_force;
if let Some(timeline) = walked.timeline.as_mut() {
timeline.leave(frame);
}
if crate::probes::splice() {
eprintln!(
"splice: {} | {} changes, {} edges, {} events",
file.display(),
contribution.changes.len(),
contribution.edges.len(),
contribution.events.len(),
);
}
walked.spliced.insert(file);
true
}
pub fn macros_from_direct_includes<'a>(
summary: &FileSummary,
mut look_up: impl FnMut(&std::path::Path) -> Option<&'a FileSummary>,
) -> Vec<cpp_parser::IncludedMacro> {
let mut entries = Vec::new();
for include in &summary.includes {
let Some(included) = include.resolved.as_deref().and_then(&mut look_up) else {
continue;
};
let from_offset = include.range.start_offset + include.range.length;
for fact in &included.macros {
if !matches!(fact.guard, FactGuard::Unconditional) {
continue;
}
entries.push(if fact.kind.is_definition() {
cpp_parser::IncludedMacro::defined_at(
from_offset,
&fact.name,
fact.function_like,
fact.body,
)
} else {
cpp_parser::IncludedMacro::undefined_at(from_offset, &fact.name)
});
}
}
entries
}
pub use crate::preprocess::directive::IncludeForm;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FactGuard {
Unconditional,
Region(u32),
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SummaryGuards {
pub regions: Vec<cpp_parser::SourceRange>,
pub conditionals: Vec<ConditionalRegion>,
pub own_guard: Option<u32>,
pub visit_once: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConditionalRegion {
pub branches: Vec<GuardBranch>,
pub parent: Option<u32>,
pub decoded: std::sync::OnceLock<Vec<crate::Branch>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GuardBranch {
pub kind: crate::DirectiveKind,
pub condition: Option<Box<str>>,
pub body: cpp_parser::SourceRange,
pub range: cpp_parser::SourceRange,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConditionAt {
pub region: u32,
pub condition_at: usize,
}
impl SummaryGuards {
pub fn conditions_at(&self, offset: usize) -> Vec<ConditionAt> {
let mut found: Vec<ConditionAt> = Vec::new();
let mut current = (0..self.conditionals.len())
.filter(|index| self.conditionals[*index].contains(offset))
.min_by_key(|index| {
self.span_of(*index as u32)
.map_or(usize::MAX, |span| span.length)
});
while let Some(index) = current {
let Some(span) = self.span_of(index as u32) else {
break;
};
if Some(index as u32) != self.own_guard {
found.push(ConditionAt {
region: index as u32,
condition_at: span.start_offset,
});
}
current = self.conditionals[index]
.parent
.map(|parent| parent as usize);
}
found
}
pub fn conditions_of(&self, region: u32) -> Vec<ConditionAt> {
let mut found = Vec::new();
let mut current = Some(region);
while let Some(index) = current {
let Some(span) = self.span_of(index) else {
break;
};
if Some(index) != self.own_guard {
found.push(ConditionAt {
region: index,
condition_at: span.start_offset,
});
}
current = self
.conditionals
.get(index as usize)
.and_then(|conditional| conditional.parent);
}
found
}
pub fn region_at(&self, region: u32, offset: usize) -> Option<Region> {
let conditional = self.conditionals.get(region as usize)?;
let decoded = conditional.decoded.get_or_init(|| {
conditional
.branches
.iter()
.map(GuardBranch::as_branch)
.collect()
});
Some(Region {
branches: decoded.clone(),
active_branch: conditional.branch_at(offset)?,
})
}
pub fn span_of(&self, region: u32) -> Option<cpp_parser::SourceRange> {
self.regions.get(region as usize).copied()
}
pub fn visibility_of<M: crate::MacroValues>(
&self,
guard: FactGuard,
offset: usize,
macros_at: impl Fn(usize) -> M,
) -> Visibility {
let FactGuard::Region(region) = guard else {
return Visibility::Active;
};
let mut unknown = false;
for at in self.conditions_of(region) {
let Some(region) = self.region_at(at.region, offset) else {
unknown = true;
continue;
};
match region.visibility(¯os_at(at.condition_at)) {
Some(true) => {}
Some(false) => return Visibility::Inactive,
None => unknown = true,
}
}
if unknown {
Visibility::Unknown
} else {
Visibility::Active
}
}
}
impl ConditionalRegion {
pub fn branch_at(&self, offset: usize) -> Option<usize> {
if let Some(index) = self.branches.iter().position(|branch| {
branch.body.start_offset <= offset && offset < branch.body.end_offset()
}) {
return Some(index);
}
self.branches
.iter()
.rposition(|branch| branch.body.start_offset <= offset)
.or(if self.branches.is_empty() {
None
} else {
Some(0)
})
}
pub fn exhaustive(&self) -> bool {
self.branches
.iter()
.any(|branch| branch.kind == crate::DirectiveKind::Else)
}
fn contains(&self, offset: usize) -> bool {
self.branches
.iter()
.any(|branch| branch.body.start_offset <= offset && offset < branch.body.end_offset())
}
}
impl GuardBranch {
pub fn as_branch(&self) -> Branch {
match self.kind {
crate::DirectiveKind::Ifdef | crate::DirectiveKind::Ifndef => {
Branch::new(self.kind, Vec::new(), self.condition.clone(), self.range)
}
_ => Branch::new(self.kind, self.tokens(), None, self.range),
}
}
fn tokens(&self) -> Vec<crate::Token> {
let Some(text) = self.condition.as_deref() else {
return Vec::new();
};
let mut errors = Vec::new();
let mut lexer =
cpp_parser::CppLexer::new(text, cpp_parser::LexerConfig::default(), &mut errors);
let base = self.range.start_offset;
lexer
.tokenize()
.into_iter()
.filter(|token| !cpp_parser::is_trivia(token.kind))
.map(|token| {
crate::Token::new(
token.kind,
text.get(token.range.start_offset..token.range.end_offset())
.unwrap_or_default(),
cpp_parser::SourceRange::new(
base + token.range.start_offset,
token.range.length,
),
)
})
.collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileSummary {
pub path: std::path::PathBuf,
pub key: SummaryKey,
pub declarations: Vec<DeclFact>,
pub macros: Vec<MacroFact>,
pub includes: Vec<IncludeFact>,
pub guards: SummaryGuards,
pub macro_readings: Vec<MacroScopeReading>,
pub use_filter: Vec<u8>,
pub modules: ModuleReading,
}
const USE_FILTER_BITS_PER_NAME: usize = 14;
const USE_FILTER_MIN_BYTES: usize = 64;
const USE_FILTER_MAX_BYTES: usize = 32 * 1024;
pub fn use_filter_of(root: &cpp_parser::CppSyntaxNode) -> Vec<u8> {
use std::collections::HashSet;
let mut names: HashSet<String> = HashSet::new();
for element in root.descendants_with_tokens() {
let Some(token) = element.as_token() else {
continue;
};
if cpp_parser::CppTokenKind::from(token.kind()) != cpp_parser::CppTokenKind::Identifier {
continue;
}
let name = token.text();
if !name.is_empty() {
names.insert(name.to_string());
}
}
use_filter_of_names(names)
}
pub fn use_filter_of_tokens(source: &str, tokens: &[cpp_parser::CppTokenData]) -> Vec<u8> {
use std::collections::HashSet;
let mut names: HashSet<&str> = HashSet::new();
for token in tokens {
if token.kind != cpp_parser::CppTokenKind::Identifier {
continue;
}
let from = token.range.start_offset;
if let Some(name) = source.get(from..from + token.range.length)
&& !name.is_empty()
{
names.insert(name);
}
}
use_filter_of_names(names)
}
fn use_filter_of_names<S: AsRef<str> + Eq + std::hash::Hash>(
names: impl IntoIterator<Item = S>,
) -> Vec<u8> {
use std::collections::HashSet;
let names: HashSet<S> = names
.into_iter()
.filter(|name| !name.as_ref().is_empty())
.collect();
let bits = names
.len()
.saturating_mul(USE_FILTER_BITS_PER_NAME)
.clamp(USE_FILTER_MIN_BYTES * 8, USE_FILTER_MAX_BYTES * 8);
let mut filter = vec![0u8; bits.div_ceil(8)];
for name in names {
for probe in use_filter_probes(name.as_ref()) {
let bit = probe as usize % bits;
filter[bit / 8] |= 1 << (bit % 8);
}
}
filter
}
pub fn use_filter_might_contain(filter: &[u8], name: &str) -> bool {
if filter.is_empty() {
return true;
}
let bits = filter.len() * 8;
use_filter_probes(name).iter().all(|probe| {
let bit = *probe as usize % bits;
filter[bit / 8] & (1 << (bit % 8)) != 0
})
}
fn use_filter_probes(name: &str) -> [u64; 3] {
const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const PRIME: u64 = 0x0000_0100_0000_01b3;
let mut first = OFFSET;
for byte in name.as_bytes() {
first ^= u64::from(*byte);
first = first.wrapping_mul(PRIME);
}
let mut second = OFFSET ^ 0x9e37_79b9_7f4a_7c15;
for byte in name.as_bytes().iter().rev() {
second ^= u64::from(*byte);
second = second.wrapping_mul(PRIME);
}
let step = second | 1;
[
first,
first.wrapping_add(step),
first.wrapping_add(step.wrapping_mul(2)),
]
}
impl FileSummary {
pub fn empty(path: impl Into<std::path::PathBuf>, key: SummaryKey) -> Self {
FileSummary {
path: path.into(),
key,
declarations: Vec::new(),
macros: Vec::new(),
includes: Vec::new(),
guards: SummaryGuards::default(),
macro_readings: Vec::new(),
use_filter: Vec::new(),
modules: ModuleReading::default(),
}
}
pub fn is_empty(&self) -> bool {
self.declarations.is_empty() && self.macros.is_empty() && self.includes.is_empty()
}
pub fn intern_region(&mut self, region: Option<cpp_parser::SourceRange>) -> FactGuard {
let Some(range) = region else {
return FactGuard::Unconditional;
};
match self.guards.regions.iter().position(|known| *known == range) {
Some(index) => FactGuard::Region(index as u32),
None => {
self.guards.regions.push(range);
FactGuard::Region((self.guards.regions.len() - 1) as u32)
}
}
}
pub fn take_the_directives_of(&mut self, directed: FileSummary) {
let authored = std::mem::take(&mut self.guards.regions);
let mut directed = directed;
let mut regions = std::mem::take(&mut directed.guards.regions);
if !authored.is_empty() {
for fact in &mut self.declarations {
let FactGuard::Region(index) = fact.guard else {
continue;
};
let Some(range) = authored.get(index as usize).copied() else {
fact.guard = FactGuard::Unconditional;
continue;
};
fact.guard = match regions.iter().position(|known| *known == range) {
Some(index) => FactGuard::Region(index as u32),
None => {
regions.push(range);
FactGuard::Region((regions.len() - 1) as u32)
}
};
}
}
self.macros = directed.macros;
self.includes = directed.includes;
self.guards = directed.guards;
self.guards.regions = regions;
if !directed.use_filter.is_empty() {
self.use_filter = directed.use_filter;
}
}
pub fn map_into_the_file(
&mut self,
rendered: &crate::preprocess::cooked::RenderedCooked,
) -> MapReport {
let mut report = MapReport::default();
let place = |range: cpp_parser::SourceRange, report: &mut MapReport| match rendered
.reported_span(range)
{
Some(mapped) => {
report.placed += 1;
Some(mapped)
}
None => {
report.dropped += 1;
None
}
};
self.declarations.retain_mut(|fact| {
let (Some(range), Some(name_range)) = (
place(fact.range, &mut report),
place(fact.name_range, &mut report),
) else {
return false;
};
fact.range = range;
fact.name_range = name_range;
true
});
self.macros.retain_mut(|fact| {
let Some(range) = place(fact.range, &mut report) else {
return false;
};
fact.range = range;
fact.body_range = fact.body_range.and_then(|body| place(body, &mut report));
true
});
self.includes.retain_mut(|fact| {
let Some(range) = place(fact.range, &mut report) else {
return false;
};
fact.range = range;
true
});
self.macro_readings.retain_mut(|reading| {
let Some(range) = place(reading.range, &mut report) else {
return false;
};
reading.range = range;
true
});
for region in &mut self.guards.regions {
if let Some(mapped) = place(*region, &mut report) {
*region = mapped;
}
}
report
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MapReport {
pub placed: usize,
pub dropped: usize,
}
#[derive(Debug, Default, Clone)]
pub struct IndexedUnit {
pub files: Vec<(std::path::PathBuf, crate::CookedFile)>,
pub unplaced: usize,
pub tokens: usize,
pub files_with_tokens: usize,
pub missing: usize,
pub unbalanced: Vec<std::path::PathBuf>,
pub braces: i64,
pub errors: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnitReading {
pub root: std::path::PathBuf,
pub files: usize,
pub declared: usize,
pub tokens: usize,
pub files_with_tokens: usize,
pub missing: usize,
pub unplaced: usize,
pub unbalanced: Vec<std::path::PathBuf>,
pub braces: i64,
pub errors: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CookedDiagnostic {
pub range: cpp_parser::SourceRange,
pub message: String,
}
#[derive(Debug, Clone)]
pub struct IndexedRendering {
pub summary: FileSummary,
pub rendered: std::sync::Arc<crate::preprocess::cooked::RenderedCooked>,
pub mapped: MapReport,
pub diagnostics: Vec<CookedDiagnostic>,
pub unplaced: usize,
}
impl DeclKind {
pub fn from_binding_kind(kind: crate::BindingKind) -> DeclKind {
use crate::BindingKind as B;
match kind {
B::Class | B::Enum | B::Alias | B::Typedef | B::TemplateParameter => DeclKind::Type,
B::Function
| B::Constructor
| B::Destructor
| B::ConversionFunction
| B::OperatorFunction
| B::LiteralOperator => DeclKind::Function,
B::Variable | B::Enumerator => DeclKind::Variable,
B::Namespace => DeclKind::Namespace,
_ => DeclKind::Other,
}
}
}