use super::diagnostic::{Diagnostic, DiagnosticCategory};
use super::environment::CfgSet;
use super::model::{
DiscoveredItem, DiscoveredItemKind, ImageScope, Location, ModuleBody, SelectedField,
SymbolArgument, SymbolDeclaration, SymbolFunction, SymbolGlobal, SymbolSafety, TypeSyntax,
};
use super::predicate::effective_metas;
use pdb_bindgen_macro_support::{MarkerSchema, MarkerTarget, parse_marker};
use proc_macro2::{Span, TokenStream};
use quote::ToTokens as _;
use std::collections::BTreeSet;
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned as _;
use syn::{Attribute, Expr, Fields, Ident, Item, Lit, Meta, Token, Visibility};
fn path_text(path: &syn::Path) -> String {
path.segments
.iter()
.map(|segment| segment.ident.to_string())
.collect::<Vec<_>>()
.join("::")
}
fn marker_arguments(meta: &Meta) -> TokenStream {
match meta {
Meta::Path(_) => TokenStream::new(),
Meta::List(list) => list.tokens.clone(),
Meta::NameValue(pair) => pair.value.to_token_stream(),
}
}
pub(super) fn walk_items(
items: &[Item],
cfg: &CfgSet,
path: &str,
) -> Result<Vec<DiscoveredItem>, Diagnostic> {
let mut discovered = Vec::new();
for item in items {
let effective = effective_metas(item_attrs(item), cfg, path)?;
if !effective.active {
continue;
}
if effective.markers.len() > 1 {
return Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
effective.markers[1].span(),
"duplicate outer #[pdb] attribute",
));
}
let marker = effective
.markers
.first()
.map(|meta| {
let clean = item_without_attrs(item);
parse_marker(marker_arguments(meta), MarkerTarget::Item(&clean)).map_err(|error| {
Diagnostic::at(
DiagnosticCategory::Marker,
path,
error.span(),
error.to_string(),
)
})
})
.transpose()?;
match item {
Item::Mod(module) => {
let image = match marker {
Some(MarkerSchema::Image { image, base, .. }) => Some(ImageScope {
image,
base: path_text(&base),
}),
None => None,
Some(_) => unreachable!("module marker placement was validated"),
};
let path_attribute = module_path(&effective.paths, path)?;
let body = if let Some((_, nested)) = &module.content {
ModuleBody::Inline(walk_items(nested, cfg, path)?)
} else {
ModuleBody::OutOfLine
};
discovered.push(discovered_item(
module.ident.span(),
DiscoveredItemKind::Module {
name: module.ident.to_string(),
body,
image,
path: path_attribute,
},
));
}
Item::Struct(item_struct) => {
validate_type_shape(&item_struct.generics, &item_struct.fields, &effective, path)?;
let fields = walk_fields(
item_struct.fields.iter(),
marker
.as_ref()
.is_some_and(|marker| matches!(marker, MarkerSchema::Type { .. })),
cfg,
path,
)?;
if let Some(marker) = marker {
discovered.push(discovered_marker(
marker,
fields,
type_syntax(&item_struct.vis, &effective, path)?,
));
}
}
Item::Union(item_union) => {
validate_type_shape(
&item_union.generics,
&Fields::Named(item_union.fields.clone()),
&effective,
path,
)?;
let fields = walk_fields(
item_union.fields.named.iter(),
marker
.as_ref()
.is_some_and(|marker| matches!(marker, MarkerSchema::Type { .. })),
cfg,
path,
)?;
if let Some(marker) = marker {
discovered.push(discovered_marker(
marker,
fields,
type_syntax(&item_union.vis, &effective, path)?,
));
}
}
Item::ForeignMod(foreign) => {
if let Some(MarkerSchema::Symbols { span }) = marker {
if !effective.attributes.is_empty() {
return Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
foreign.span(),
"#[pdb(symbols)] blocks cannot carry non-discovery attributes",
));
}
if foreign
.abi
.name
.as_ref()
.is_none_or(|name| name.value() != "system")
|| foreign.unsafety.is_none()
{
return Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
foreign.span(),
"#[pdb(symbols)] requires unsafe extern \"system\"",
));
}
discovered.push(discovered_item(
span,
DiscoveredItemKind::Symbols {
declarations: walk_symbols(&foreign.items, cfg, path)?,
},
));
}
}
_ => {
if let Some(marker) = marker {
discovered.push(discovered_marker(
marker,
Vec::new(),
TypeSyntax {
visibility: String::new(),
attributes: Vec::new(),
},
));
}
}
}
}
Ok(discovered)
}
fn walk_symbols(
items: &[syn::ForeignItem],
cfg: &CfgSet,
path: &str,
) -> Result<Vec<SymbolDeclaration>, Diagnostic> {
let mut result = Vec::new();
for item in items {
match item {
syn::ForeignItem::Fn(value) => {
let effective = effective_metas(&value.attrs, cfg, path)?;
if effective.active {
result.push(symbol_function(
&value.attrs,
&value.vis,
&value.sig,
SymbolSafety::Unsafe,
cfg,
path,
)?);
}
}
syn::ForeignItem::Static(value) => {
let effective = effective_metas(&value.attrs, cfg, path)?;
if effective.active {
result.push(symbol_static(
&value.attrs,
&value.vis,
&value.ident,
&value.ty,
matches!(value.mutability, syn::StaticMutability::Mut(_)),
SymbolSafety::Unsafe,
cfg,
path,
)?);
}
}
syn::ForeignItem::Verbatim(tokens) => {
let prefix = syn::parse2::<VerbatimPrefix>(tokens.clone()).map_err(|error| {
Diagnostic::at(
DiagnosticCategory::Marker,
path,
error.span(),
error.to_string(),
)
})?;
let effective = effective_metas(&prefix.attrs, cfg, path)?;
if !effective.active {
continue;
}
let value = syn::parse2::<ContextualForeignItemBody>(prefix.remainder).map_err(
|error| {
Diagnostic::at(
DiagnosticCategory::Marker,
path,
error.span(),
error.to_string(),
)
},
)?;
result.push(value.into_declaration(prefix.attrs, cfg, path)?);
}
_ => {
return Err(Diagnostic::new(
DiagnosticCategory::Marker,
path,
"PDB symbols blocks support only functions and statics",
));
}
}
}
let mut names = BTreeSet::new();
for declaration in &result {
let (name, location) = match declaration {
SymbolDeclaration::Function(function) => (&function.name, function.location),
SymbolDeclaration::Global(global) => (&global.name, global.location),
};
if !names.insert(name) {
return Err(Diagnostic::at_location(
DiagnosticCategory::Marker,
path,
location,
format!("duplicate PDB symbol declaration `{name}`"),
));
}
}
Ok(result)
}
fn symbol_function(
attrs: &[Attribute],
vis: &Visibility,
sig: &syn::Signature,
safety: SymbolSafety,
cfg: &CfgSet,
path: &str,
) -> Result<SymbolDeclaration, Diagnostic> {
let effective = effective_metas(attrs, cfg, path)?;
let attributes = approved_attributes(&effective, path)?;
if sig.constness.is_some()
|| sig.asyncness.is_some()
|| sig.variadic.is_some()
|| !sig.generics.params.is_empty()
|| sig.generics.where_clause.is_some()
|| sig.abi.is_some()
|| sig.ident.to_string().starts_with("r#")
{
return Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
sig.span(),
"unsupported PDB function declaration",
));
}
let mut arguments = Vec::new();
for argument in &sig.inputs {
let syn::FnArg::Typed(argument) = argument else {
return Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
argument.span(),
"PDB functions require named arguments",
));
};
let syn::Pat::Ident(name) = argument.pat.as_ref() else {
return Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
argument.pat.span(),
"PDB functions require simple named arguments",
));
};
if !argument.attrs.is_empty()
|| name.by_ref.is_some()
|| name.mutability.is_some()
|| name.subpat.is_some()
|| name.ident.to_string().starts_with("r#")
{
return Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
argument.span(),
"PDB functions require simple named arguments",
));
}
arguments.push(SymbolArgument {
name: name.ident.to_string(),
ty: argument.ty.to_token_stream().to_string(),
});
}
Ok(SymbolDeclaration::Function(SymbolFunction {
location: location(sig.ident.span()),
name: sig.ident.to_string(),
visibility: vis.to_token_stream().to_string(),
attributes,
safety,
arguments,
output: match &sig.output {
syn::ReturnType::Default => None,
syn::ReturnType::Type(_, ty) => Some(ty.to_token_stream().to_string()),
},
}))
}
#[allow(clippy::too_many_arguments)]
fn symbol_static(
attrs: &[Attribute],
vis: &Visibility,
ident: &Ident,
ty: &syn::Type,
mutable: bool,
safety: SymbolSafety,
cfg: &CfgSet,
path: &str,
) -> Result<SymbolDeclaration, Diagnostic> {
let effective = effective_metas(attrs, cfg, path)?;
let attributes = approved_attributes(&effective, path)?;
if ident.to_string().starts_with("r#") {
return Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
ident.span(),
"unsupported PDB static declaration",
));
}
if safety == SymbolSafety::Safe && mutable {
return Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
ident.span(),
"safe static mut is unsupported",
));
}
Ok(SymbolDeclaration::Global(SymbolGlobal {
location: location(ident.span()),
name: ident.to_string(),
visibility: vis.to_token_stream().to_string(),
attributes,
safety,
ty: ty.to_token_stream().to_string(),
mutable,
}))
}
struct VerbatimPrefix {
attrs: Vec<Attribute>,
remainder: TokenStream,
}
impl Parse for VerbatimPrefix {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
Ok(Self {
attrs: input.call(Attribute::parse_outer)?,
remainder: input.parse()?,
})
}
}
enum ContextualForeignItemBody {
Function {
vis: Visibility,
safety: SymbolSafety,
sig: syn::Signature,
},
Static {
vis: Visibility,
safety: SymbolSafety,
ident: Ident,
ty: syn::Type,
mutable: bool,
},
}
impl ContextualForeignItemBody {
fn into_declaration(
self,
attrs: Vec<Attribute>,
cfg: &CfgSet,
path: &str,
) -> Result<SymbolDeclaration, Diagnostic> {
match self {
Self::Function { vis, safety, sig } => {
symbol_function(&attrs, &vis, &sig, safety, cfg, path)
}
Self::Static {
vis,
safety,
ident,
ty,
mutable,
} => symbol_static(&attrs, &vis, &ident, &ty, mutable, safety, cfg, path),
}
}
}
impl Parse for ContextualForeignItemBody {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let vis: Visibility = input.parse()?;
let safety = if input.peek(Token![unsafe]) {
input.parse::<Token![unsafe]>()?;
SymbolSafety::Unsafe
} else {
let safe: Ident = input.parse()?;
if safe != "safe" {
return Err(syn::Error::new(safe.span(), "expected `safe` or `unsafe`"));
}
SymbolSafety::Safe
};
if input.peek(Token![fn]) {
let sig: syn::Signature = input.parse()?;
input.parse::<Token![;]>()?;
if !input.is_empty() {
return Err(input.error("unexpected tokens after foreign function declaration"));
}
Ok(Self::Function { vis, safety, sig })
} else {
input.parse::<Token![static]>()?;
let mutable = matches!(
input.parse::<syn::StaticMutability>()?,
syn::StaticMutability::Mut(_)
);
let ident: Ident = input.parse()?;
input.parse::<Token![:]>()?;
let ty: syn::Type = input.parse()?;
input.parse::<Token![;]>()?;
if !input.is_empty() {
return Err(input.error("unexpected tokens after foreign static declaration"));
}
Ok(Self::Static {
vis,
safety,
ident,
ty,
mutable,
})
}
}
}
fn module_path(paths: &[Meta], source_path: &str) -> Result<Option<String>, Diagnostic> {
if paths.len() > 1 {
return Err(Diagnostic::at(
DiagnosticCategory::ModuleGraph,
source_path,
paths[1].span(),
"duplicate effective #[path] attribute",
));
}
let Some(path) = paths.first() else {
return Ok(None);
};
let Meta::NameValue(value) = path else {
return Err(Diagnostic::at(
DiagnosticCategory::ModuleGraph,
source_path,
path.span(),
"#[path] requires a string literal value",
));
};
let Expr::Lit(value) = &value.value else {
return Err(Diagnostic::at(
DiagnosticCategory::ModuleGraph,
source_path,
value.value.span(),
"#[path] requires a string literal value",
));
};
let Lit::Str(value) = &value.lit else {
return Err(Diagnostic::at(
DiagnosticCategory::ModuleGraph,
source_path,
value.lit.span(),
"#[path] requires a string literal value",
));
};
Ok(Some(value.value()))
}
fn walk_fields<'a>(
fields: impl Iterator<Item = &'a syn::Field>,
owner_is_pdb_type: bool,
cfg: &CfgSet,
path: &str,
) -> Result<Vec<SelectedField>, Diagnostic> {
let mut selected = Vec::new();
for field in fields {
let effective = effective_metas(&field.attrs, cfg, path)?;
if !effective.active {
continue;
}
if effective.markers.len() > 1 {
return Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
effective.markers[1].span(),
"duplicate outer #[pdb] attribute",
));
}
if let Some(meta) = effective.markers.first() {
if !owner_is_pdb_type {
return Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
meta.span(),
"field helper requires an outer PDB type",
));
}
let marker = parse_marker(marker_arguments(meta), MarkerTarget::Field(field)).map_err(
|error| {
Diagnostic::at(
DiagnosticCategory::Marker,
path,
error.span(),
error.to_string(),
)
},
)?;
let MarkerSchema::Field {
field_name,
rust_name,
read_only,
span,
} = marker
else {
unreachable!("field marker placement was validated")
};
selected.push(SelectedField {
location: location(span),
rust_name,
field_name,
visibility: field.vis.to_token_stream().to_string(),
attributes: approved_attributes(&effective, path)?,
ty: field.ty.to_token_stream().to_string(),
read_only,
});
}
}
Ok(selected)
}
fn validate_type_shape(
generics: &syn::Generics,
fields: &Fields,
effective: &super::predicate::EffectiveMetas,
path: &str,
) -> Result<(), Diagnostic> {
if !effective.markers.is_empty()
&& (!generics.params.is_empty() || generics.where_clause.is_some())
{
return Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
generics.span(),
"PDB-backed types cannot be generic or have where clauses",
));
}
if !effective.markers.is_empty() && matches!(fields, Fields::Unnamed(_)) {
return Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
fields.span(),
"PDB-backed types do not support tuple fields",
));
}
Ok(())
}
fn type_syntax(
visibility: &Visibility,
effective: &super::predicate::EffectiveMetas,
path: &str,
) -> Result<TypeSyntax, Diagnostic> {
Ok(TypeSyntax {
visibility: visibility.to_token_stream().to_string(),
attributes: approved_attributes(effective, path)?,
})
}
fn approved_attributes(
effective: &super::predicate::EffectiveMetas,
path: &str,
) -> Result<Vec<String>, Diagnostic> {
effective
.attributes
.iter()
.map(|attribute| {
let name = attribute
.path()
.get_ident()
.map(ToString::to_string)
.unwrap_or_default();
if name == "repr" {
return Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
attribute.span(),
"#[repr] conflicts with PDB-backed representation",
));
}
if matches!(
name.as_str(),
"doc" | "deprecated" | "allow" | "warn" | "deny" | "forbid"
) {
Ok(format!("#[{}]", attribute.to_token_stream()))
} else {
Err(Diagnostic::at(
DiagnosticCategory::Marker,
path,
attribute.span(),
format!("unsupported attribute on PDB-backed item: #[{name}]"),
))
}
})
.collect()
}
fn discovered_marker(
marker: MarkerSchema,
fields: Vec<SelectedField>,
syntax: TypeSyntax,
) -> DiscoveredItem {
match marker {
MarkerSchema::Compatibility { name, span } => {
discovered_item(span, DiscoveredItemKind::Compatibility { name })
}
MarkerSchema::Type {
type_name,
name,
kind,
span,
} => discovered_item(
span,
DiscoveredItemKind::Type {
rust_name: name,
type_name,
kind,
syntax,
fields,
},
),
MarkerSchema::Symbols { span } => discovered_item(
span,
DiscoveredItemKind::Symbols {
declarations: Vec::new(),
},
),
MarkerSchema::Image { .. } | MarkerSchema::Field { .. } => {
unreachable!("marker ownership was handled by its lexical owner")
}
}
}
fn discovered_item(span: Span, kind: DiscoveredItemKind) -> DiscoveredItem {
DiscoveredItem {
location: location(span),
kind,
}
}
fn location(span: Span) -> Location {
let start = span.start();
Location {
line: start.line,
column: start.column + 1,
}
}
fn item_attrs(item: &Item) -> &[Attribute] {
match item {
Item::Const(x) => &x.attrs,
Item::Enum(x) => &x.attrs,
Item::ExternCrate(x) => &x.attrs,
Item::Fn(x) => &x.attrs,
Item::ForeignMod(x) => &x.attrs,
Item::Impl(x) => &x.attrs,
Item::Macro(x) => &x.attrs,
Item::Mod(x) => &x.attrs,
Item::Static(x) => &x.attrs,
Item::Struct(x) => &x.attrs,
Item::Trait(x) => &x.attrs,
Item::TraitAlias(x) => &x.attrs,
Item::Type(x) => &x.attrs,
Item::Union(x) => &x.attrs,
Item::Use(x) => &x.attrs,
Item::Verbatim(_) => &[],
_ => &[],
}
}
fn is_non_discovery_attribute(attribute: &Attribute) -> bool {
!attribute.path().is_ident("cfg")
&& !attribute.path().is_ident("cfg_attr")
&& !attribute.path().is_ident("path")
&& attribute
.path()
.segments
.last()
.is_none_or(|segment| segment.ident != "pdb")
}
fn item_without_attrs(item: &Item) -> Item {
let mut item = item.clone();
match &mut item {
Item::Const(x) => x.attrs.retain(is_non_discovery_attribute),
Item::Enum(x) => x.attrs.retain(is_non_discovery_attribute),
Item::ExternCrate(x) => x.attrs.retain(is_non_discovery_attribute),
Item::Fn(x) => x.attrs.retain(is_non_discovery_attribute),
Item::ForeignMod(x) => x.attrs.retain(is_non_discovery_attribute),
Item::Impl(x) => x.attrs.retain(is_non_discovery_attribute),
Item::Macro(x) => x.attrs.retain(is_non_discovery_attribute),
Item::Mod(x) => x.attrs.retain(is_non_discovery_attribute),
Item::Static(x) => x.attrs.retain(is_non_discovery_attribute),
Item::Struct(x) => x.attrs.retain(is_non_discovery_attribute),
Item::Trait(x) => x.attrs.retain(is_non_discovery_attribute),
Item::TraitAlias(x) => x.attrs.retain(is_non_discovery_attribute),
Item::Type(x) => x.attrs.retain(is_non_discovery_attribute),
Item::Union(x) => x.attrs.retain(is_non_discovery_attribute),
Item::Use(x) => x.attrs.retain(is_non_discovery_attribute),
_ => {}
}
item
}