use std::collections::HashSet;
use cpp_parser::SourceRange;
use crate::paths::FileId;
use crate::summary::MacroScopeReading;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Known<T> {
Yes(T),
No,
Unknown(UnknownReason),
}
impl<T> Known<T> {
pub fn is_known(&self) -> bool {
matches!(self, Known::Yes(_))
}
pub fn is_definitely_absent(&self) -> bool {
matches!(self, Known::No)
}
pub fn value(self) -> Option<T> {
match self {
Known::Yes(value) => Some(value),
_ => None,
}
}
pub fn value_ref(&self) -> Option<&T> {
match self {
Known::Yes(value) => Some(value),
_ => None,
}
}
pub fn reason(&self) -> Option<&UnknownReason> {
match self {
Known::Unknown(reason) => Some(reason),
_ => None,
}
}
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Known<U> {
match self {
Known::Yes(value) => Known::Yes(f(value)),
Known::No => Known::No,
Known::Unknown(reason) => Known::Unknown(reason),
}
}
pub fn then_unknown(self, reason: UnknownReason) -> Known<T> {
match self {
Known::No => Known::No,
_ => Known::Unknown(reason),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UnknownReason {
MacroExpansion(Box<str>),
ConditionalCompilation,
UnresolvedInclude(Box<str>),
UnresolvedModule(Box<str>),
DependentName,
UnexpandedTemplate,
UnparsableName,
IncompleteMacroContext,
NotDeclaredHere(Box<str>),
Ambiguous(Box<str>),
UndefinedHere(Box<str>),
UnknownType(Box<str>),
}
impl UnknownReason {
pub fn describe(&self) -> String {
match self {
UnknownReason::MacroExpansion(name) => {
format!(
"the name comes from the expansion of `{name}`, which was not expanded here"
)
}
UnknownReason::ConditionalCompilation => {
"the name is behind a condition that could not be evaluated".to_string()
}
UnknownReason::UnresolvedInclude(name) => {
format!("the name may be declared in `{name}`, which was not found")
}
UnknownReason::UnresolvedModule(name) => format!(
"the name may be exported by module `{name}`, which is not part of this analysis"
),
UnknownReason::DependentName => {
"the name depends on a template argument that is not known yet".to_string()
}
UnknownReason::UnexpandedTemplate => {
"the declaration is inside a template that has not been instantiated".to_string()
}
UnknownReason::UnparsableName => {
"the declared name could not be read from the source".to_string()
}
UnknownReason::IncompleteMacroContext => {
"this file's macro environment is not fully known".to_string()
}
UnknownReason::NotDeclaredHere(name) => format!(
"`{name}` is not declared in this file, so its declaration is in a file that was not read"
),
UnknownReason::Ambiguous(name) => format!(
"`{name}` is declared more than once in what this file can see, and nothing here chooses \
between the declarations"
),
UnknownReason::UndefinedHere(name) => format!(
"`{name}` is a macro that an `#undef` above this point has ended, so this is an ordinary \
identifier"
),
UnknownReason::UnknownType(written) => format!(
"the type of `{written}` is not known here, so what its members are is not known either"
),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum NameKind {
Identifier(String),
Destructor(String),
Conversion(String),
Operator(String),
Literal(String),
}
impl NameKind {
pub fn text(&self) -> String {
match self {
NameKind::Identifier(name) => name.clone(),
NameKind::Destructor(name) => format!("~{name}"),
NameKind::Conversion(type_name) => format!("operator {type_name}"),
NameKind::Operator(symbol) => {
if symbol.starts_with(|first: char| first.is_alphanumeric() || first == '_') {
format!("operator {symbol}")
} else {
format!("operator{symbol}")
}
}
NameKind::Literal(suffix) => format!("operator\"\"_{suffix}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Name {
pub kind: NameKind,
}
impl Name {
pub fn identifier(text: impl Into<String>) -> Self {
Name {
kind: NameKind::Identifier(text.into()),
}
}
pub fn destructor(class: impl Into<String>) -> Self {
Name {
kind: NameKind::Destructor(class.into()),
}
}
pub fn conversion(type_name: impl Into<String>) -> Self {
Name {
kind: NameKind::Conversion(type_name.into()),
}
}
pub fn operator(symbol: impl Into<String>) -> Self {
Name {
kind: NameKind::Operator(symbol.into()),
}
}
pub fn literal(suffix: impl Into<String>) -> Self {
Name {
kind: NameKind::Literal(suffix.into()),
}
}
pub fn text(&self) -> String {
self.kind.text()
}
pub fn is_ordinary(&self) -> bool {
matches!(self.kind, NameKind::Identifier(_) | NameKind::Destructor(_))
}
pub fn identifier_text(&self) -> Option<&str> {
match &self.kind {
NameKind::Identifier(name) => Some(name),
_ => None,
}
}
pub fn base_text(&self) -> Option<&str> {
match &self.kind {
NameKind::Identifier(name) | NameKind::Destructor(name) => Some(name),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct QualifiedName {
pub components: Vec<String>,
}
impl QualifiedName {
pub fn single(component: impl Into<String>) -> Self {
QualifiedName {
components: vec![component.into()],
}
}
pub fn from_components(components: impl IntoIterator<Item = String>) -> Self {
QualifiedName {
components: components.into_iter().collect(),
}
}
pub fn last(&self) -> Option<&str> {
self.components.last().map(String::as_str)
}
pub fn qualifiers(&self) -> &[String] {
let end = self.components.len().saturating_sub(1);
&self.components[..end]
}
pub fn text(&self) -> String {
self.components.join("::")
}
pub fn is_empty(&self) -> bool {
self.components.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HeaderName {
pub name: String,
pub is_angle: bool,
}
impl HeaderName {
pub fn text(&self) -> String {
if self.is_angle {
format!("<{}>", self.name)
} else {
format!("\"{}\"", self.name)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DeclName {
Named(Name),
Qualified(QualifiedName),
Module(QualifiedName),
HeaderUnit(HeaderName),
Partition(QualifiedName),
}
impl DeclName {
pub fn text(&self) -> String {
match self {
DeclName::Named(name) => name.text(),
DeclName::Qualified(qualified) => qualified.text(),
DeclName::Module(module) => module.text(),
DeclName::HeaderUnit(header) => header.text(),
DeclName::Partition(partition) => format!(":{}", partition.text()),
}
}
pub fn ordinary_name(&self) -> Option<&Name> {
match self {
DeclName::Named(name) if name.is_ordinary() => Some(name),
_ => None,
}
}
}
pub type MaybeName = Option<DeclName>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum BindingKind {
Namespace,
Class,
Enum,
Enumerator,
Function,
Constructor,
Destructor,
ConversionFunction,
OperatorFunction,
LiteralOperator,
Variable,
UsingDeclaration,
UsingDirective,
Alias,
Typedef,
TemplateParameter,
Label,
Other,
}
impl BindingKind {
pub fn is_type_like(self) -> bool {
matches!(
self,
BindingKind::Class
| BindingKind::Enum
| BindingKind::Alias
| BindingKind::Typedef
| BindingKind::Namespace
)
}
pub fn opens_a_scope(self) -> bool {
matches!(
self,
BindingKind::Namespace | BindingKind::Class | BindingKind::Enum | BindingKind::Function
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binding {
pub name: Name,
pub kind: BindingKind,
pub range: SourceRange,
pub name_range: SourceRange,
pub scope: ScopeId,
pub origin: Option<BindingOrigin>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BindingOrigin {
MacroExpansion {
macro_name: String,
definition: SourceRange,
},
Included { file: FileId },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ScopeKind {
TranslationUnit,
Namespace,
Class,
Enum,
Function,
Block,
TemplateParameters,
Lambda,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Scope {
pub parent: Option<ScopeId>,
pub children: Vec<ScopeId>,
pub kind: ScopeKind,
pub name: Option<Box<str>>,
pub range: Option<SourceRange>,
pub unscoped_enum: bool,
pub bindings: Vec<Binding>,
}
impl Scope {
pub fn bindings_of(&self, name: &Name) -> impl Iterator<Item = &Binding> {
self.bindings
.iter()
.filter(move |binding| &binding.name == name)
}
pub fn declared_names(&self) -> Vec<&Name> {
let mut names: Vec<&Name> = self.bindings.iter().map(|binding| &binding.name).collect();
names.sort_unstable();
names.dedup();
names
}
pub fn is_empty(&self) -> bool {
self.bindings.is_empty()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ScopeId(pub usize);
impl ScopeId {
pub fn index(self) -> usize {
self.0
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScopeTree {
scopes: Vec<Scope>,
root: Option<ScopeId>,
pub macro_readings: Vec<MacroScopeReading>,
by_qualified_name: std::collections::HashMap<String, ScopeId>,
by_start: Vec<(usize, ScopeId)>,
}
impl ScopeTree {
pub fn new() -> Self {
ScopeTree::default()
}
pub fn macro_readings(&self) -> &[MacroScopeReading] {
&self.macro_readings
}
pub fn root(&self) -> Option<ScopeId> {
self.root
}
pub fn scope(&self, id: ScopeId) -> Option<&Scope> {
self.scopes.get(id.index())
}
pub fn scope_mut(&mut self, id: ScopeId) -> Option<&mut Scope> {
self.scopes.get_mut(id.index())
}
pub fn scopes(&self) -> &[Scope] {
&self.scopes
}
pub fn len(&self) -> usize {
self.scopes.len()
}
pub fn is_empty(&self) -> bool {
self.scopes.is_empty()
}
pub fn create_scope(
&mut self,
kind: ScopeKind,
parent: Option<ScopeId>,
range: Option<SourceRange>,
) -> ScopeId {
self.create_named_scope(kind, parent, range, None)
}
pub fn create_named_scope(
&mut self,
kind: ScopeKind,
parent: Option<ScopeId>,
range: Option<SourceRange>,
name: Option<&str>,
) -> ScopeId {
let id = ScopeId(self.scopes.len());
self.scopes.push(Scope {
parent,
children: Vec::new(),
kind,
name: name.map(Box::from),
range,
unscoped_enum: false,
bindings: Vec::new(),
});
match parent {
Some(parent) => {
if let Some(scope) = self.scopes.get_mut(parent.index()) {
scope.children.push(id);
}
}
None => {
if self.root.is_none() {
self.root = Some(id);
}
}
}
if name.is_some()
&& let Some(qualified) = self.qualified_name_of(id)
{
self.by_qualified_name.entry(qualified).or_insert(id);
}
if let Some(range) = range {
self.by_start.push((range.start_offset, id));
}
id
}
pub fn qualified_name_of(&self, scope: ScopeId) -> Option<String> {
let mut segments: Vec<&str> = Vec::new();
let mut seen = HashSet::new();
let mut current = Some(scope);
while let Some(id) = current {
if !seen.insert(id) {
break;
}
let Some(scope) = self.scopes.get(id.index()) else {
break;
};
match &scope.name {
Some(name) => segments.push(name),
None if matches!(scope.kind, ScopeKind::Class | ScopeKind::Enum) => break,
None => {}
}
current = scope.parent;
}
if segments.is_empty() {
return None;
}
segments.reverse();
Some(segments.join("::"))
}
pub fn add_binding(&mut self, scope: ScopeId, binding: Binding) -> bool {
let Some(target) = self.scopes.get_mut(scope.index()) else {
return false;
};
if !accepts_binding(target.kind, binding.kind) {
return false;
}
let position = target
.bindings
.partition_point(|existing| existing.name <= binding.name);
target.bindings.insert(position, binding);
true
}
pub fn qualification_prefix_of(&self, scope: ScopeId) -> Option<String> {
match self.scopes.get(scope.index())?.kind {
ScopeKind::Namespace | ScopeKind::Class | ScopeKind::Enum => {
self.qualified_name_of(scope)
}
ScopeKind::TranslationUnit
| ScopeKind::Function
| ScopeKind::Block
| ScopeKind::Lambda
| ScopeKind::TemplateParameters => None,
}
}
pub fn scope_at(&self, offset: usize) -> Option<ScopeId> {
let at = self.by_start.partition_point(|(start, _)| *start <= offset);
let mut current = at.checked_sub(1).map(|index| self.by_start[index].1);
while let Some(id) = current {
let scope = self.scopes.get(id.index())?;
if let Some(range) = scope.range
&& offset >= range.start_offset
&& offset <= range.end_offset()
{
return Some(id);
}
current = scope.parent;
}
None
}
pub fn scope_chain(&self, from: ScopeId) -> Vec<ScopeId> {
let mut chain = Vec::new();
let mut seen = HashSet::new();
let mut current = Some(from);
while let Some(id) = current {
if !seen.insert(id) {
break;
}
let Some(scope) = self.scopes.get(id.index()) else {
break;
};
chain.push(id);
current = scope.parent;
}
chain
}
pub fn scope_with_qualified_name(&self, name: &str) -> Option<ScopeId> {
self.by_qualified_name.get(name).copied()
}
pub fn binding_declared_at(&self, offset: usize) -> Option<&Binding> {
self.scopes
.iter()
.flat_map(|scope| scope.bindings.iter())
.find(|binding| binding.name_range.contain(offset))
}
pub fn declares_a_local(&self, scope: ScopeId) -> bool {
self.scope_chain(scope).iter().any(|id| {
matches!(
self.scopes.get(id.index()).map(|scope| scope.kind),
Some(ScopeKind::Function | ScopeKind::Block | ScopeKind::Lambda)
)
})
}
}
fn accepts_binding(scope: ScopeKind, binding: BindingKind) -> bool {
match binding {
BindingKind::Label => matches!(
scope,
ScopeKind::Function | ScopeKind::Block | ScopeKind::Lambda
),
BindingKind::Namespace | BindingKind::UsingDirective => {
matches!(scope, ScopeKind::TranslationUnit | ScopeKind::Namespace)
}
BindingKind::TemplateParameter => matches!(scope, ScopeKind::TemplateParameters),
_ => !matches!(scope, ScopeKind::TemplateParameters),
}
}