use cpp_parser::{CppSyntaxKind, CppSyntaxNode, CppTokenKind};
use crate::token::tokens_of;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ModuleUnit {
InterfaceUnit,
ImplementationUnit,
PartitionInterfaceUnit,
PartitionImplementationUnit,
}
impl ModuleUnit {
pub fn exports_to_importers(self) -> bool {
matches!(self, ModuleUnit::InterfaceUnit)
}
pub fn is_interface(self) -> bool {
matches!(
self,
ModuleUnit::InterfaceUnit | ModuleUnit::PartitionInterfaceUnit
)
}
pub fn is_partition(self) -> bool {
matches!(
self,
ModuleUnit::PartitionInterfaceUnit | ModuleUnit::PartitionImplementationUnit
)
}
pub fn describe(self) -> &'static str {
match self {
ModuleUnit::InterfaceUnit => "module interface unit",
ModuleUnit::ImplementationUnit => "module implementation unit",
ModuleUnit::PartitionInterfaceUnit => "module partition interface unit",
ModuleUnit::PartitionImplementationUnit => "module partition implementation unit",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ImportTarget {
Module(Box<str>),
Partition(Box<str>),
HeaderUnit { name: Box<str>, is_angle: bool },
}
impl ImportTarget {
pub fn describe(&self) -> String {
match self {
ImportTarget::Module(name) => format!("module `{name}`"),
ImportTarget::Partition(name) => format!("partition `:{name}`"),
ImportTarget::HeaderUnit { name, is_angle } => {
if *is_angle {
format!("header unit `<{name}>`")
} else {
format!("header unit `\"{name}\"`")
}
}
}
}
pub fn partition_name(&self) -> Option<&str> {
match self {
ImportTarget::Partition(name) => Some(name),
_ => None,
}
}
pub fn module_name(&self) -> Option<&str> {
match self {
ImportTarget::Module(name) => Some(name),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportDeclaration {
pub target: ImportTarget,
pub is_reexport: bool,
pub range: cpp_parser::SourceRange,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ModuleInfo {
pub unit: Option<ModuleUnit>,
pub module_name: Option<Box<str>>,
pub partition_name: Option<Box<str>>,
pub has_global_fragment: bool,
pub has_private_fragment: bool,
pub imports: Vec<ImportDeclaration>,
}
impl ModuleInfo {
pub fn has_an_imported_partition(&self) -> bool {
self.imports
.iter()
.any(|declaration| declaration.target.partition_name().is_some())
}
pub fn from_tree(root: &CppSyntaxNode) -> Self {
let mut info = ModuleInfo::default();
for node in root.descendants() {
match CppSyntaxKind::from(node.kind()) {
CppSyntaxKind::GlobalModuleFragment => info.has_global_fragment = true,
CppSyntaxKind::PrivateModuleFragment => info.has_private_fragment = true,
CppSyntaxKind::ModuleDecl => {
if info.unit.is_none() {
let (name, partition) = read_module_parts(&node);
let has_partition = partition.is_some();
info.unit = Some(classify_unit(&node, has_partition));
info.module_name = name;
info.partition_name = partition;
}
}
CppSyntaxKind::ImportDecl => {
if let Some(declaration) = read_import(&node) {
info.imports.push(declaration);
}
}
_ => {}
}
}
info
}
pub fn qualified_name(&self) -> Option<String> {
match (&self.module_name, &self.partition_name) {
(Some(module), Some(partition)) => Some(format!("{module}:{partition}")),
(Some(module), None) => Some(module.to_string()),
_ => None,
}
}
pub fn is_module_unit(&self) -> bool {
self.unit.is_some()
}
pub fn macros_are_self_contained(&self) -> bool {
self.is_module_unit()
}
pub fn plain_imports(&self) -> impl Iterator<Item = &ImportDeclaration> {
self.imports.iter().filter(|import| !import.is_reexport)
}
pub fn reexports(&self) -> impl Iterator<Item = &ImportDeclaration> {
self.imports.iter().filter(|import| import.is_reexport)
}
}
fn read_module_parts(node: &CppSyntaxNode) -> (Option<Box<str>>, Option<Box<str>>) {
let mut name = None;
let mut partition = None;
for child in node.children() {
match CppSyntaxKind::from(child.kind()) {
CppSyntaxKind::ModuleName if name.is_none() => name = Some(read_dotted_name(&child)),
CppSyntaxKind::ModulePartition => {
partition = child
.children()
.find(|inner| CppSyntaxKind::from(inner.kind()) == CppSyntaxKind::ModuleName)
.map(|inner| read_dotted_name(&inner));
}
_ => {}
}
}
(name, partition)
}
fn read_dotted_name(node: &CppSyntaxNode) -> Box<str> {
let mut name = String::new();
let mut first = true;
for token in tokens_of(node) {
match token.kind {
CppTokenKind::Identifier => {
name.push_str(&token.text);
first = false;
}
CppTokenKind::Dot if !first => name.push('.'),
_ => {}
}
}
name.into_boxed_str()
}
fn classify_unit(node: &CppSyntaxNode, has_partition: bool) -> ModuleUnit {
let is_exported = tokens_of(node)
.iter()
.any(|token| token.kind == CppTokenKind::ExportKeyword);
match (is_exported, has_partition) {
(true, false) => ModuleUnit::InterfaceUnit,
(false, false) => ModuleUnit::ImplementationUnit,
(true, true) => ModuleUnit::PartitionInterfaceUnit,
(false, true) => ModuleUnit::PartitionImplementationUnit,
}
}
fn read_import(node: &CppSyntaxNode) -> Option<ImportDeclaration> {
let is_reexport = tokens_of(node)
.iter()
.any(|token| token.kind == CppTokenKind::ExportKeyword);
let mut target = None;
for child in node.children() {
match CppSyntaxKind::from(child.kind()) {
CppSyntaxKind::HeaderName => {
let text = child.text().to_string();
let is_angle = text.trim_start().starts_with('<');
let name = text
.trim()
.trim_start_matches(['<', '"'])
.trim_end_matches(['>', '"']);
target = Some(ImportTarget::HeaderUnit {
name: name.into(),
is_angle,
});
}
CppSyntaxKind::ModulePartition => {
let name = child
.children()
.find(|inner| CppSyntaxKind::from(inner.kind()) == CppSyntaxKind::ModuleName)
.map(|inner| read_dotted_name(&inner))
.unwrap_or_default();
if !name.is_empty() {
target = Some(ImportTarget::Partition(name));
}
}
CppSyntaxKind::ModuleName => {
let name = read_dotted_name(&child);
if !name.is_empty() {
target = Some(ImportTarget::Module(name));
}
}
_ => {}
}
}
Some(ImportDeclaration {
target: target?,
is_reexport,
range: cpp_parser::source_range(node.text_range()),
})
}