diff --git a/.github/workflows/bindgen.yml b/.github/workflows/bindgen.yml index 8faa4988ec..9a8b2bb00f 100644 --- a/.github/workflows/bindgen.yml +++ b/.github/workflows/bindgen.yml @@ -107,7 +107,6 @@ jobs: # `static` feature is not testable atm. feature_runtime: [0, 1] feature_extra_asserts: [0] - feature_testing_only_docs: [0] include: # Test with extra asserts + docs just with latest llvm versions to @@ -117,7 +116,6 @@ jobs: release_build: 0 no_default_features: 0 feature_extra_asserts: 1 - feature_testing_only_docs: 1 # FIXME: Seems installing multiarch packages fails: # @@ -132,7 +130,6 @@ jobs: # main_tests: 0 # release_build: 0 # feature_extra_asserts: 0 - # feature_testing_only_docs: 0 # Ensure stuff works on macos too - os: macos-latest @@ -140,7 +137,6 @@ jobs: release_build: 0 no_default_features: 0 feature_extra_asserts: 0 - feature_testing_only_docs: 0 steps: - uses: actions/checkout@v3 @@ -181,7 +177,6 @@ jobs: BINDGEN_RELEASE_BUILD: ${{matrix.release_build}} BINDGEN_FEATURE_RUNTIME: ${{matrix.feature_runtime}} BINDGEN_FEATURE_EXTRA_ASSERTS: ${{matrix.feature_extra_asserts}} - BINDGEN_FEATURE_TESTING_ONLY_DOCS: ${{matrix.feature_testing_only_docs}} BINDGEN_NO_DEFAULT_FEATURES: ${{matrix.no_default_features}} run: ./ci/test.sh diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6189619da8..127e5c5ef0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -79,14 +79,6 @@ versions of llvm, or specify the path of the desired libclang explicitly: $ export LIBCLANG_PATH=path/to/clang-9.0/lib ``` -Additionally, you may want to build and test with the `testing_only_docs` -feature to ensure that you aren't forgetting to document types and functions. CI -will catch it if you forget, but the turn around will be a lot slower ;) - -``` -$ cargo build --features testing_only_docs -``` - ## Testing ### Overview diff --git a/bindgen-integration/Cargo.toml b/bindgen-integration/Cargo.toml index 60f0426a76..ac1b03eeaa 100644 --- a/bindgen-integration/Cargo.toml +++ b/bindgen-integration/Cargo.toml @@ -14,7 +14,6 @@ cc = "1.0" static = ["bindgen/static"] runtime = ["bindgen/runtime"] -testing_only_docs = ["bindgen/testing_only_docs"] testing_only_extra_assertions = ["bindgen/testing_only_extra_assertions"] testing_only_libclang_9 = ["bindgen/testing_only_libclang_9"] testing_only_libclang_5 = ["bindgen/testing_only_libclang_5"] diff --git a/bindgen-tests/Cargo.toml b/bindgen-tests/Cargo.toml index 6df84e8e9b..ace5b3810a 100644 --- a/bindgen-tests/Cargo.toml +++ b/bindgen-tests/Cargo.toml @@ -17,7 +17,6 @@ static = ["bindgen/static"] runtime = ["bindgen/runtime"] which-rustfmt = ["bindgen/which-rustfmt"] -testing_only_docs = ["bindgen/testing_only_docs"] testing_only_extra_assertions = ["bindgen/testing_only_extra_assertions"] testing_only_libclang_9 = ["bindgen/testing_only_libclang_9"] testing_only_libclang_5 = ["bindgen/testing_only_libclang_5"] diff --git a/bindgen/Cargo.toml b/bindgen/Cargo.toml index c2e8543bb0..e1bdc3cbca 100644 --- a/bindgen/Cargo.toml +++ b/bindgen/Cargo.toml @@ -52,7 +52,6 @@ experimental = [] # These features only exist for CI testing -- don't use them if you're not hacking # on bindgen! -testing_only_docs = [] testing_only_extra_assertions = [] testing_only_libclang_9 = [] testing_only_libclang_5 = [] diff --git a/bindgen/callbacks.rs b/bindgen/callbacks.rs index dc20e2581e..b1339e4663 100644 --- a/bindgen/callbacks.rs +++ b/bindgen/callbacks.rs @@ -146,7 +146,7 @@ pub enum TypeKind { Union, } -/// An struct providing information about the item being passed to `ParseCallbacks::generated_name_override`. +/// A struct providing information about the item being passed to [`ParseCallbacks::generated_name_override`]. #[non_exhaustive] pub struct ItemInfo<'a> { /// The name of the item diff --git a/bindgen/clang.rs b/bindgen/clang.rs index 32a25449bc..62bf84f6d3 100644 --- a/bindgen/clang.rs +++ b/bindgen/clang.rs @@ -2,6 +2,7 @@ //! `clang_sys` module. #![allow(non_upper_case_globals, dead_code)] +#![deny(clippy::missing_docs_in_private_items)] use crate::ir::context::BindgenContext; use clang_sys::*; @@ -16,7 +17,7 @@ use std::{mem, ptr, slice}; /// /// Values of this type can be used to check for different attributes using the `has_attrs` /// function. -pub struct Attribute { +pub(crate) struct Attribute { name: &'static [u8], kind: Option, token_kind: CXTokenKind, @@ -24,7 +25,7 @@ pub struct Attribute { impl Attribute { /// A `warn_unused_result` attribute. - pub const MUST_USE: Self = Self { + pub(crate) const MUST_USE: Self = Self { name: b"warn_unused_result", // FIXME(emilio): clang-sys doesn't expose `CXCursor_WarnUnusedResultAttr` (from clang 9). kind: Some(440), @@ -32,14 +33,14 @@ impl Attribute { }; /// A `_Noreturn` attribute. - pub const NO_RETURN: Self = Self { + pub(crate) const NO_RETURN: Self = Self { name: b"_Noreturn", kind: None, token_kind: CXToken_Keyword, }; /// A `[[noreturn]]` attribute. - pub const NO_RETURN_CPP: Self = Self { + pub(crate) const NO_RETURN_CPP: Self = Self { name: b"noreturn", kind: None, token_kind: CXToken_Identifier, @@ -50,7 +51,7 @@ impl Attribute { /// /// We call the AST node pointed to by the cursor the cursor's "referent". #[derive(Copy, Clone)] -pub struct Cursor { +pub(crate) struct Cursor { x: CXCursor, } @@ -72,7 +73,7 @@ impl Cursor { /// available. /// /// The USR can be used to compare entities across translation units. - pub fn usr(&self) -> Option { + pub(crate) fn usr(&self) -> Option { let s = unsafe { cxstring_into_string(clang_getCursorUSR(self.x)) }; if s.is_empty() { None @@ -82,17 +83,17 @@ impl Cursor { } /// Is this cursor's referent a declaration? - pub fn is_declaration(&self) -> bool { + pub(crate) fn is_declaration(&self) -> bool { unsafe { clang_isDeclaration(self.kind()) != 0 } } /// Is this cursor's referent an anonymous record or so? - pub fn is_anonymous(&self) -> bool { + pub(crate) fn is_anonymous(&self) -> bool { unsafe { clang_Cursor_isAnonymous(self.x) != 0 } } /// Get this cursor's referent's spelling. - pub fn spelling(&self) -> String { + pub(crate) fn spelling(&self) -> String { unsafe { cxstring_into_string(clang_getCursorSpelling(self.x)) } } @@ -100,18 +101,18 @@ impl Cursor { /// /// This is not necessarily a valid identifier. It includes extra /// information, such as parameters for a function, etc. - pub fn display_name(&self) -> String { + pub(crate) fn display_name(&self) -> String { unsafe { cxstring_into_string(clang_getCursorDisplayName(self.x)) } } /// Get the mangled name of this cursor's referent. - pub fn mangling(&self) -> String { + pub(crate) fn mangling(&self) -> String { unsafe { cxstring_into_string(clang_Cursor_getMangling(self.x)) } } /// Gets the C++ manglings for this cursor, or an error if the manglings /// are not available. - pub fn cxx_manglings(&self) -> Result, ()> { + pub(crate) fn cxx_manglings(&self) -> Result, ()> { use clang_sys::*; unsafe { let manglings = clang_Cursor_getCXXManglings(self.x); @@ -131,7 +132,7 @@ impl Cursor { } /// Returns whether the cursor refers to a built-in definition. - pub fn is_builtin(&self) -> bool { + pub(crate) fn is_builtin(&self) -> bool { let (file, _, _, _) = self.location().location(); file.name().is_none() } @@ -153,7 +154,7 @@ impl Cursor { /// /// void Foo::method() { /* ... */ } /// ``` - pub fn lexical_parent(&self) -> Cursor { + pub(crate) fn lexical_parent(&self) -> Cursor { unsafe { Cursor { x: clang_getCursorLexicalParent(self.x), @@ -165,7 +166,7 @@ impl Cursor { /// /// See documentation for `lexical_parent` for details on semantic vs /// lexical parents. - pub fn fallible_semantic_parent(&self) -> Option { + pub(crate) fn fallible_semantic_parent(&self) -> Option { let sp = unsafe { Cursor { x: clang_getCursorSemanticParent(self.x), @@ -181,7 +182,7 @@ impl Cursor { /// /// See documentation for `lexical_parent` for details on semantic vs /// lexical parents. - pub fn semantic_parent(&self) -> Cursor { + pub(crate) fn semantic_parent(&self) -> Cursor { self.fallible_semantic_parent().unwrap() } @@ -191,7 +192,7 @@ impl Cursor { /// /// NOTE: This may not return `Some` for partial template specializations, /// see #193 and #194. - pub fn num_template_args(&self) -> Option { + pub(crate) fn num_template_args(&self) -> Option { // XXX: `clang_Type_getNumTemplateArguments` is sort of reliable, while // `clang_Cursor_getNumTemplateArguments` is totally unreliable. // Therefore, try former first, and only fallback to the latter if we @@ -225,7 +226,7 @@ impl Cursor { /// bindgen assumes there will only be one of them alive at a time, and /// disposes it on drop. That can change if this would be required, but I /// think we can survive fine without it. - pub fn translation_unit(&self) -> Cursor { + pub(crate) fn translation_unit(&self) -> Cursor { assert!(self.is_valid()); unsafe { let tu = clang_Cursor_getTranslationUnit(self.x); @@ -238,7 +239,7 @@ impl Cursor { } /// Is the referent a top level construct? - pub fn is_toplevel(&self) -> bool { + pub(crate) fn is_toplevel(&self) -> bool { let mut semantic_parent = self.fallible_semantic_parent(); while semantic_parent.is_some() && @@ -259,7 +260,7 @@ impl Cursor { /// There are a few kinds of types that we need to treat specially, mainly /// not tracking the type declaration but the location of the cursor, given /// clang doesn't expose a proper declaration for these types. - pub fn is_template_like(&self) -> bool { + pub(crate) fn is_template_like(&self) -> bool { matches!( self.kind(), CXCursor_ClassTemplate | @@ -269,28 +270,28 @@ impl Cursor { } /// Is this Cursor pointing to a function-like macro definition? - pub fn is_macro_function_like(&self) -> bool { + pub(crate) fn is_macro_function_like(&self) -> bool { unsafe { clang_Cursor_isMacroFunctionLike(self.x) != 0 } } /// Get the kind of referent this cursor is pointing to. - pub fn kind(&self) -> CXCursorKind { + pub(crate) fn kind(&self) -> CXCursorKind { self.x.kind } /// Returns true if the cursor is a definition - pub fn is_definition(&self) -> bool { + pub(crate) fn is_definition(&self) -> bool { unsafe { clang_isCursorDefinition(self.x) != 0 } } /// Is the referent a template specialization? - pub fn is_template_specialization(&self) -> bool { + pub(crate) fn is_template_specialization(&self) -> bool { self.specialized().is_some() } /// Is the referent a fully specialized template specialization without any /// remaining free template arguments? - pub fn is_fully_specialized_template(&self) -> bool { + pub(crate) fn is_fully_specialized_template(&self) -> bool { self.is_template_specialization() && self.kind() != CXCursor_ClassTemplatePartialSpecialization && self.num_template_args().unwrap_or(0) > 0 @@ -298,7 +299,7 @@ impl Cursor { /// Is the referent a template specialization that still has remaining free /// template arguments? - pub fn is_in_non_fully_specialized_template(&self) -> bool { + pub(crate) fn is_in_non_fully_specialized_template(&self) -> bool { if self.is_toplevel() { return false; } @@ -316,7 +317,7 @@ impl Cursor { } /// Is the referent any kind of template parameter? - pub fn is_template_parameter(&self) -> bool { + pub(crate) fn is_template_parameter(&self) -> bool { matches!( self.kind(), CXCursor_TemplateTemplateParameter | @@ -326,7 +327,7 @@ impl Cursor { } /// Does the referent's type or value depend on a template parameter? - pub fn is_dependent_on_template_parameter(&self) -> bool { + pub(crate) fn is_dependent_on_template_parameter(&self) -> bool { fn visitor( found_template_parameter: &mut bool, cur: Cursor, @@ -366,12 +367,12 @@ impl Cursor { } /// Is this cursor pointing a valid referent? - pub fn is_valid(&self) -> bool { + pub(crate) fn is_valid(&self) -> bool { unsafe { clang_isInvalid(self.kind()) == 0 } } /// Get the source location for the referent. - pub fn location(&self) -> SourceLocation { + pub(crate) fn location(&self) -> SourceLocation { unsafe { SourceLocation { x: clang_getCursorLocation(self.x), @@ -380,12 +381,12 @@ impl Cursor { } /// Get the source location range for the referent. - pub fn extent(&self) -> CXSourceRange { + pub(crate) fn extent(&self) -> CXSourceRange { unsafe { clang_getCursorExtent(self.x) } } /// Get the raw declaration comment for this referent, if one exists. - pub fn raw_comment(&self) -> Option { + pub(crate) fn raw_comment(&self) -> Option { let s = unsafe { cxstring_into_string(clang_Cursor_getRawCommentText(self.x)) }; @@ -397,7 +398,7 @@ impl Cursor { } /// Get the referent's parsed comment. - pub fn comment(&self) -> Comment { + pub(crate) fn comment(&self) -> Comment { unsafe { Comment { x: clang_Cursor_getParsedComment(self.x), @@ -406,7 +407,7 @@ impl Cursor { } /// Get the referent's type. - pub fn cur_type(&self) -> Type { + pub(crate) fn cur_type(&self) -> Type { unsafe { Type { x: clang_getCursorType(self.x), @@ -417,7 +418,7 @@ impl Cursor { /// Given that this cursor's referent is a reference to another type, or is /// a declaration, get the cursor pointing to the referenced type or type of /// the declared thing. - pub fn definition(&self) -> Option { + pub(crate) fn definition(&self) -> Option { unsafe { let ret = Cursor { x: clang_getCursorDefinition(self.x), @@ -433,7 +434,7 @@ impl Cursor { /// Given that this cursor's referent is reference type, get the cursor /// pointing to the referenced type. - pub fn referenced(&self) -> Option { + pub(crate) fn referenced(&self) -> Option { unsafe { let ret = Cursor { x: clang_getCursorReferenced(self.x), @@ -452,7 +453,7 @@ impl Cursor { /// Many types can be declared multiple times before finally being properly /// defined. This method allows us to get the canonical cursor for the /// referent type. - pub fn canonical(&self) -> Cursor { + pub(crate) fn canonical(&self) -> Cursor { unsafe { Cursor { x: clang_getCanonicalCursor(self.x), @@ -463,7 +464,7 @@ impl Cursor { /// Given that this cursor points to either a template specialization or a /// template instantiation, get a cursor pointing to the template definition /// that is being specialized. - pub fn specialized(&self) -> Option { + pub(crate) fn specialized(&self) -> Option { unsafe { let ret = Cursor { x: clang_getSpecializedCursorTemplate(self.x), @@ -478,14 +479,14 @@ impl Cursor { /// Assuming that this cursor's referent is a template declaration, get the /// kind of cursor that would be generated for its specializations. - pub fn template_kind(&self) -> CXCursorKind { + pub(crate) fn template_kind(&self) -> CXCursorKind { unsafe { clang_getTemplateCursorKind(self.x) } } /// Traverse this cursor's referent and its children. /// /// Call the given function on each AST node traversed. - pub fn visit(&self, mut visitor: Visitor) + pub(crate) fn visit(&self, mut visitor: Visitor) where Visitor: FnMut(Cursor) -> CXChildVisitResult, { @@ -496,7 +497,7 @@ impl Cursor { } /// Collect all of this cursor's children into a vec and return them. - pub fn collect_children(&self) -> Vec { + pub(crate) fn collect_children(&self) -> Vec { let mut children = vec![]; self.visit(|c| { children.push(c); @@ -506,7 +507,7 @@ impl Cursor { } /// Does this cursor have any children? - pub fn has_children(&self) -> bool { + pub(crate) fn has_children(&self) -> bool { let mut has_children = false; self.visit(|_| { has_children = true; @@ -516,7 +517,7 @@ impl Cursor { } /// Does this cursor have at least `n` children? - pub fn has_at_least_num_children(&self, n: usize) -> bool { + pub(crate) fn has_at_least_num_children(&self, n: usize) -> bool { assert!(n > 0); let mut num_left = n; self.visit(|_| { @@ -533,7 +534,7 @@ impl Cursor { /// Returns whether the given location contains a cursor with the given /// kind in the first level of nesting underneath (doesn't look /// recursively). - pub fn contains_cursor(&self, kind: CXCursorKind) -> bool { + pub(crate) fn contains_cursor(&self, kind: CXCursorKind) -> bool { let mut found = false; self.visit(|c| { @@ -549,17 +550,17 @@ impl Cursor { } /// Is the referent an inlined function? - pub fn is_inlined_function(&self) -> bool { + pub(crate) fn is_inlined_function(&self) -> bool { unsafe { clang_Cursor_isFunctionInlined(self.x) != 0 } } /// Is the referent a defaulted function? - pub fn is_defaulted_function(&self) -> bool { + pub(crate) fn is_defaulted_function(&self) -> bool { unsafe { clang_CXXMethod_isDefaulted(self.x) != 0 } } /// Is the referent a deleted function? - pub fn is_deleted_function(&self) -> bool { + pub(crate) fn is_deleted_function(&self) -> bool { // Unfortunately, libclang doesn't yet have an API for checking if a // member function is deleted, but the following should be a good // enough approximation. @@ -575,13 +576,13 @@ impl Cursor { } /// Is the referent a bit field declaration? - pub fn is_bit_field(&self) -> bool { + pub(crate) fn is_bit_field(&self) -> bool { unsafe { clang_Cursor_isBitField(self.x) != 0 } } /// Get a cursor to the bit field's width expression, or `None` if it's not /// a bit field. - pub fn bit_width_expr(&self) -> Option { + pub(crate) fn bit_width_expr(&self) -> Option { if !self.is_bit_field() { return None; } @@ -605,7 +606,7 @@ impl Cursor { /// Get the width of this cursor's referent bit field, or `None` if the /// referent is not a bit field or if the width could not be evaluated. - pub fn bit_width(&self) -> Option { + pub(crate) fn bit_width(&self) -> Option { // It is not safe to check the bit width without ensuring it doesn't // depend on a template parameter. See // https://github.com/rust-lang/rust-bindgen/issues/2239 @@ -625,7 +626,7 @@ impl Cursor { /// Get the integer representation type used to hold this cursor's referent /// enum type. - pub fn enum_type(&self) -> Option { + pub(crate) fn enum_type(&self) -> Option { unsafe { let t = Type { x: clang_getEnumDeclIntegerType(self.x), @@ -641,7 +642,7 @@ impl Cursor { /// Get the boolean constant value for this cursor's enum variant referent. /// /// Returns None if the cursor's referent is not an enum variant. - pub fn enum_val_boolean(&self) -> Option { + pub(crate) fn enum_val_boolean(&self) -> Option { unsafe { if self.kind() == CXCursor_EnumConstantDecl { Some(clang_getEnumConstantDeclValue(self.x) != 0) @@ -654,7 +655,7 @@ impl Cursor { /// Get the signed constant value for this cursor's enum variant referent. /// /// Returns None if the cursor's referent is not an enum variant. - pub fn enum_val_signed(&self) -> Option { + pub(crate) fn enum_val_signed(&self) -> Option { unsafe { if self.kind() == CXCursor_EnumConstantDecl { #[allow(clippy::unnecessary_cast)] @@ -668,7 +669,7 @@ impl Cursor { /// Get the unsigned constant value for this cursor's enum variant referent. /// /// Returns None if the cursor's referent is not an enum variant. - pub fn enum_val_unsigned(&self) -> Option { + pub(crate) fn enum_val_unsigned(&self) -> Option { unsafe { if self.kind() == CXCursor_EnumConstantDecl { #[allow(clippy::unnecessary_cast)] @@ -680,7 +681,7 @@ impl Cursor { } /// Does this cursor have the given attributes? - pub fn has_attrs( + pub(crate) fn has_attrs( &self, attrs: &[Attribute; N], ) -> [bool; N] { @@ -718,7 +719,7 @@ impl Cursor { /// Given that this cursor's referent is a `typedef`, get the `Type` that is /// being aliased. - pub fn typedef_type(&self) -> Option { + pub(crate) fn typedef_type(&self) -> Option { let inner = Type { x: unsafe { clang_getTypedefDeclUnderlyingType(self.x) }, }; @@ -733,12 +734,12 @@ impl Cursor { /// Get the linkage kind for this cursor's referent. /// /// This only applies to functions and variables. - pub fn linkage(&self) -> CXLinkageKind { + pub(crate) fn linkage(&self) -> CXLinkageKind { unsafe { clang_getCursorLinkage(self.x) } } /// Get the visibility of this cursor's referent. - pub fn visibility(&self) -> CXVisibilityKind { + pub(crate) fn visibility(&self) -> CXVisibilityKind { unsafe { clang_getCursorVisibility(self.x) } } @@ -747,7 +748,7 @@ impl Cursor { /// /// Returns None if the cursor's referent is not a function/method call or /// declaration. - pub fn args(&self) -> Option> { + pub(crate) fn args(&self) -> Option> { // match self.kind() { // CXCursor_FunctionDecl | // CXCursor_CXXMethod => { @@ -765,7 +766,7 @@ impl Cursor { /// /// Returns Err if the cursor's referent is not a function/method call or /// declaration. - pub fn num_args(&self) -> Result { + pub(crate) fn num_args(&self) -> Result { unsafe { let w = clang_Cursor_getNumArguments(self.x); if w == -1 { @@ -777,7 +778,7 @@ impl Cursor { } /// Get the access specifier for this cursor's referent. - pub fn access_specifier(&self) -> CX_CXXAccessSpecifier { + pub(crate) fn access_specifier(&self) -> CX_CXXAccessSpecifier { unsafe { clang_getCXXAccessSpecifier(self.x) } } @@ -785,19 +786,19 @@ impl Cursor { /// /// Returns true if self.access_specifier() is `CX_CXXPublic` or /// `CX_CXXInvalidAccessSpecifier`. - pub fn public_accessible(&self) -> bool { + pub(crate) fn public_accessible(&self) -> bool { let access = self.access_specifier(); access == CX_CXXPublic || access == CX_CXXInvalidAccessSpecifier } /// Is this cursor's referent a field declaration that is marked as /// `mutable`? - pub fn is_mutable_field(&self) -> bool { + pub(crate) fn is_mutable_field(&self) -> bool { unsafe { clang_CXXField_isMutable(self.x) != 0 } } /// Get the offset of the field represented by the Cursor. - pub fn offset_of_field(&self) -> Result { + pub(crate) fn offset_of_field(&self) -> Result { let offset = unsafe { clang_Cursor_getOffsetOfField(self.x) }; if offset < 0 { @@ -808,37 +809,37 @@ impl Cursor { } /// Is this cursor's referent a member function that is declared `static`? - pub fn method_is_static(&self) -> bool { + pub(crate) fn method_is_static(&self) -> bool { unsafe { clang_CXXMethod_isStatic(self.x) != 0 } } /// Is this cursor's referent a member function that is declared `const`? - pub fn method_is_const(&self) -> bool { + pub(crate) fn method_is_const(&self) -> bool { unsafe { clang_CXXMethod_isConst(self.x) != 0 } } /// Is this cursor's referent a member function that is virtual? - pub fn method_is_virtual(&self) -> bool { + pub(crate) fn method_is_virtual(&self) -> bool { unsafe { clang_CXXMethod_isVirtual(self.x) != 0 } } /// Is this cursor's referent a member function that is pure virtual? - pub fn method_is_pure_virtual(&self) -> bool { + pub(crate) fn method_is_pure_virtual(&self) -> bool { unsafe { clang_CXXMethod_isPureVirtual(self.x) != 0 } } /// Is this cursor's referent a struct or class with virtual members? - pub fn is_virtual_base(&self) -> bool { + pub(crate) fn is_virtual_base(&self) -> bool { unsafe { clang_isVirtualBase(self.x) != 0 } } /// Try to evaluate this cursor. - pub fn evaluate(&self) -> Option { + pub(crate) fn evaluate(&self) -> Option { EvalResult::new(*self) } /// Return the result type for this cursor - pub fn ret_type(&self) -> Option { + pub(crate) fn ret_type(&self) -> Option { let rt = Type { x: unsafe { clang_getCursorResultType(self.x) }, }; @@ -850,12 +851,12 @@ impl Cursor { } /// Gets the tokens that correspond to that cursor. - pub fn tokens(&self) -> RawTokens { + pub(crate) fn tokens(&self) -> RawTokens { RawTokens::new(self) } /// Gets the tokens that correspond to that cursor as `cexpr` tokens. - pub fn cexpr_tokens(self) -> Vec { + pub(crate) fn cexpr_tokens(self) -> Vec { self.tokens() .iter() .filter_map(|token| token.as_cexpr_token()) @@ -865,7 +866,7 @@ impl Cursor { /// Obtain the real path name of a cursor of InclusionDirective kind. /// /// Returns None if the cursor does not include a file, otherwise the file's full name - pub fn get_included_file_name(&self) -> Option { + pub(crate) fn get_included_file_name(&self) -> Option { let file = unsafe { clang_sys::clang_getIncludedFile(self.x) }; if file.is_null() { None @@ -878,7 +879,7 @@ impl Cursor { } /// A struct that owns the tokenizer result from a given cursor. -pub struct RawTokens<'a> { +pub(crate) struct RawTokens<'a> { cursor: &'a Cursor, tu: CXTranslationUnit, tokens: *mut CXToken, @@ -908,7 +909,7 @@ impl<'a> RawTokens<'a> { } /// Get an iterator over these tokens. - pub fn iter(&self) -> ClangTokenIterator { + pub(crate) fn iter(&self) -> ClangTokenIterator { ClangTokenIterator { tu: self.tu, raw: self.as_slice().iter(), @@ -934,19 +935,19 @@ impl<'a> Drop for RawTokens<'a> { /// slightly more convenient version of `CXToken` which owns the spelling /// string and extent. #[derive(Debug)] -pub struct ClangToken { +pub(crate) struct ClangToken { spelling: CXString, /// The extent of the token. This is the same as the relevant member from /// `CXToken`. - pub extent: CXSourceRange, + pub(crate) extent: CXSourceRange, /// The kind of the token. This is the same as the relevant member from /// `CXToken`. - pub kind: CXTokenKind, + pub(crate) kind: CXTokenKind, } impl ClangToken { /// Get the token spelling, without being converted to utf-8. - pub fn spelling(&self) -> &[u8] { + pub(crate) fn spelling(&self) -> &[u8] { let c_str = unsafe { CStr::from_ptr(clang_getCString(self.spelling) as *const _) }; @@ -954,7 +955,7 @@ impl ClangToken { } /// Converts a ClangToken to a `cexpr` token if possible. - pub fn as_cexpr_token(&self) -> Option { + pub(crate) fn as_cexpr_token(&self) -> Option { use cexpr::token; let kind = match self.kind { @@ -985,7 +986,7 @@ impl Drop for ClangToken { } /// An iterator over a set of Tokens. -pub struct ClangTokenIterator<'a> { +pub(crate) struct ClangTokenIterator<'a> { tu: CXTranslationUnit, raw: slice::Iter<'a, CXToken>, } @@ -1010,7 +1011,7 @@ impl<'a> Iterator for ClangTokenIterator<'a> { /// Checks whether the name looks like an identifier, i.e. is alphanumeric /// (including '_') and does not start with a digit. -pub fn is_valid_identifier(name: &str) -> bool { +pub(crate) fn is_valid_identifier(name: &str) -> bool { let mut chars = name.chars(); let first_valid = chars .next() @@ -1050,7 +1051,7 @@ impl Hash for Cursor { /// The type of a node in clang's AST. #[derive(Clone, Copy)] -pub struct Type { +pub(crate) struct Type { x: CXType, } @@ -1078,7 +1079,7 @@ impl fmt::Debug for Type { /// An error about the layout of a struct, class, or type. #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] -pub enum LayoutError { +pub(crate) enum LayoutError { /// Asked for the layout of an invalid type. Invalid, /// Asked for the layout of an incomplete type. @@ -1111,12 +1112,12 @@ impl ::std::convert::From for LayoutError { impl Type { /// Get this type's kind. - pub fn kind(&self) -> CXTypeKind { + pub(crate) fn kind(&self) -> CXTypeKind { self.x.kind } /// Get a cursor pointing to this type's declaration. - pub fn declaration(&self) -> Cursor { + pub(crate) fn declaration(&self) -> Cursor { unsafe { Cursor { x: clang_getTypeDeclaration(self.x), @@ -1125,7 +1126,7 @@ impl Type { } /// Get the canonical declaration of this type, if it is available. - pub fn canonical_declaration( + pub(crate) fn canonical_declaration( &self, location: Option<&Cursor>, ) -> Option { @@ -1151,7 +1152,7 @@ impl Type { } /// Get a raw display name for this type. - pub fn spelling(&self) -> String { + pub(crate) fn spelling(&self) -> String { let s = unsafe { cxstring_into_string(clang_getTypeSpelling(self.x)) }; // Clang 5.0 introduced changes in the spelling API so it returned the // full qualified name. Let's undo that here. @@ -1165,7 +1166,7 @@ impl Type { } /// Is this type const qualified? - pub fn is_const(&self) -> bool { + pub(crate) fn is_const(&self) -> bool { unsafe { clang_isConstQualifiedType(self.x) != 0 } } @@ -1203,7 +1204,7 @@ impl Type { /// What is the size of this type? Paper over invalid types by returning `0` /// for them. - pub fn size(&self, ctx: &BindgenContext) -> usize { + pub(crate) fn size(&self, ctx: &BindgenContext) -> usize { let val = self.clang_size_of(ctx); if val < 0 { 0 @@ -1213,7 +1214,7 @@ impl Type { } /// What is the size of this type? - pub fn fallible_size( + pub(crate) fn fallible_size( &self, ctx: &BindgenContext, ) -> Result { @@ -1227,7 +1228,7 @@ impl Type { /// What is the alignment of this type? Paper over invalid types by /// returning `0`. - pub fn align(&self, ctx: &BindgenContext) -> usize { + pub(crate) fn align(&self, ctx: &BindgenContext) -> usize { let val = self.clang_align_of(ctx); if val < 0 { 0 @@ -1237,7 +1238,7 @@ impl Type { } /// What is the alignment of this type? - pub fn fallible_align( + pub(crate) fn fallible_align( &self, ctx: &BindgenContext, ) -> Result { @@ -1251,7 +1252,7 @@ impl Type { /// Get the layout for this type, or an error describing why it does not /// have a valid layout. - pub fn fallible_layout( + pub(crate) fn fallible_layout( &self, ctx: &BindgenContext, ) -> Result { @@ -1263,7 +1264,7 @@ impl Type { /// Get the number of template arguments this type has, or `None` if it is /// not some kind of template. - pub fn num_template_args(&self) -> Option { + pub(crate) fn num_template_args(&self) -> Option { let n = unsafe { clang_Type_getNumTemplateArguments(self.x) }; if n >= 0 { Some(n as u32) @@ -1275,7 +1276,7 @@ impl Type { /// If this type is a class template specialization, return its /// template arguments. Otherwise, return None. - pub fn template_args(&self) -> Option { + pub(crate) fn template_args(&self) -> Option { self.num_template_args().map(|n| TypeTemplateArgIterator { x: self.x, length: n, @@ -1286,7 +1287,7 @@ impl Type { /// Given that this type is a function prototype, return the types of its parameters. /// /// Returns None if the type is not a function prototype. - pub fn args(&self) -> Option> { + pub(crate) fn args(&self) -> Option> { self.num_args().ok().map(|num| { (0..num) .map(|i| Type { @@ -1299,7 +1300,7 @@ impl Type { /// Given that this type is a function prototype, return the number of arguments it takes. /// /// Returns Err if the type is not a function prototype. - pub fn num_args(&self) -> Result { + pub(crate) fn num_args(&self) -> Result { unsafe { let w = clang_getNumArgTypes(self.x); if w == -1 { @@ -1312,7 +1313,7 @@ impl Type { /// Given that this type is a pointer type, return the type that it points /// to. - pub fn pointee_type(&self) -> Option { + pub(crate) fn pointee_type(&self) -> Option { match self.kind() { CXType_Pointer | CXType_RValueReference | @@ -1332,7 +1333,7 @@ impl Type { /// Given that this type is an array, vector, or complex type, return the /// type of its elements. - pub fn elem_type(&self) -> Option { + pub(crate) fn elem_type(&self) -> Option { let current_type = Type { x: unsafe { clang_getElementType(self.x) }, }; @@ -1345,7 +1346,7 @@ impl Type { /// Given that this type is an array or vector type, return its number of /// elements. - pub fn num_elements(&self) -> Option { + pub(crate) fn num_elements(&self) -> Option { let num_elements_returned = unsafe { clang_getNumElements(self.x) }; if num_elements_returned != -1 { Some(num_elements_returned as usize) @@ -1356,7 +1357,7 @@ impl Type { /// Get the canonical version of this type. This sees through `typedef`s and /// aliases to get the underlying, canonical type. - pub fn canonical_type(&self) -> Type { + pub(crate) fn canonical_type(&self) -> Type { unsafe { Type { x: clang_getCanonicalType(self.x), @@ -1365,13 +1366,13 @@ impl Type { } /// Is this type a variadic function type? - pub fn is_variadic(&self) -> bool { + pub(crate) fn is_variadic(&self) -> bool { unsafe { clang_isFunctionTypeVariadic(self.x) != 0 } } /// Given that this type is a function type, get the type of its return /// value. - pub fn ret_type(&self) -> Option { + pub(crate) fn ret_type(&self) -> Option { let rt = Type { x: unsafe { clang_getResultType(self.x) }, }; @@ -1384,13 +1385,13 @@ impl Type { /// Given that this type is a function type, get its calling convention. If /// this is not a function type, `CXCallingConv_Invalid` is returned. - pub fn call_conv(&self) -> CXCallingConv { + pub(crate) fn call_conv(&self) -> CXCallingConv { unsafe { clang_getFunctionTypeCallingConv(self.x) } } /// For elaborated types (types which use `class`, `struct`, or `union` to /// disambiguate types from local bindings), get the underlying type. - pub fn named(&self) -> Type { + pub(crate) fn named(&self) -> Type { unsafe { Type { x: clang_Type_getNamedType(self.x), @@ -1399,17 +1400,17 @@ impl Type { } /// Is this a valid type? - pub fn is_valid(&self) -> bool { + pub(crate) fn is_valid(&self) -> bool { self.kind() != CXType_Invalid } /// Is this a valid and exposed type? - pub fn is_valid_and_exposed(&self) -> bool { + pub(crate) fn is_valid_and_exposed(&self) -> bool { self.is_valid() && self.kind() != CXType_Unexposed } /// Is this type a fully instantiated template? - pub fn is_fully_instantiated_template(&self) -> bool { + pub(crate) fn is_fully_instantiated_template(&self) -> bool { // Yep, the spelling of this containing type-parameter is extremely // nasty... But can happen in . Unfortunately I couldn't // reduce it enough :( @@ -1431,7 +1432,7 @@ impl Type { /// typename T::Associated member; /// }; /// ``` - pub fn is_associated_type(&self) -> bool { + pub(crate) fn is_associated_type(&self) -> bool { // This is terrible :( fn hacky_parse_associated_type>(spelling: S) -> bool { lazy_static! { @@ -1457,22 +1458,22 @@ impl Type { /// cursor match up in a canonical declaration relationship, and it simply /// cannot be otherwise. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct CanonicalTypeDeclaration(Type, Cursor); +pub(crate) struct CanonicalTypeDeclaration(Type, Cursor); impl CanonicalTypeDeclaration { /// Get the type. - pub fn ty(&self) -> &Type { + pub(crate) fn ty(&self) -> &Type { &self.0 } /// Get the type's canonical declaration cursor. - pub fn cursor(&self) -> &Cursor { + pub(crate) fn cursor(&self) -> &Cursor { &self.1 } } /// An iterator for a type's template arguments. -pub struct TypeTemplateArgIterator { +pub(crate) struct TypeTemplateArgIterator { x: CXType, length: u32, index: u32, @@ -1502,14 +1503,14 @@ impl ExactSizeIterator for TypeTemplateArgIterator { /// A `SourceLocation` is a file, line, column, and byte offset location for /// some source text. -pub struct SourceLocation { +pub(crate) struct SourceLocation { x: CXSourceLocation, } impl SourceLocation { /// Get the (file, line, column, byte offset) tuple for this source /// location. - pub fn location(&self) -> (File, usize, usize, usize) { + pub(crate) fn location(&self) -> (File, usize, usize, usize) { unsafe { let mut file = mem::zeroed(); let mut line = 0; @@ -1543,18 +1544,18 @@ impl fmt::Debug for SourceLocation { /// A comment in the source text. /// /// Comments are sort of parsed by Clang, and have a tree structure. -pub struct Comment { +pub(crate) struct Comment { x: CXComment, } impl Comment { /// What kind of comment is this? - pub fn kind(&self) -> CXCommentKind { + pub(crate) fn kind(&self) -> CXCommentKind { unsafe { clang_Comment_getKind(self.x) } } /// Get this comment's children comment - pub fn get_children(&self) -> CommentChildrenIterator { + pub(crate) fn get_children(&self) -> CommentChildrenIterator { CommentChildrenIterator { parent: self.x, length: unsafe { clang_Comment_getNumChildren(self.x) }, @@ -1564,12 +1565,12 @@ impl Comment { /// Given that this comment is the start or end of an HTML tag, get its tag /// name. - pub fn get_tag_name(&self) -> String { + pub(crate) fn get_tag_name(&self) -> String { unsafe { cxstring_into_string(clang_HTMLTagComment_getTagName(self.x)) } } /// Given that this comment is an HTML start tag, get its attributes. - pub fn get_tag_attrs(&self) -> CommentAttributesIterator { + pub(crate) fn get_tag_attrs(&self) -> CommentAttributesIterator { CommentAttributesIterator { x: self.x, length: unsafe { clang_HTMLStartTag_getNumAttrs(self.x) }, @@ -1579,7 +1580,7 @@ impl Comment { } /// An iterator for a comment's children -pub struct CommentChildrenIterator { +pub(crate) struct CommentChildrenIterator { parent: CXComment, length: c_uint, index: c_uint, @@ -1601,15 +1602,15 @@ impl Iterator for CommentChildrenIterator { } /// An HTML start tag comment attribute -pub struct CommentAttribute { +pub(crate) struct CommentAttribute { /// HTML start tag attribute name - pub name: String, + pub(crate) name: String, /// HTML start tag attribute value - pub value: String, + pub(crate) value: String, } /// An iterator for a comment's attributes -pub struct CommentAttributesIterator { +pub(crate) struct CommentAttributesIterator { x: CXComment, length: c_uint, index: c_uint, @@ -1640,13 +1641,13 @@ impl Iterator for CommentAttributesIterator { } /// A source file. -pub struct File { +pub(crate) struct File { x: CXFile, } impl File { /// Get the name of this source file. - pub fn name(&self) -> Option { + pub(crate) fn name(&self) -> Option { if self.x.is_null() { return None; } @@ -1670,7 +1671,7 @@ fn cxstring_into_string(s: CXString) -> String { /// An `Index` is an environment for a set of translation units that will /// typically end up linked together in one final binary. -pub struct Index { +pub(crate) struct Index { x: CXIndex, } @@ -1681,7 +1682,7 @@ impl Index { /// headers are included when enumerating a translation unit's "locals". /// /// The `diag` parameter controls whether debugging diagnostics are enabled. - pub fn new(pch: bool, diag: bool) -> Index { + pub(crate) fn new(pch: bool, diag: bool) -> Index { unsafe { Index { x: clang_createIndex(pch as c_int, diag as c_int), @@ -1705,7 +1706,7 @@ impl Drop for Index { } /// A translation unit (or "compilation unit"). -pub struct TranslationUnit { +pub(crate) struct TranslationUnit { x: CXTranslationUnit, } @@ -1717,7 +1718,7 @@ impl fmt::Debug for TranslationUnit { impl TranslationUnit { /// Parse a source file into a translation unit. - pub fn parse( + pub(crate) fn parse( ix: &Index, file: &str, cmd_args: &[String], @@ -1753,7 +1754,7 @@ impl TranslationUnit { /// Get the Clang diagnostic information associated with this translation /// unit. - pub fn diags(&self) -> Vec { + pub(crate) fn diags(&self) -> Vec { unsafe { let num = clang_getNumDiagnostics(self.x) as usize; let mut diags = vec![]; @@ -1767,7 +1768,7 @@ impl TranslationUnit { } /// Get a cursor pointing to the root of this translation unit's AST. - pub fn cursor(&self) -> Cursor { + pub(crate) fn cursor(&self) -> Cursor { unsafe { Cursor { x: clang_getTranslationUnitCursor(self.x), @@ -1776,7 +1777,7 @@ impl TranslationUnit { } /// Is this the null translation unit? - pub fn is_null(&self) -> bool { + pub(crate) fn is_null(&self) -> bool { self.x.is_null() } } @@ -1790,14 +1791,14 @@ impl Drop for TranslationUnit { } /// A diagnostic message generated while parsing a translation unit. -pub struct Diagnostic { +pub(crate) struct Diagnostic { x: CXDiagnostic, } impl Diagnostic { /// Format this diagnostic message as a string, using the given option bit /// flags. - pub fn format(&self) -> String { + pub(crate) fn format(&self) -> String { unsafe { let opts = clang_defaultDiagnosticDisplayOptions(); cxstring_into_string(clang_formatDiagnostic(self.x, opts)) @@ -1805,7 +1806,7 @@ impl Diagnostic { } /// What is the severity of this diagnostic message? - pub fn severity(&self) -> CXDiagnosticSeverity { + pub(crate) fn severity(&self) -> CXDiagnosticSeverity { unsafe { clang_getDiagnosticSeverity(self.x) } } } @@ -1820,17 +1821,17 @@ impl Drop for Diagnostic { } /// A file which has not been saved to disk. -pub struct UnsavedFile { +pub(crate) struct UnsavedFile { x: CXUnsavedFile, /// The name of the unsaved file. Kept here to avoid leaving dangling pointers in /// `CXUnsavedFile`. - pub name: CString, + pub(crate) name: CString, contents: CString, } impl UnsavedFile { /// Construct a new unsaved file with the given `name` and `contents`. - pub fn new(name: String, contents: String) -> UnsavedFile { + pub(crate) fn new(name: String, contents: String) -> UnsavedFile { let name = CString::new(name).unwrap(); let contents = CString::new(contents).unwrap(); let x = CXUnsavedFile { @@ -1853,17 +1854,17 @@ impl fmt::Debug for UnsavedFile { } /// Convert a cursor kind into a static string. -pub fn kind_to_str(x: CXCursorKind) -> String { +pub(crate) fn kind_to_str(x: CXCursorKind) -> String { unsafe { cxstring_into_string(clang_getCursorKindSpelling(x)) } } /// Convert a type kind to a static string. -pub fn type_to_str(x: CXTypeKind) -> String { +pub(crate) fn type_to_str(x: CXTypeKind) -> String { unsafe { cxstring_into_string(clang_getTypeKindSpelling(x)) } } /// Dump the Clang AST to stdout for debugging purposes. -pub fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { +pub(crate) fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { fn print_indent>(depth: isize, s: S) { for _ in 0..depth { print!(" "); @@ -2095,19 +2096,19 @@ pub fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { } /// Try to extract the clang version to a string -pub fn extract_clang_version() -> String { +pub(crate) fn extract_clang_version() -> String { unsafe { cxstring_into_string(clang_getClangVersion()) } } /// A wrapper for the result of evaluating an expression. #[derive(Debug)] -pub struct EvalResult { +pub(crate) struct EvalResult { x: CXEvalResult, } impl EvalResult { /// Evaluate `cursor` and return the result. - pub fn new(cursor: Cursor) -> Option { + pub(crate) fn new(cursor: Cursor) -> Option { // Work around https://bugs.llvm.org/show_bug.cgi?id=42532, see: // * https://github.com/rust-lang/rust-bindgen/issues/283 // * https://github.com/rust-lang/rust-bindgen/issues/1590 @@ -2138,7 +2139,7 @@ impl EvalResult { } /// Try to get back the result as a double. - pub fn as_double(&self) -> Option { + pub(crate) fn as_double(&self) -> Option { match self.kind() { CXEval_Float => { Some(unsafe { clang_EvalResult_getAsDouble(self.x) }) @@ -2148,7 +2149,7 @@ impl EvalResult { } /// Try to get back the result as an integer. - pub fn as_int(&self) -> Option { + pub(crate) fn as_int(&self) -> Option { if self.kind() != CXEval_Int { return None; } @@ -2175,7 +2176,7 @@ impl EvalResult { /// Evaluates the expression as a literal string, that may or may not be /// valid utf-8. - pub fn as_literal_string(&self) -> Option> { + pub(crate) fn as_literal_string(&self) -> Option> { match self.kind() { CXEval_StrLiteral => { let ret = unsafe { @@ -2196,16 +2197,16 @@ impl Drop for EvalResult { /// Target information obtained from libclang. #[derive(Debug)] -pub struct TargetInfo { +pub(crate) struct TargetInfo { /// The target triple. - pub triple: String, + pub(crate) triple: String, /// The width of the pointer _in bits_. - pub pointer_width: usize, + pub(crate) pointer_width: usize, } impl TargetInfo { /// Tries to obtain target information from libclang. - pub fn new(tu: &TranslationUnit) -> Self { + pub(crate) fn new(tu: &TranslationUnit) -> Self { let triple; let pointer_width; unsafe { diff --git a/bindgen/codegen/dyngen.rs b/bindgen/codegen/dyngen.rs index d8ea81175e..c067fada0e 100644 --- a/bindgen/codegen/dyngen.rs +++ b/bindgen/codegen/dyngen.rs @@ -5,7 +5,7 @@ use proc_macro2::Ident; /// Used to build the output tokens for dynamic bindings. #[derive(Default)] -pub struct DynamicItems { +pub(crate) struct DynamicItems { /// Tracks the tokens that will appears inside the library struct -- e.g.: /// ```ignore /// struct Lib { @@ -69,11 +69,11 @@ pub struct DynamicItems { } impl DynamicItems { - pub fn new() -> Self { + pub(crate) fn new() -> Self { Self::default() } - pub fn get_tokens( + pub(crate) fn get_tokens( &self, lib_ident: Ident, ctx: &BindgenContext, diff --git a/bindgen/codegen/error.rs b/bindgen/codegen/error.rs index c1bcf4e1cb..ead34965ba 100644 --- a/bindgen/codegen/error.rs +++ b/bindgen/codegen/error.rs @@ -3,7 +3,7 @@ use std::fmt; /// Errors that can occur during code generation. #[derive(Clone, Debug, PartialEq, Eq)] -pub enum Error { +pub(crate) enum Error { /// Tried to generate an opaque blob for a type that did not have a layout. NoLayoutForOpaqueBlob, @@ -30,4 +30,4 @@ impl fmt::Display for Error { impl error::Error for Error {} /// A `Result` of `T` or an error of `bindgen::codegen::error::Error`. -pub type Result = ::std::result::Result; +pub(crate) type Result = ::std::result::Result; diff --git a/bindgen/codegen/helpers.rs b/bindgen/codegen/helpers.rs index 088c7f9363..9c907ae23e 100644 --- a/bindgen/codegen/helpers.rs +++ b/bindgen/codegen/helpers.rs @@ -5,18 +5,18 @@ use crate::ir::layout::Layout; use proc_macro2::{Ident, Span, TokenStream}; use quote::TokenStreamExt; -pub mod attributes { +pub(crate) mod attributes { use proc_macro2::{Ident, Span, TokenStream}; use std::str::FromStr; - pub fn repr(which: &str) -> TokenStream { + pub(crate) fn repr(which: &str) -> TokenStream { let which = Ident::new(which, Span::call_site()); quote! { #[repr( #which )] } } - pub fn repr_list(which_ones: &[&str]) -> TokenStream { + pub(crate) fn repr_list(which_ones: &[&str]) -> TokenStream { let which_ones = which_ones .iter() .cloned() @@ -26,7 +26,7 @@ pub mod attributes { } } - pub fn derives(which_ones: &[&str]) -> TokenStream { + pub(crate) fn derives(which_ones: &[&str]) -> TokenStream { let which_ones = which_ones .iter() .cloned() @@ -36,25 +36,25 @@ pub mod attributes { } } - pub fn inline() -> TokenStream { + pub(crate) fn inline() -> TokenStream { quote! { #[inline] } } - pub fn must_use() -> TokenStream { + pub(crate) fn must_use() -> TokenStream { quote! { #[must_use] } } - pub fn non_exhaustive() -> TokenStream { + pub(crate) fn non_exhaustive() -> TokenStream { quote! { #[non_exhaustive] } } - pub fn doc(comment: String) -> TokenStream { + pub(crate) fn doc(comment: String) -> TokenStream { if comment.is_empty() { quote!() } else { @@ -62,7 +62,7 @@ pub mod attributes { } } - pub fn link_name(name: &str) -> TokenStream { + pub(crate) fn link_name(name: &str) -> TokenStream { // LLVM mangles the name by default but it's already mangled. // Prefixing the name with \u{1} should tell LLVM to not mangle it. let name = format!("\u{1}{}", name); @@ -74,7 +74,7 @@ pub mod attributes { /// Generates a proper type for a field or type with a given `Layout`, that is, /// a type with the correct size and alignment restrictions. -pub fn blob(ctx: &BindgenContext, layout: Layout) -> TokenStream { +pub(crate) fn blob(ctx: &BindgenContext, layout: Layout) -> TokenStream { let opaque = layout.opaque(); // FIXME(emilio, #412): We fall back to byte alignment, but there are @@ -105,7 +105,7 @@ pub fn blob(ctx: &BindgenContext, layout: Layout) -> TokenStream { } /// Integer type of the same size as the given `Layout`. -pub fn integer_type( +pub(crate) fn integer_type( ctx: &BindgenContext, layout: Layout, ) -> Option { @@ -115,7 +115,10 @@ pub fn integer_type( } /// Generates a bitfield allocation unit type for a type with the given `Layout`. -pub fn bitfield_unit(ctx: &BindgenContext, layout: Layout) -> TokenStream { +pub(crate) fn bitfield_unit( + ctx: &BindgenContext, + layout: Layout, +) -> TokenStream { let mut tokens = quote! {}; if ctx.options().enable_cxx_namespaces { @@ -130,7 +133,7 @@ pub fn bitfield_unit(ctx: &BindgenContext, layout: Layout) -> TokenStream { tokens } -pub mod ast_ty { +pub(crate) mod ast_ty { use crate::ir::context::BindgenContext; use crate::ir::function::FunctionSig; use crate::ir::layout::Layout; @@ -138,7 +141,7 @@ pub mod ast_ty { use proc_macro2::{self, TokenStream}; use std::str::FromStr; - pub fn c_void(ctx: &BindgenContext) -> TokenStream { + pub(crate) fn c_void(ctx: &BindgenContext) -> TokenStream { // ctypes_prefix takes precedence match ctx.options().ctypes_prefix { Some(ref prefix) => { @@ -159,7 +162,7 @@ pub mod ast_ty { } } - pub fn raw_type(ctx: &BindgenContext, name: &str) -> TokenStream { + pub(crate) fn raw_type(ctx: &BindgenContext, name: &str) -> TokenStream { let ident = ctx.rust_ident_raw(name); match ctx.options().ctypes_prefix { Some(ref prefix) => { @@ -184,7 +187,7 @@ pub mod ast_ty { } } - pub fn float_kind_rust_type( + pub(crate) fn float_kind_rust_type( ctx: &BindgenContext, fk: FloatKind, layout: Option, @@ -229,25 +232,25 @@ pub mod ast_ty { } } - pub fn int_expr(val: i64) -> TokenStream { + pub(crate) fn int_expr(val: i64) -> TokenStream { // Don't use quote! { #val } because that adds the type suffix. let val = proc_macro2::Literal::i64_unsuffixed(val); quote!(#val) } - pub fn uint_expr(val: u64) -> TokenStream { + pub(crate) fn uint_expr(val: u64) -> TokenStream { // Don't use quote! { #val } because that adds the type suffix. let val = proc_macro2::Literal::u64_unsuffixed(val); quote!(#val) } - pub fn byte_array_expr(bytes: &[u8]) -> TokenStream { + pub(crate) fn byte_array_expr(bytes: &[u8]) -> TokenStream { let mut bytes: Vec<_> = bytes.to_vec(); bytes.push(0); quote! { [ #(#bytes),* ] } } - pub fn cstr_expr(mut string: String) -> TokenStream { + pub(crate) fn cstr_expr(mut string: String) -> TokenStream { string.push('\0'); let b = proc_macro2::Literal::byte_string(string.as_bytes()); quote! { @@ -255,7 +258,10 @@ pub mod ast_ty { } } - pub fn float_expr(ctx: &BindgenContext, f: f64) -> Result { + pub(crate) fn float_expr( + ctx: &BindgenContext, + f: f64, + ) -> Result { if f.is_finite() { let val = proc_macro2::Literal::f64_unsuffixed(f); @@ -286,7 +292,7 @@ pub mod ast_ty { Err(()) } - pub fn arguments_from_signature( + pub(crate) fn arguments_from_signature( signature: &FunctionSig, ctx: &BindgenContext, ) -> Vec { diff --git a/bindgen/codegen/impl_debug.rs b/bindgen/codegen/impl_debug.rs index 0e2cd33ad5..67ec214ee8 100644 --- a/bindgen/codegen/impl_debug.rs +++ b/bindgen/codegen/impl_debug.rs @@ -3,7 +3,7 @@ use crate::ir::context::BindgenContext; use crate::ir::item::{HasTypeParamInArray, IsOpaque, Item, ItemCanonicalName}; use crate::ir::ty::{TypeKind, RUST_DERIVE_IN_ARRAY_LIMIT}; -pub fn gen_debug_impl( +pub(crate) fn gen_debug_impl( ctx: &BindgenContext, fields: &[Field], item: &Item, @@ -51,7 +51,7 @@ pub fn gen_debug_impl( /// A trait for the things which we can codegen tokens that contribute towards a /// generated `impl Debug`. -pub trait ImplDebug<'a> { +pub(crate) trait ImplDebug<'a> { /// Any extra parameter required by this a particular `ImplDebug` implementation. type Extra; diff --git a/bindgen/codegen/impl_partialeq.rs b/bindgen/codegen/impl_partialeq.rs index 960306ffc6..24abf20df7 100644 --- a/bindgen/codegen/impl_partialeq.rs +++ b/bindgen/codegen/impl_partialeq.rs @@ -5,7 +5,7 @@ use crate::ir::ty::{TypeKind, RUST_DERIVE_IN_ARRAY_LIMIT}; /// Generate a manual implementation of `PartialEq` trait for the /// specified compound type. -pub fn gen_partialeq_impl( +pub(crate) fn gen_partialeq_impl( ctx: &BindgenContext, comp_info: &CompInfo, item: &Item, diff --git a/bindgen/codegen/mod.rs b/bindgen/codegen/mod.rs index b6fb70eb01..5d69309d8b 100644 --- a/bindgen/codegen/mod.rs +++ b/bindgen/codegen/mod.rs @@ -5,7 +5,7 @@ mod impl_debug; mod impl_partialeq; mod postprocessing; mod serialize; -pub mod struct_layout; +pub(crate) mod struct_layout; #[cfg(test)] #[allow(warnings)] @@ -84,7 +84,7 @@ impl std::fmt::Display for CodegenError { } // Name of type defined in constified enum module -pub static CONSTIFIED_ENUM_MODULE_REPR_NAME: &str = "Type"; +pub(crate) static CONSTIFIED_ENUM_MODULE_REPR_NAME: &str = "Type"; fn top_level_path( ctx: &BindgenContext, @@ -3349,7 +3349,7 @@ pub enum MacroTypeVariation { impl MacroTypeVariation { /// Convert a `MacroTypeVariation` to its str representation. - pub fn as_str(&self) -> &str { + pub(crate) fn as_str(&self) -> &str { match self { MacroTypeVariation::Signed => "signed", MacroTypeVariation::Unsigned => "unsigned", @@ -3395,7 +3395,7 @@ pub enum AliasVariation { impl AliasVariation { /// Convert an `AliasVariation` to its str representation. - pub fn as_str(&self) -> &str { + pub(crate) fn as_str(&self) -> &str { match self { AliasVariation::TypeAlias => "type_alias", AliasVariation::NewType => "new_type", @@ -3444,7 +3444,7 @@ pub enum NonCopyUnionStyle { impl NonCopyUnionStyle { /// Convert an `NonCopyUnionStyle` to its str representation. - pub fn as_str(&self) -> &'static str { + pub(crate) fn as_str(&self) -> &'static str { match self { Self::BindgenWrapper => "bindgen_wrapper", Self::ManuallyDrop => "manually_drop", @@ -4536,7 +4536,7 @@ pub(crate) fn codegen( }) } -pub mod utils { +pub(crate) mod utils { use super::serialize::CSerialize; use super::{error, CodegenError, CodegenResult, ToRustTyOrOpaque}; use crate::ir::context::BindgenContext; @@ -4544,7 +4544,6 @@ pub mod utils { use crate::ir::item::{Item, ItemCanonicalPath}; use crate::ir::ty::TypeKind; use crate::{args_are_cpp, file_is_cpp}; - use proc_macro2; use std::borrow::Cow; use std::mem; use std::path::PathBuf; @@ -4570,7 +4569,7 @@ pub mod utils { let dir = path.parent().unwrap(); if !dir.exists() { - std::fs::create_dir_all(&dir)?; + std::fs::create_dir_all(dir)?; } let is_cpp = args_are_cpp(&context.options().clang_args) || @@ -4594,7 +4593,7 @@ pub mod utils { Ok(()) } - pub fn prepend_bitfield_unit_type( + pub(crate) fn prepend_bitfield_unit_type( ctx: &BindgenContext, result: &mut Vec, ) { @@ -4613,7 +4612,7 @@ pub mod utils { result.extend(old_items); } - pub fn prepend_objc_header( + pub(crate) fn prepend_objc_header( ctx: &BindgenContext, result: &mut Vec, ) { @@ -4638,7 +4637,7 @@ pub mod utils { result.extend(old_items.into_iter()); } - pub fn prepend_block_header( + pub(crate) fn prepend_block_header( ctx: &BindgenContext, result: &mut Vec, ) { @@ -4657,7 +4656,7 @@ pub mod utils { result.extend(old_items.into_iter()); } - pub fn prepend_union_types( + pub(crate) fn prepend_union_types( ctx: &BindgenContext, result: &mut Vec, ) { @@ -4769,7 +4768,7 @@ pub mod utils { result.extend(old_items.into_iter()); } - pub fn prepend_incomplete_array_types( + pub(crate) fn prepend_incomplete_array_types( ctx: &BindgenContext, result: &mut Vec, ) { @@ -4845,7 +4844,9 @@ pub mod utils { result.extend(old_items.into_iter()); } - pub fn prepend_complex_type(result: &mut Vec) { + pub(crate) fn prepend_complex_type( + result: &mut Vec, + ) { let complex_type = quote! { #[derive(PartialEq, Copy, Clone, Hash, Debug, Default)] #[repr(C)] @@ -4860,7 +4861,7 @@ pub mod utils { result.extend(old_items.into_iter()); } - pub fn build_path( + pub(crate) fn build_path( item: &Item, ctx: &BindgenContext, ) -> error::Result { @@ -4881,7 +4882,7 @@ pub mod utils { } } - pub fn type_from_named( + pub(crate) fn type_from_named( ctx: &BindgenContext, name: &str, ) -> Option { @@ -4949,14 +4950,14 @@ pub mod utils { } } - pub fn fnsig_return_ty( + pub(crate) fn fnsig_return_ty( ctx: &BindgenContext, sig: &FunctionSig, ) -> proc_macro2::TokenStream { fnsig_return_ty_internal(ctx, sig, /* include_arrow = */ true) } - pub fn fnsig_arguments( + pub(crate) fn fnsig_arguments( ctx: &BindgenContext, sig: &FunctionSig, ) -> Vec { @@ -5029,7 +5030,7 @@ pub mod utils { args } - pub fn fnsig_argument_identifiers( + pub(crate) fn fnsig_argument_identifiers( ctx: &BindgenContext, sig: &FunctionSig, ) -> Vec { @@ -5058,7 +5059,7 @@ pub mod utils { args } - pub fn fnsig_block( + pub(crate) fn fnsig_block( ctx: &BindgenContext, sig: &FunctionSig, ) -> proc_macro2::TokenStream { diff --git a/bindgen/codegen/struct_layout.rs b/bindgen/codegen/struct_layout.rs index ddac1b0abb..cca4a59b73 100644 --- a/bindgen/codegen/struct_layout.rs +++ b/bindgen/codegen/struct_layout.rs @@ -13,7 +13,7 @@ const MAX_GUARANTEED_ALIGN: usize = 8; /// Trace the layout of struct. #[derive(Debug)] -pub struct StructLayoutTracker<'a> { +pub(crate) struct StructLayoutTracker<'a> { name: &'a str, ctx: &'a BindgenContext, comp: &'a CompInfo, @@ -29,7 +29,7 @@ pub struct StructLayoutTracker<'a> { } /// Returns a size aligned to a given value. -pub fn align_to(size: usize, align: usize) -> usize { +pub(crate) fn align_to(size: usize, align: usize) -> usize { if align == 0 { return size; } @@ -43,7 +43,7 @@ pub fn align_to(size: usize, align: usize) -> usize { } /// Returns the lower power of two byte count that can hold at most n bits. -pub fn bytes_from_bits_pow2(mut n: usize) -> usize { +pub(crate) fn bytes_from_bits_pow2(mut n: usize) -> usize { if n == 0 { return 0; } @@ -83,7 +83,7 @@ fn test_bytes_from_bits_pow2() { } impl<'a> StructLayoutTracker<'a> { - pub fn new( + pub(crate) fn new( ctx: &'a BindgenContext, comp: &'a CompInfo, ty: &'a Type, @@ -109,15 +109,15 @@ impl<'a> StructLayoutTracker<'a> { } } - pub fn can_copy_union_fields(&self) -> bool { + pub(crate) fn can_copy_union_fields(&self) -> bool { self.can_copy_union_fields } - pub fn is_rust_union(&self) -> bool { + pub(crate) fn is_rust_union(&self) -> bool { self.is_rust_union } - pub fn saw_vtable(&mut self) { + pub(crate) fn saw_vtable(&mut self) { debug!("saw vtable for {}", self.name); let ptr_size = self.ctx.target_pointer_size(); @@ -126,7 +126,7 @@ impl<'a> StructLayoutTracker<'a> { self.max_field_align = ptr_size; } - pub fn saw_base(&mut self, base_ty: &Type) { + pub(crate) fn saw_base(&mut self, base_ty: &Type) { debug!("saw base for {}", self.name); if let Some(layout) = base_ty.layout(self.ctx) { self.align_to_latest_field(layout); @@ -137,7 +137,7 @@ impl<'a> StructLayoutTracker<'a> { } } - pub fn saw_bitfield_unit(&mut self, layout: Layout) { + pub(crate) fn saw_bitfield_unit(&mut self, layout: Layout) { debug!("saw bitfield unit for {}: {:?}", self.name, layout); self.align_to_latest_field(layout); @@ -159,7 +159,7 @@ impl<'a> StructLayoutTracker<'a> { /// Returns a padding field if necessary for a given new field _before_ /// adding that field. - pub fn saw_field( + pub(crate) fn saw_field( &mut self, field_name: &str, field_ty: &Type, @@ -189,7 +189,7 @@ impl<'a> StructLayoutTracker<'a> { self.saw_field_with_layout(field_name, field_layout, field_offset) } - pub fn saw_field_with_layout( + pub(crate) fn saw_field_with_layout( &mut self, field_name: &str, field_layout: Layout, @@ -274,7 +274,7 @@ impl<'a> StructLayoutTracker<'a> { padding_layout.map(|layout| self.padding_field(layout)) } - pub fn add_tail_padding( + pub(crate) fn add_tail_padding( &mut self, comp_name: &str, comp_layout: Layout, @@ -305,7 +305,7 @@ impl<'a> StructLayoutTracker<'a> { Some(self.padding_field(Layout::new(size, 0))) } - pub fn pad_struct( + pub(crate) fn pad_struct( &mut self, layout: Layout, ) -> Option { @@ -360,7 +360,7 @@ impl<'a> StructLayoutTracker<'a> { } } - pub fn requires_explicit_align(&self, layout: Layout) -> bool { + pub(crate) fn requires_explicit_align(&self, layout: Layout) -> bool { let repr_align = self.ctx.options().rust_features().repr_align; // Always force explicit repr(align) for stuff more than 16-byte aligned diff --git a/bindgen/features.rs b/bindgen/features.rs index 4fee5d63fc..ef44571a39 100644 --- a/bindgen/features.rs +++ b/bindgen/features.rs @@ -1,7 +1,7 @@ //! Contains code for selecting features -#![deny(missing_docs)] #![deny(unused_extern_crates)] +#![deny(clippy::missing_docs_in_private_items)] #![allow(deprecated)] use std::io; diff --git a/bindgen/ir/analysis/derive.rs b/bindgen/ir/analysis/derive.rs index d888cd558b..0f496a7ead 100644 --- a/bindgen/ir/analysis/derive.rs +++ b/bindgen/ir/analysis/derive.rs @@ -61,7 +61,7 @@ pub enum DeriveTrait { /// * For all other (simple) types, compiler and standard library limitations /// dictate whether the trait is implemented. #[derive(Debug, Clone)] -pub struct CannotDerive<'ctx> { +pub(crate) struct CannotDerive<'ctx> { ctx: &'ctx BindgenContext, derive_trait: DeriveTrait, @@ -722,7 +722,7 @@ impl<'ctx> From> for HashMap { /// /// Elements that are not `CanDerive::Yes` are kept in the set, so that it /// represents all items that cannot derive. -pub fn as_cannot_derive_set( +pub(crate) fn as_cannot_derive_set( can_derive: HashMap, ) -> HashSet { can_derive diff --git a/bindgen/ir/analysis/has_destructor.rs b/bindgen/ir/analysis/has_destructor.rs index 74fd73d14e..cbcbe55af2 100644 --- a/bindgen/ir/analysis/has_destructor.rs +++ b/bindgen/ir/analysis/has_destructor.rs @@ -22,7 +22,7 @@ use crate::{HashMap, HashSet}; /// * If T is the type of a field, that field has a destructor if it's not a bitfield, /// and if T has a destructor. #[derive(Debug, Clone)] -pub struct HasDestructorAnalysis<'ctx> { +pub(crate) struct HasDestructorAnalysis<'ctx> { ctx: &'ctx BindgenContext, // The incremental result of this analysis's computation. Everything in this diff --git a/bindgen/ir/analysis/has_float.rs b/bindgen/ir/analysis/has_float.rs index bbf2126f70..219c5a5a8d 100644 --- a/bindgen/ir/analysis/has_float.rs +++ b/bindgen/ir/analysis/has_float.rs @@ -22,7 +22,7 @@ use crate::{HashMap, HashSet}; /// float if any of the template arguments or template definition /// has. #[derive(Debug, Clone)] -pub struct HasFloat<'ctx> { +pub(crate) struct HasFloat<'ctx> { ctx: &'ctx BindgenContext, // The incremental result of this analysis's computation. Everything in this diff --git a/bindgen/ir/analysis/has_type_param_in_array.rs b/bindgen/ir/analysis/has_type_param_in_array.rs index aa52304758..088c08f542 100644 --- a/bindgen/ir/analysis/has_type_param_in_array.rs +++ b/bindgen/ir/analysis/has_type_param_in_array.rs @@ -22,7 +22,7 @@ use crate::{HashMap, HashSet}; /// type parameter in array if any of the template arguments or template definition /// has. #[derive(Debug, Clone)] -pub struct HasTypeParameterInArray<'ctx> { +pub(crate) struct HasTypeParameterInArray<'ctx> { ctx: &'ctx BindgenContext, // The incremental result of this analysis's computation. Everything in this diff --git a/bindgen/ir/analysis/has_vtable.rs b/bindgen/ir/analysis/has_vtable.rs index 8ac47a65da..980a551b88 100644 --- a/bindgen/ir/analysis/has_vtable.rs +++ b/bindgen/ir/analysis/has_vtable.rs @@ -10,7 +10,7 @@ use std::ops; /// The result of the `HasVtableAnalysis` for an individual item. #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub enum HasVtableResult { +pub(crate) enum HasVtableResult { /// The item does not have a vtable pointer. No, @@ -30,7 +30,7 @@ impl Default for HasVtableResult { impl HasVtableResult { /// Take the least upper bound of `self` and `rhs`. - pub fn join(self, rhs: Self) -> Self { + pub(crate) fn join(self, rhs: Self) -> Self { cmp::max(self, rhs) } } @@ -60,7 +60,7 @@ impl ops::BitOrAssign for HasVtableResult { /// * If T is an instantiation of an abstract template definition, T has /// vtable if template definition has vtable #[derive(Debug, Clone)] -pub struct HasVtableAnalysis<'ctx> { +pub(crate) struct HasVtableAnalysis<'ctx> { ctx: &'ctx BindgenContext, // The incremental result of this analysis's computation. Everything in this @@ -230,7 +230,7 @@ impl<'ctx> From> for HashMap { /// This is not for _computing_ whether the thing has a vtable, it is for /// looking up the results of the HasVtableAnalysis's computations for a /// specific thing. -pub trait HasVtable { +pub(crate) trait HasVtable { /// Return `true` if this thing has vtable, `false` otherwise. fn has_vtable(&self, ctx: &BindgenContext) -> bool; diff --git a/bindgen/ir/analysis/mod.rs b/bindgen/ir/analysis/mod.rs index 40dfc6d644..0263088a99 100644 --- a/bindgen/ir/analysis/mod.rs +++ b/bindgen/ir/analysis/mod.rs @@ -39,19 +39,24 @@ // Re-export individual analyses. mod template_params; -pub use self::template_params::UsedTemplateParameters; +pub(crate) use self::template_params::UsedTemplateParameters; mod derive; -pub use self::derive::{as_cannot_derive_set, CannotDerive, DeriveTrait}; +pub use self::derive::DeriveTrait; +pub(crate) use self::derive::{as_cannot_derive_set, CannotDerive}; mod has_vtable; -pub use self::has_vtable::{HasVtable, HasVtableAnalysis, HasVtableResult}; +pub(crate) use self::has_vtable::{ + HasVtable, HasVtableAnalysis, HasVtableResult, +}; mod has_destructor; -pub use self::has_destructor::HasDestructorAnalysis; +pub(crate) use self::has_destructor::HasDestructorAnalysis; mod has_type_param_in_array; -pub use self::has_type_param_in_array::HasTypeParameterInArray; +pub(crate) use self::has_type_param_in_array::HasTypeParameterInArray; mod has_float; -pub use self::has_float::HasFloat; +pub(crate) use self::has_float::HasFloat; mod sizedness; -pub use self::sizedness::{Sizedness, SizednessAnalysis, SizednessResult}; +pub(crate) use self::sizedness::{ + Sizedness, SizednessAnalysis, SizednessResult, +}; use crate::ir::context::{BindgenContext, ItemId}; @@ -73,7 +78,7 @@ use std::ops; /// /// For a simple example analysis, see the `ReachableFrom` type in the `tests` /// module below. -pub trait MonotoneFramework: Sized + fmt::Debug { +pub(crate) trait MonotoneFramework: Sized + fmt::Debug { /// The type of node in our dependency graph. /// /// This is just generic (and not `ItemId`) so that we can easily unit test @@ -121,7 +126,7 @@ pub trait MonotoneFramework: Sized + fmt::Debug { /// Whether an analysis's `constrain` function modified the incremental results /// or not. #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum ConstrainResult { +pub(crate) enum ConstrainResult { /// The incremental results were updated, and the fix-point computation /// should continue. Changed, @@ -155,7 +160,7 @@ impl ops::BitOrAssign for ConstrainResult { } /// Run an analysis in the monotone framework. -pub fn analyze(extra: Analysis::Extra) -> Analysis::Output +pub(crate) fn analyze(extra: Analysis::Extra) -> Analysis::Output where Analysis: MonotoneFramework, { @@ -174,7 +179,7 @@ where } /// Generate the dependency map for analysis -pub fn generate_dependencies( +pub(crate) fn generate_dependencies( ctx: &BindgenContext, consider_edge: F, ) -> HashMap> diff --git a/bindgen/ir/analysis/sizedness.rs b/bindgen/ir/analysis/sizedness.rs index 251c3747b2..b4c953e647 100644 --- a/bindgen/ir/analysis/sizedness.rs +++ b/bindgen/ir/analysis/sizedness.rs @@ -25,7 +25,7 @@ use std::{cmp, ops}; /// We initially assume that all types are `ZeroSized` and then update our /// understanding as we learn more about each type. #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub enum SizednessResult { +pub(crate) enum SizednessResult { /// The type is zero-sized. /// /// This means that if it is a C++ type, and is not being used as a base @@ -70,7 +70,7 @@ impl Default for SizednessResult { impl SizednessResult { /// Take the least upper bound of `self` and `rhs`. - pub fn join(self, rhs: Self) -> Self { + pub(crate) fn join(self, rhs: Self) -> Self { cmp::max(self, rhs) } } @@ -102,7 +102,7 @@ impl ops::BitOrAssign for SizednessResult { /// /// * For type parameters, `DependsOnTypeParam` is assigned. #[derive(Debug)] -pub struct SizednessAnalysis<'ctx> { +pub(crate) struct SizednessAnalysis<'ctx> { ctx: &'ctx BindgenContext, dependencies: HashMap>, // Incremental results of the analysis. Missing entries are implicitly @@ -350,7 +350,7 @@ impl<'ctx> From> for HashMap { /// /// This is not for _computing_ whether the thing is sized, it is for looking up /// the results of the `Sizedness` analysis's computations for a specific thing. -pub trait Sizedness { +pub(crate) trait Sizedness { /// Get the sizedness of this type. fn sizedness(&self, ctx: &BindgenContext) -> SizednessResult; diff --git a/bindgen/ir/analysis/template_params.rs b/bindgen/ir/analysis/template_params.rs index f4f0c59d71..4ac5f08809 100644 --- a/bindgen/ir/analysis/template_params.rs +++ b/bindgen/ir/analysis/template_params.rs @@ -14,7 +14,7 @@ //! If we generate the naive Rust code for this alias, we get: //! //! ```ignore -//! pub type Fml = ::std::os::raw::int; +//! pub(crate) type Fml = ::std::os::raw::int; //! ``` //! //! And this is rejected by `rustc` due to the unused type parameter. @@ -146,7 +146,7 @@ use crate::{HashMap, HashSet}; /// specially; see `constrain_instantiation_of_blocklisted_template` and its /// documentation for details. #[derive(Debug, Clone)] -pub struct UsedTemplateParameters<'ctx> { +pub(crate) struct UsedTemplateParameters<'ctx> { ctx: &'ctx BindgenContext, // The Option is only there for temporary moves out of the hash map. See the diff --git a/bindgen/ir/annotations.rs b/bindgen/ir/annotations.rs index 288c11ebae..efffe07b9b 100644 --- a/bindgen/ir/annotations.rs +++ b/bindgen/ir/annotations.rs @@ -8,7 +8,7 @@ use crate::clang; /// What kind of accessor should we provide for a field? #[derive(Copy, PartialEq, Eq, Clone, Debug)] -pub enum FieldAccessorKind { +pub(crate) enum FieldAccessorKind { /// No accessor. None, /// Plain accessor. @@ -26,7 +26,7 @@ pub enum FieldAccessorKind { /// /// http://www.stack.nl/~dimitri/doxygen/manual/docblocks.html #[derive(Default, Clone, PartialEq, Eq, Debug)] -pub struct Annotations { +pub(crate) struct Annotations { /// Whether this item is marked as opaque. Only applies to types. opaque: bool, /// Whether this item should be hidden from the output. Only applies to @@ -80,7 +80,7 @@ fn parse_accessor(s: &str) -> FieldAccessorKind { impl Annotations { /// Construct new annotations for the given cursor and its bindgen comments /// (if any). - pub fn new(cursor: &clang::Cursor) -> Option { + pub(crate) fn new(cursor: &clang::Cursor) -> Option { let mut anno = Annotations::default(); let mut matched_one = false; anno.parse(&cursor.comment(), &mut matched_one); @@ -93,12 +93,12 @@ impl Annotations { } /// Should this type be hidden? - pub fn hide(&self) -> bool { + pub(crate) fn hide(&self) -> bool { self.hide } /// Should this type be opaque? - pub fn opaque(&self) -> bool { + pub(crate) fn opaque(&self) -> bool { self.opaque } @@ -124,42 +124,42 @@ impl Annotations { /// ``` /// /// That is, code for `Foo` is used to generate `Bar`. - pub fn use_instead_of(&self) -> Option<&[String]> { + pub(crate) fn use_instead_of(&self) -> Option<&[String]> { self.use_instead_of.as_deref() } /// The list of derives that have been specified in this annotation. - pub fn derives(&self) -> &[String] { + pub(crate) fn derives(&self) -> &[String] { &self.derives } /// Should we avoid implementing the `Copy` trait? - pub fn disallow_copy(&self) -> bool { + pub(crate) fn disallow_copy(&self) -> bool { self.disallow_copy } /// Should we avoid implementing the `Debug` trait? - pub fn disallow_debug(&self) -> bool { + pub(crate) fn disallow_debug(&self) -> bool { self.disallow_debug } /// Should we avoid implementing the `Default` trait? - pub fn disallow_default(&self) -> bool { + pub(crate) fn disallow_default(&self) -> bool { self.disallow_default } /// Should this type get a `#[must_use]` annotation? - pub fn must_use_type(&self) -> bool { + pub(crate) fn must_use_type(&self) -> bool { self.must_use_type } /// Should the fields be private? - pub fn private_fields(&self) -> Option { + pub(crate) fn private_fields(&self) -> Option { self.private_fields } /// What kind of accessors should we provide for this type's fields? - pub fn accessor_kind(&self) -> Option { + pub(crate) fn accessor_kind(&self) -> Option { self.accessor_kind } @@ -205,7 +205,7 @@ impl Annotations { } /// Returns whether we've parsed a "constant" attribute. - pub fn constify_enum_variant(&self) -> bool { + pub(crate) fn constify_enum_variant(&self) -> bool { self.constify_enum_variant } } diff --git a/bindgen/ir/comment.rs b/bindgen/ir/comment.rs index 3eb17aacb9..7b6f105a4d 100644 --- a/bindgen/ir/comment.rs +++ b/bindgen/ir/comment.rs @@ -12,7 +12,7 @@ enum Kind { } /// Preprocesses a C/C++ comment so that it is a valid Rust comment. -pub fn preprocess(comment: &str) -> String { +pub(crate) fn preprocess(comment: &str) -> String { match self::kind(comment) { Some(Kind::SingleLines) => preprocess_single_lines(comment), Some(Kind::MultiLine) => preprocess_multi_line(comment), diff --git a/bindgen/ir/comp.rs b/bindgen/ir/comp.rs index 18a4291cf9..fd1d1b8e52 100644 --- a/bindgen/ir/comp.rs +++ b/bindgen/ir/comp.rs @@ -22,7 +22,7 @@ use std::mem; /// The kind of compound type. #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum CompKind { +pub(crate) enum CompKind { /// A struct. Struct, /// A union. @@ -31,7 +31,7 @@ pub enum CompKind { /// The kind of C++ method. #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum MethodKind { +pub(crate) enum MethodKind { /// A constructor. We represent it as method for convenience, to avoid code /// duplication. Constructor, @@ -55,7 +55,7 @@ pub enum MethodKind { impl MethodKind { /// Is this a destructor method? - pub fn is_destructor(&self) -> bool { + pub(crate) fn is_destructor(&self) -> bool { matches!( *self, MethodKind::Destructor | MethodKind::VirtualDestructor { .. } @@ -63,7 +63,7 @@ impl MethodKind { } /// Is this a pure virtual method? - pub fn is_pure_virtual(&self) -> bool { + pub(crate) fn is_pure_virtual(&self) -> bool { match *self { MethodKind::Virtual { pure_virtual } | MethodKind::VirtualDestructor { pure_virtual } => pure_virtual, @@ -74,7 +74,7 @@ impl MethodKind { /// A struct representing a C++ method, either static, normal, or virtual. #[derive(Debug)] -pub struct Method { +pub(crate) struct Method { kind: MethodKind, /// The signature of the method. Take into account this is not a `Type` /// item, but a `Function` one. @@ -86,7 +86,7 @@ pub struct Method { impl Method { /// Construct a new `Method`. - pub fn new( + pub(crate) fn new( kind: MethodKind, signature: FunctionId, is_const: bool, @@ -99,17 +99,17 @@ impl Method { } /// What kind of method is this? - pub fn kind(&self) -> MethodKind { + pub(crate) fn kind(&self) -> MethodKind { self.kind } /// Is this a constructor? - pub fn is_constructor(&self) -> bool { + pub(crate) fn is_constructor(&self) -> bool { self.kind == MethodKind::Constructor } /// Is this a virtual method? - pub fn is_virtual(&self) -> bool { + pub(crate) fn is_virtual(&self) -> bool { matches!( self.kind, MethodKind::Virtual { .. } | MethodKind::VirtualDestructor { .. } @@ -117,23 +117,23 @@ impl Method { } /// Is this a static method? - pub fn is_static(&self) -> bool { + pub(crate) fn is_static(&self) -> bool { self.kind == MethodKind::Static } /// Get the id for the `Function` signature for this method. - pub fn signature(&self) -> FunctionId { + pub(crate) fn signature(&self) -> FunctionId { self.signature } /// Is this a const qualified method? - pub fn is_const(&self) -> bool { + pub(crate) fn is_const(&self) -> bool { self.is_const } } /// Methods common to the various field types. -pub trait FieldMethods { +pub(crate) trait FieldMethods { /// Get the name of this field. fn name(&self) -> Option<&str>; @@ -161,7 +161,7 @@ pub trait FieldMethods { /// 2.4.II.1 in the Itanium C++ /// ABI](http://itanium-cxx-abi.github.io/cxx-abi/abi.html#class-types). #[derive(Debug)] -pub struct BitfieldUnit { +pub(crate) struct BitfieldUnit { nth: usize, layout: Layout, bitfields: Vec, @@ -171,24 +171,24 @@ impl BitfieldUnit { /// Get the 1-based index of this bitfield unit within its containing /// struct. Useful for generating a Rust struct's field name for this unit /// of bitfields. - pub fn nth(&self) -> usize { + pub(crate) fn nth(&self) -> usize { self.nth } /// Get the layout within which these bitfields reside. - pub fn layout(&self) -> Layout { + pub(crate) fn layout(&self) -> Layout { self.layout } /// Get the bitfields within this unit. - pub fn bitfields(&self) -> &[Bitfield] { + pub(crate) fn bitfields(&self) -> &[Bitfield] { &self.bitfields } } /// A struct representing a C++ field. #[derive(Debug)] -pub enum Field { +pub(crate) enum Field { /// A normal data member. DataMember(FieldData), @@ -198,7 +198,7 @@ pub enum Field { impl Field { /// Get this field's layout. - pub fn layout(&self, ctx: &BindgenContext) -> Option { + pub(crate) fn layout(&self, ctx: &BindgenContext) -> Option { match *self { Field::Bitfields(BitfieldUnit { layout, .. }) => Some(layout), Field::DataMember(ref data) => { @@ -307,7 +307,7 @@ impl DotAttributes for Bitfield { /// A logical bitfield within some physical bitfield allocation unit. #[derive(Debug)] -pub struct Bitfield { +pub(crate) struct Bitfield { /// Index of the bit within this bitfield's allocation unit where this /// bitfield's bits begin. offset_into_unit: usize, @@ -341,27 +341,12 @@ impl Bitfield { /// Get the index of the bit within this bitfield's allocation unit where /// this bitfield begins. - pub fn offset_into_unit(&self) -> usize { + pub(crate) fn offset_into_unit(&self) -> usize { self.offset_into_unit } - /// Get the mask value that when &'ed with this bitfield's allocation unit - /// produces this bitfield's value. - pub fn mask(&self) -> u64 { - use std::u64; - - let unoffseted_mask = - if self.width() as u64 == mem::size_of::() as u64 * 8 { - u64::MAX - } else { - (1u64 << self.width()) - 1u64 - }; - - unoffseted_mask << self.offset_into_unit() - } - /// Get the bit width of this bitfield. - pub fn width(&self) -> u32 { + pub(crate) fn width(&self) -> u32 { self.data.bitfield_width().unwrap() } @@ -369,7 +354,7 @@ impl Bitfield { /// /// Panics if called before assigning bitfield accessor names or if /// this bitfield have no name. - pub fn getter_name(&self) -> &str { + pub(crate) fn getter_name(&self) -> &str { assert!( self.name().is_some(), "`Bitfield::getter_name` called on anonymous field" @@ -384,7 +369,7 @@ impl Bitfield { /// /// Panics if called before assigning bitfield accessor names or if /// this bitfield have no name. - pub fn setter_name(&self) -> &str { + pub(crate) fn setter_name(&self) -> &str { assert!( self.name().is_some(), "`Bitfield::setter_name` called on anonymous field" @@ -866,7 +851,7 @@ impl Trace for CompFields { /// Common data shared across different field types. #[derive(Clone, Debug)] -pub struct FieldData { +pub(crate) struct FieldData { /// The name of the field, empty if it's an unnamed bitfield width. name: Option, @@ -921,7 +906,7 @@ impl FieldMethods for FieldData { /// The kind of inheritance a base class is using. #[derive(Clone, Debug, PartialEq, Eq)] -pub enum BaseKind { +pub(crate) enum BaseKind { /// Normal inheritance, like: /// /// ```cpp @@ -938,25 +923,25 @@ pub enum BaseKind { /// A base class. #[derive(Clone, Debug)] -pub struct Base { +pub(crate) struct Base { /// The type of this base class. - pub ty: TypeId, + pub(crate) ty: TypeId, /// The kind of inheritance we're doing. - pub kind: BaseKind, + pub(crate) kind: BaseKind, /// Name of the field in which this base should be stored. - pub field_name: String, + pub(crate) field_name: String, /// Whether this base is inherited from publically. - pub is_pub: bool, + pub(crate) is_pub: bool, } impl Base { /// Whether this base class is inheriting virtually. - pub fn is_virtual(&self) -> bool { + pub(crate) fn is_virtual(&self) -> bool { self.kind == BaseKind::Virtual } /// Whether this base class should have it's own field for storage. - pub fn requires_storage(&self, ctx: &BindgenContext) -> bool { + pub(crate) fn requires_storage(&self, ctx: &BindgenContext) -> bool { // Virtual bases are already taken into account by the vtable // pointer. // @@ -976,7 +961,7 @@ impl Base { } /// Whether this base is inherited from publically. - pub fn is_public(&self) -> bool { + pub(crate) fn is_public(&self) -> bool { self.is_pub } } @@ -987,7 +972,7 @@ impl Base { /// of fields which also are associated with their own (potentially compound) /// type. #[derive(Debug)] -pub struct CompInfo { +pub(crate) struct CompInfo { /// Whether this is a struct or a union. kind: CompKind, @@ -1067,7 +1052,7 @@ pub struct CompInfo { impl CompInfo { /// Construct a new compound type. - pub fn new(kind: CompKind) -> Self { + pub(crate) fn new(kind: CompKind) -> Self { CompInfo { kind, fields: CompFields::default(), @@ -1097,7 +1082,7 @@ impl CompInfo { /// If we're a union without known layout, we try to compute it from our /// members. This is not ideal, but clang fails to report the size for these /// kind of unions, see test/headers/template_union.hpp - pub fn layout(&self, ctx: &BindgenContext) -> Option { + pub(crate) fn layout(&self, ctx: &BindgenContext) -> Option { // We can't do better than clang here, sorry. if self.kind == CompKind::Struct { return None; @@ -1126,7 +1111,7 @@ impl CompInfo { } /// Get this type's set of fields. - pub fn fields(&self) -> &[Field] { + pub(crate) fn fields(&self) -> &[Field] { match self.fields { CompFields::Error => &[], CompFields::After { ref fields, .. } => fields, @@ -1184,7 +1169,7 @@ impl CompInfo { /// Returns whether we have a too large bitfield unit, in which case we may /// not be able to derive some of the things we should be able to normally /// derive. - pub fn has_too_large_bitfield_unit(&self) -> bool { + pub(crate) fn has_too_large_bitfield_unit(&self) -> bool { if !self.has_bitfields() { return false; } @@ -1198,53 +1183,53 @@ impl CompInfo { /// Does this type have any template parameters that aren't types /// (e.g. int)? - pub fn has_non_type_template_params(&self) -> bool { + pub(crate) fn has_non_type_template_params(&self) -> bool { self.has_non_type_template_params } /// Do we see a virtual function during parsing? /// Get the has_own_virtual_method boolean. - pub fn has_own_virtual_method(&self) -> bool { + pub(crate) fn has_own_virtual_method(&self) -> bool { self.has_own_virtual_method } /// Did we see a destructor when parsing this type? - pub fn has_own_destructor(&self) -> bool { + pub(crate) fn has_own_destructor(&self) -> bool { self.has_destructor } /// Get this type's set of methods. - pub fn methods(&self) -> &[Method] { + pub(crate) fn methods(&self) -> &[Method] { &self.methods } /// Get this type's set of constructors. - pub fn constructors(&self) -> &[FunctionId] { + pub(crate) fn constructors(&self) -> &[FunctionId] { &self.constructors } /// Get this type's destructor. - pub fn destructor(&self) -> Option<(MethodKind, FunctionId)> { + pub(crate) fn destructor(&self) -> Option<(MethodKind, FunctionId)> { self.destructor } /// What kind of compound type is this? - pub fn kind(&self) -> CompKind { + pub(crate) fn kind(&self) -> CompKind { self.kind } /// Is this a union? - pub fn is_union(&self) -> bool { + pub(crate) fn is_union(&self) -> bool { self.kind() == CompKind::Union } /// The set of types that this one inherits from. - pub fn base_members(&self) -> &[Base] { + pub(crate) fn base_members(&self) -> &[Base] { &self.base_members } /// Construct a new compound type from a Clang type. - pub fn from_ty( + pub(crate) fn from_ty( potential_id: ItemId, ty: &clang::Type, location: Option, @@ -1611,23 +1596,23 @@ impl CompInfo { /// Get the set of types that were declared within this compound type /// (e.g. nested class definitions). - pub fn inner_types(&self) -> &[TypeId] { + pub(crate) fn inner_types(&self) -> &[TypeId] { &self.inner_types } /// Get the set of static variables declared within this compound type. - pub fn inner_vars(&self) -> &[VarId] { + pub(crate) fn inner_vars(&self) -> &[VarId] { &self.inner_vars } /// Have we found a field with an opaque type that could potentially mess up /// the layout of this compound type? - pub fn found_unknown_attr(&self) -> bool { + pub(crate) fn found_unknown_attr(&self) -> bool { self.found_unknown_attr } /// Is this compound type packed? - pub fn is_packed( + pub(crate) fn is_packed( &self, ctx: &BindgenContext, layout: Option<&Layout>, @@ -1657,12 +1642,12 @@ impl CompInfo { } /// Returns true if compound type has been forward declared - pub fn is_forward_declaration(&self) -> bool { + pub(crate) fn is_forward_declaration(&self) -> bool { self.is_forward_declaration } /// Compute this compound structure's bitfield allocation units. - pub fn compute_bitfield_units( + pub(crate) fn compute_bitfield_units( &mut self, ctx: &BindgenContext, layout: Option<&Layout>, @@ -1672,7 +1657,7 @@ impl CompInfo { } /// Assign for each anonymous field a generated name. - pub fn deanonymize_fields(&mut self, ctx: &BindgenContext) { + pub(crate) fn deanonymize_fields(&mut self, ctx: &BindgenContext) { self.fields.deanonymize_fields(ctx, &self.methods); } @@ -1685,7 +1670,7 @@ impl CompInfo { /// /// Second boolean returns whether all fields can be copied (and thus /// ManuallyDrop is not needed). - pub fn is_rust_union( + pub(crate) fn is_rust_union( &self, ctx: &BindgenContext, layout: Option<&Layout>, diff --git a/bindgen/ir/context.rs b/bindgen/ir/context.rs index b693a7047e..b821429a42 100644 --- a/bindgen/ir/context.rs +++ b/bindgen/ir/context.rs @@ -35,12 +35,13 @@ use std::mem; /// An identifier for some kind of IR item. #[derive(Debug, Copy, Clone, Eq, PartialOrd, Ord, Hash)] -pub struct ItemId(usize); +pub(crate) struct ItemId(usize); +/// Declare a newtype around `ItemId` with convesion methods. macro_rules! item_id_newtype { ( $( #[$attr:meta] )* - pub struct $name:ident(ItemId) + pub(crate) struct $name:ident(ItemId) where $( #[$checked_attr:meta] )* checked = $checked:ident with $check_method:ident, @@ -51,11 +52,12 @@ macro_rules! item_id_newtype { ) => { $( #[$attr] )* #[derive(Debug, Copy, Clone, Eq, PartialOrd, Ord, Hash)] - pub struct $name(ItemId); + pub(crate) struct $name(ItemId); impl $name { /// Create an `ItemResolver` from this id. - pub fn into_resolver(self) -> ItemResolver { + #[allow(dead_code)] + pub(crate) fn into_resolver(self) -> ItemResolver { let id: ItemId = self.into(); id.into() } @@ -83,9 +85,10 @@ macro_rules! item_id_newtype { } } + #[allow(dead_code)] impl ItemId { $( #[$checked_attr] )* - pub fn $checked(&self, ctx: &BindgenContext) -> Option<$name> { + pub(crate) fn $checked(&self, ctx: &BindgenContext) -> Option<$name> { if ctx.resolve_item(*self).kind().$check_method() { Some($name(*self)) } else { @@ -94,7 +97,7 @@ macro_rules! item_id_newtype { } $( #[$expected_attr] )* - pub fn $expected(&self, ctx: &BindgenContext) -> $name { + pub(crate) fn $expected(&self, ctx: &BindgenContext) -> $name { self.$checked(ctx) .expect(concat!( stringify!($expected), @@ -103,7 +106,7 @@ macro_rules! item_id_newtype { } $( #[$unchecked_attr] )* - pub fn $unchecked(&self) -> $name { + pub(crate) fn $unchecked(&self) -> $name { $name(*self) } } @@ -113,7 +116,7 @@ macro_rules! item_id_newtype { item_id_newtype! { /// An identifier for an `Item` whose `ItemKind` is known to be /// `ItemKind::Type`. - pub struct TypeId(ItemId) + pub(crate) struct TypeId(ItemId) where /// Convert this `ItemId` into a `TypeId` if its associated item is a type, /// otherwise return `None`. @@ -132,7 +135,7 @@ item_id_newtype! { item_id_newtype! { /// An identifier for an `Item` whose `ItemKind` is known to be /// `ItemKind::Module`. - pub struct ModuleId(ItemId) + pub(crate) struct ModuleId(ItemId) where /// Convert this `ItemId` into a `ModuleId` if its associated item is a /// module, otherwise return `None`. @@ -151,7 +154,7 @@ item_id_newtype! { item_id_newtype! { /// An identifier for an `Item` whose `ItemKind` is known to be /// `ItemKind::Var`. - pub struct VarId(ItemId) + pub(crate) struct VarId(ItemId) where /// Convert this `ItemId` into a `VarId` if its associated item is a var, /// otherwise return `None`. @@ -170,7 +173,7 @@ item_id_newtype! { item_id_newtype! { /// An identifier for an `Item` whose `ItemKind` is known to be /// `ItemKind::Function`. - pub struct FunctionId(ItemId) + pub(crate) struct FunctionId(ItemId) where /// Convert this `ItemId` into a `FunctionId` if its associated item is a function, /// otherwise return `None`. @@ -194,7 +197,7 @@ impl From for usize { impl ItemId { /// Get a numeric representation of this id. - pub fn as_usize(&self) -> usize { + pub(crate) fn as_usize(&self) -> usize { (*self).into() } } @@ -305,7 +308,7 @@ enum TypeKey { /// A context used during parsing and generation of structs. #[derive(Debug)] -pub struct BindgenContext { +pub(crate) struct BindgenContext { /// The map of all the items parsed so far, keyed off ItemId. items: Vec>, @@ -504,7 +507,7 @@ impl<'ctx> Iterator for AllowlistedItemsTraversal<'ctx> { impl<'ctx> AllowlistedItemsTraversal<'ctx> { /// Construct a new allowlisted items traversal. - pub fn new( + pub(crate) fn new( ctx: &'ctx BindgenContext, roots: R, predicate: for<'a> fn(&'a BindgenContext, Edge) -> bool, @@ -598,46 +601,46 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Returns `true` if the target architecture is wasm32 - pub fn is_target_wasm32(&self) -> bool { + pub(crate) fn is_target_wasm32(&self) -> bool { self.target_info.triple.starts_with("wasm32-") } /// Creates a timer for the current bindgen phase. If time_phases is `true`, /// the timer will print to stderr when it is dropped, otherwise it will do /// nothing. - pub fn timer<'a>(&self, name: &'a str) -> Timer<'a> { + pub(crate) fn timer<'a>(&self, name: &'a str) -> Timer<'a> { Timer::new(name).with_output(self.options.time_phases) } /// Returns the pointer width to use for the target for the current /// translation. - pub fn target_pointer_size(&self) -> usize { + pub(crate) fn target_pointer_size(&self) -> usize { self.target_info.pointer_width / 8 } /// Get the stack of partially parsed types that we are in the middle of /// parsing. - pub fn currently_parsed_types(&self) -> &[PartialType] { + pub(crate) fn currently_parsed_types(&self) -> &[PartialType] { &self.currently_parsed_types[..] } /// Begin parsing the given partial type, and push it onto the /// `currently_parsed_types` stack so that we won't infinite recurse if we /// run into a reference to it while parsing it. - pub fn begin_parsing(&mut self, partial_ty: PartialType) { + pub(crate) fn begin_parsing(&mut self, partial_ty: PartialType) { self.currently_parsed_types.push(partial_ty); } /// Finish parsing the current partial type, pop it off the /// `currently_parsed_types` stack, and return it. - pub fn finish_parsing(&mut self) -> PartialType { + pub(crate) fn finish_parsing(&mut self) -> PartialType { self.currently_parsed_types.pop().expect( "should have been parsing a type, if we finished parsing a type", ) } /// Add another path to the set of included files. - pub fn include_file(&mut self, filename: String) { + pub(crate) fn include_file(&mut self, filename: String) { for cb in &self.options().parse_callbacks { cb.include_file(&filename); } @@ -645,7 +648,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Get any included files. - pub fn deps(&self) -> &BTreeSet { + pub(crate) fn deps(&self) -> &BTreeSet { &self.deps } @@ -653,7 +656,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// /// This inserts it into the internal items set, and its type into the /// internal types set. - pub fn add_item( + pub(crate) fn add_item( &mut self, item: Item, declaration: Option, @@ -778,7 +781,11 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Add a new named template type parameter to this context's item set. - pub fn add_type_param(&mut self, item: Item, definition: clang::Cursor) { + pub(crate) fn add_type_param( + &mut self, + item: Item, + definition: clang::Cursor, + ) { debug!( "BindgenContext::add_type_param: item = {:?}; definition = {:?}", item, definition @@ -813,7 +820,10 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Get the named type defined at the given cursor location, if we've /// already added one. - pub fn get_type_param(&self, definition: &clang::Cursor) -> Option { + pub(crate) fn get_type_param( + &self, + definition: &clang::Cursor, + ) -> Option { assert_eq!( definition.kind(), clang_sys::CXCursor_TemplateTypeParameter @@ -825,7 +835,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Mangles a name so it doesn't conflict with any keyword. #[rustfmt::skip] - pub fn rust_mangle<'a>(&self, name: &'a str) -> Cow<'a, str> { + pub(crate) fn rust_mangle<'a>(&self, name: &'a str) -> Cow<'a, str> { if name.contains('@') || name.contains('?') || name.contains('$') || @@ -856,7 +866,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Returns a mangled name as a rust identifier. - pub fn rust_ident(&self, name: S) -> Ident + pub(crate) fn rust_ident(&self, name: S) -> Ident where S: AsRef, { @@ -864,7 +874,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Returns a mangled name as a rust identifier. - pub fn rust_ident_raw(&self, name: T) -> Ident + pub(crate) fn rust_ident_raw(&self, name: T) -> Ident where T: AsRef, { @@ -872,7 +882,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Iterate over all items that have been defined. - pub fn items(&self) -> impl Iterator { + pub(crate) fn items(&self) -> impl Iterator { self.items.iter().enumerate().filter_map(|(index, item)| { let item = item.as_ref()?; Some((ItemId(index), item)) @@ -880,7 +890,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Have we collected all unresolved type references yet? - pub fn collected_typerefs(&self) -> bool { + pub(crate) fn collected_typerefs(&self) -> bool { self.collected_typerefs } @@ -1264,7 +1274,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Look up whether the type with the given id is sized or not. - pub fn lookup_sizedness(&self, id: TypeId) -> SizednessResult { + pub(crate) fn lookup_sizedness(&self, id: TypeId) -> SizednessResult { assert!( self.in_codegen_phase(), "We only compute sizedness after we've entered codegen" @@ -1286,7 +1296,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Look up whether the item with `id` has vtable or not. - pub fn lookup_has_vtable(&self, id: TypeId) -> HasVtableResult { + pub(crate) fn lookup_has_vtable(&self, id: TypeId) -> HasVtableResult { assert!( self.in_codegen_phase(), "We only compute vtables when we enter codegen" @@ -1310,7 +1320,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Look up whether the item with `id` has a destructor. - pub fn lookup_has_destructor(&self, id: TypeId) -> bool { + pub(crate) fn lookup_has_destructor(&self, id: TypeId) -> bool { assert!( self.in_codegen_phase(), "We only compute destructors when we enter codegen" @@ -1354,7 +1364,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// manually provide a definition for them. To give them the most /// flexibility when doing that, we assume that they use every template /// parameter and always pass template arguments through in instantiations. - pub fn uses_template_parameter( + pub(crate) fn uses_template_parameter( &self, item: ItemId, template_param: TypeId, @@ -1386,7 +1396,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// `false` otherwise. /// /// Has the same restrictions that `uses_template_parameter` has. - pub fn uses_any_template_parameters(&self, item: ItemId) -> bool { + pub(crate) fn uses_any_template_parameters(&self, item: ItemId) -> bool { assert!( self.in_codegen_phase(), "We only compute template parameter usage as we enter codegen" @@ -1424,7 +1434,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Get the root module. - pub fn root_module(&self) -> ModuleId { + pub(crate) fn root_module(&self) -> ModuleId { self.root_module } @@ -1432,7 +1442,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// /// Panics if there is no item for the given `TypeId` or if the resolved /// item is not a `Type`. - pub fn resolve_type(&self, type_id: TypeId) -> &Type { + pub(crate) fn resolve_type(&self, type_id: TypeId) -> &Type { self.resolve_item(type_id).kind().expect_type() } @@ -1440,7 +1450,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// /// Panics if there is no item for the given `FunctionId` or if the resolved /// item is not a `Function`. - pub fn resolve_func(&self, func_id: FunctionId) -> &Function { + pub(crate) fn resolve_func(&self, func_id: FunctionId) -> &Function { self.resolve_item(func_id).kind().expect_function() } @@ -1448,14 +1458,14 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// the given id. /// /// Panics if the id resolves to an item that is not a type. - pub fn safe_resolve_type(&self, type_id: TypeId) -> Option<&Type> { + pub(crate) fn safe_resolve_type(&self, type_id: TypeId) -> Option<&Type> { self.resolve_item_fallible(type_id) .map(|t| t.kind().expect_type()) } /// Resolve the given `ItemId` into an `Item`, or `None` if no such item /// exists. - pub fn resolve_item_fallible>( + pub(crate) fn resolve_item_fallible>( &self, id: Id, ) -> Option<&Item> { @@ -1465,7 +1475,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Resolve the given `ItemId` into an `Item`. /// /// Panics if the given id does not resolve to any item. - pub fn resolve_item>(&self, item_id: Id) -> &Item { + pub(crate) fn resolve_item>(&self, item_id: Id) -> &Item { let item_id = item_id.into(); match self.resolve_item_fallible(item_id) { Some(item) => item, @@ -1474,7 +1484,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Get the current module. - pub fn current_module(&self) -> ModuleId { + pub(crate) fn current_module(&self) -> ModuleId { self.current_module } @@ -1486,7 +1496,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// TODO(emilio): We could consider doing this only when /// declaration.lexical_parent() != definition.lexical_parent(), but it's /// not sure it's worth it. - pub fn add_semantic_parent( + pub(crate) fn add_semantic_parent( &mut self, definition: clang::Cursor, parent_id: ItemId, @@ -1495,7 +1505,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Returns a known semantic parent for a given definition. - pub fn known_semantic_parent( + pub(crate) fn known_semantic_parent( &self, definition: clang::Cursor, ) -> Option { @@ -1808,7 +1818,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// If we have already resolved the type for the given type declaration, /// return its `ItemId`. Otherwise, return `None`. - pub fn get_resolved_type( + pub(crate) fn get_resolved_type( &self, decl: &clang::CanonicalTypeDeclaration, ) -> Option { @@ -1824,7 +1834,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Looks up for an already resolved type, either because it's builtin, or /// because we already have it in the map. - pub fn builtin_or_resolved_ty( + pub(crate) fn builtin_or_resolved_ty( &mut self, with_id: ItemId, parent_id: Option, @@ -1894,7 +1904,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// We should probably make the constness tracking separate, so it doesn't /// bloat that much, but hey, we already bloat the heck out of builtin /// types. - pub fn build_ty_wrapper( + pub(crate) fn build_ty_wrapper( &mut self, with_id: ItemId, wrapped_id: TypeId, @@ -1907,7 +1917,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// A wrapper over a type that adds a const qualifier explicitly. /// /// Needed to handle const methods in C++, wrapping the type . - pub fn build_const_wrapper( + pub(crate) fn build_const_wrapper( &mut self, with_id: ItemId, wrapped_id: TypeId, @@ -1945,7 +1955,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Returns the next item id to be used for an item. - pub fn next_item_id(&mut self) -> ItemId { + pub(crate) fn next_item_id(&mut self) -> ItemId { let ret = ItemId(self.items.len()); self.items.push(None); ret @@ -2015,17 +2025,17 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Get the current Clang translation unit that is being processed. - pub fn translation_unit(&self) -> &clang::TranslationUnit { + pub(crate) fn translation_unit(&self) -> &clang::TranslationUnit { &self.translation_unit } /// Have we parsed the macro named `macro_name` already? - pub fn parsed_macro(&self, macro_name: &[u8]) -> bool { + pub(crate) fn parsed_macro(&self, macro_name: &[u8]) -> bool { self.parsed_macros.contains_key(macro_name) } /// Get the currently parsed macros. - pub fn parsed_macros( + pub(crate) fn parsed_macros( &self, ) -> &StdHashMap, cexpr::expr::EvalResult> { debug_assert!(!self.in_codegen_phase()); @@ -2033,7 +2043,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Mark the macro named `macro_name` as parsed. - pub fn note_parsed_macro( + pub(crate) fn note_parsed_macro( &mut self, id: Vec, value: cexpr::expr::EvalResult, @@ -2042,7 +2052,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Are we in the codegen phase? - pub fn in_codegen_phase(&self) -> bool { + pub(crate) fn in_codegen_phase(&self) -> bool { self.in_codegen } @@ -2051,7 +2061,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// /// Replacement types are declared using the `replaces="xxx"` annotation, /// and implies that the original type is hidden. - pub fn replace(&mut self, name: &[String], potential_ty: ItemId) { + pub(crate) fn replace(&mut self, name: &[String], potential_ty: ItemId) { match self.replacements.entry(name.into()) { Entry::Vacant(entry) => { debug!( @@ -2074,7 +2084,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Has the item with the given `name` and `id` been replaced by another /// type? - pub fn is_replaced_type>( + pub(crate) fn is_replaced_type>( &self, path: &[String], id: Id, @@ -2084,7 +2094,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Is the type with the given `name` marked as opaque? - pub fn opaque_by_name(&self, path: &[String]) -> bool { + pub(crate) fn opaque_by_name(&self, path: &[String]) -> bool { debug_assert!( self.in_codegen_phase(), "You're not supposed to call this yet" @@ -2178,7 +2188,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Given a CXCursor_Namespace cursor, return the item id of the /// corresponding module, or create one on the fly. - pub fn module(&mut self, cursor: clang::Cursor) -> ModuleId { + pub(crate) fn module(&mut self, cursor: clang::Cursor) -> ModuleId { use clang_sys::*; assert_eq!(cursor.kind(), CXCursor_Namespace, "Be a nice person"); let cursor = cursor.canonical(); @@ -2209,7 +2219,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Start traversing the module with the given `module_id`, invoke the /// callback `cb`, and then return to traversing the original module. - pub fn with_module(&mut self, module_id: ModuleId, cb: F) + pub(crate) fn with_module(&mut self, module_id: ModuleId, cb: F) where F: FnOnce(&mut Self), { @@ -2227,7 +2237,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// /// If no items are explicitly allowlisted, then all items are considered /// allowlisted. - pub fn allowlisted_items(&self) -> &ItemSet { + pub(crate) fn allowlisted_items(&self) -> &ItemSet { assert!(self.in_codegen_phase()); assert!(self.current_module == self.root_module); @@ -2236,7 +2246,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Check whether a particular blocklisted type implements a trait or not. /// Results may be cached. - pub fn blocklisted_type_implements_trait( + pub(crate) fn blocklisted_type_implements_trait( &self, item: &Item, derive_trait: DeriveTrait, @@ -2277,7 +2287,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Is the given type a type from that corresponds to a Rust primitive type? - pub fn is_stdint_type(&self, name: &str) -> bool { + pub(crate) fn is_stdint_type(&self, name: &str) -> bool { match name { "int8_t" | "uint8_t" | "int16_t" | "uint16_t" | "int32_t" | "uint32_t" | "int64_t" | "uint64_t" | "uintptr_t" | @@ -2288,7 +2298,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Get a reference to the set of items we should generate. - pub fn codegen_items(&self) -> &ItemSet { + pub(crate) fn codegen_items(&self) -> &ItemSet { assert!(self.in_codegen_phase()); assert!(self.current_module == self.root_module); self.codegen_items.as_ref().unwrap() @@ -2477,7 +2487,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Convenient method for getting the prefix to use for most traits in /// codegen depending on the `use_core` option. - pub fn trait_prefix(&self) -> Ident { + pub(crate) fn trait_prefix(&self) -> Ident { if self.options().use_core { self.rust_ident_raw("core") } else { @@ -2486,12 +2496,12 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Call if a bindgen complex is generated - pub fn generated_bindgen_complex(&self) { + pub(crate) fn generated_bindgen_complex(&self) { self.generated_bindgen_complex.set(true) } /// Whether we need to generate the bindgen complex type - pub fn need_bindgen_complex_type(&self) -> bool { + pub(crate) fn need_bindgen_complex_type(&self) -> bool { self.generated_bindgen_complex.get() } @@ -2551,7 +2561,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Look up whether `id` refers to an `enum` whose underlying type is /// defined by a `typedef`. - pub fn is_enum_typedef_combo(&self, id: ItemId) -> bool { + pub(crate) fn is_enum_typedef_combo(&self, id: ItemId) -> bool { assert!( self.in_codegen_phase(), "We only compute enum_typedef_combos when we enter codegen", @@ -2574,7 +2584,10 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Look up whether the item with `id` can /// derive debug or not. - pub fn lookup_can_derive_debug>(&self, id: Id) -> bool { + pub(crate) fn lookup_can_derive_debug>( + &self, + id: Id, + ) -> bool { let id = id.into(); assert!( self.in_codegen_phase(), @@ -2601,7 +2614,10 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Look up whether the item with `id` can /// derive default or not. - pub fn lookup_can_derive_default>(&self, id: Id) -> bool { + pub(crate) fn lookup_can_derive_default>( + &self, + id: Id, + ) -> bool { let id = id.into(); assert!( self.in_codegen_phase(), @@ -2639,7 +2655,10 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Look up whether the item with `id` can /// derive hash or not. - pub fn lookup_can_derive_hash>(&self, id: Id) -> bool { + pub(crate) fn lookup_can_derive_hash>( + &self, + id: Id, + ) -> bool { let id = id.into(); assert!( self.in_codegen_phase(), @@ -2668,7 +2687,9 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Look up whether the item with `id` can derive `Partial{Eq,Ord}`. - pub fn lookup_can_derive_partialeq_or_partialord>( + pub(crate) fn lookup_can_derive_partialeq_or_partialord< + Id: Into, + >( &self, id: Id, ) -> CanDerive { @@ -2689,7 +2710,10 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Look up whether the item with `id` can derive `Copy` or not. - pub fn lookup_can_derive_copy>(&self, id: Id) -> bool { + pub(crate) fn lookup_can_derive_copy>( + &self, + id: Id, + ) -> bool { assert!( self.in_codegen_phase(), "We only compute can_derive_debug when we enter codegen" @@ -2712,7 +2736,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Look up whether the item with `id` has type parameter in array or not. - pub fn lookup_has_type_param_in_array>( + pub(crate) fn lookup_has_type_param_in_array>( &self, id: Id, ) -> bool { @@ -2739,7 +2763,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Look up whether the item with `id` has array or not. - pub fn lookup_has_float>(&self, id: Id) -> bool { + pub(crate) fn lookup_has_float>(&self, id: Id) -> bool { assert!( self.in_codegen_phase(), "We only compute has float when we enter codegen" @@ -2751,41 +2775,42 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Check if `--no-partialeq` flag is enabled for this item. - pub fn no_partialeq_by_name(&self, item: &Item) -> bool { + pub(crate) fn no_partialeq_by_name(&self, item: &Item) -> bool { let name = item.path_for_allowlisting(self)[1..].join("::"); self.options().no_partialeq_types.matches(name) } /// Check if `--no-copy` flag is enabled for this item. - pub fn no_copy_by_name(&self, item: &Item) -> bool { + pub(crate) fn no_copy_by_name(&self, item: &Item) -> bool { let name = item.path_for_allowlisting(self)[1..].join("::"); self.options().no_copy_types.matches(name) } /// Check if `--no-debug` flag is enabled for this item. - pub fn no_debug_by_name(&self, item: &Item) -> bool { + pub(crate) fn no_debug_by_name(&self, item: &Item) -> bool { let name = item.path_for_allowlisting(self)[1..].join("::"); self.options().no_debug_types.matches(name) } /// Check if `--no-default` flag is enabled for this item. - pub fn no_default_by_name(&self, item: &Item) -> bool { + pub(crate) fn no_default_by_name(&self, item: &Item) -> bool { let name = item.path_for_allowlisting(self)[1..].join("::"); self.options().no_default_types.matches(name) } /// Check if `--no-hash` flag is enabled for this item. - pub fn no_hash_by_name(&self, item: &Item) -> bool { + pub(crate) fn no_hash_by_name(&self, item: &Item) -> bool { let name = item.path_for_allowlisting(self)[1..].join("::"); self.options().no_hash_types.matches(name) } /// Check if `--must-use-type` flag is enabled for this item. - pub fn must_use_type_by_name(&self, item: &Item) -> bool { + pub(crate) fn must_use_type_by_name(&self, item: &Item) -> bool { let name = item.path_for_allowlisting(self)[1..].join("::"); self.options().must_use_types.matches(name) } + /// Wrap some tokens in an `unsafe` block if the `--wrap-unsafe-ops` option is enabled. pub(crate) fn wrap_unsafe_ops(&self, tokens: impl ToTokens) -> TokenStream { if self.options.wrap_unsafe_ops { quote!(unsafe { #tokens }) @@ -2794,6 +2819,8 @@ If you encounter an error missing from this list, please file an issue or a PR!" } } + /// Get the suffix to be added to `static` functions if the `--wrap-static-fns` option is + /// enabled. pub(crate) fn wrap_static_fns_suffix(&self) -> &str { self.options() .wrap_static_fns_suffix @@ -2804,7 +2831,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// A builder struct for configuring item resolution options. #[derive(Debug, Copy, Clone)] -pub struct ItemResolver { +pub(crate) struct ItemResolver { id: ItemId, through_type_refs: bool, through_type_aliases: bool, @@ -2812,7 +2839,7 @@ pub struct ItemResolver { impl ItemId { /// Create an `ItemResolver` from this item id. - pub fn into_resolver(self) -> ItemResolver { + pub(crate) fn into_resolver(self) -> ItemResolver { self.into() } } @@ -2828,7 +2855,7 @@ where impl ItemResolver { /// Construct a new `ItemResolver` from the given id. - pub fn new>(id: Id) -> ItemResolver { + pub(crate) fn new>(id: Id) -> ItemResolver { let id = id.into(); ItemResolver { id, @@ -2838,19 +2865,19 @@ impl ItemResolver { } /// Keep resolving through `Type::TypeRef` items. - pub fn through_type_refs(mut self) -> ItemResolver { + pub(crate) fn through_type_refs(mut self) -> ItemResolver { self.through_type_refs = true; self } /// Keep resolving through `Type::Alias` items. - pub fn through_type_aliases(mut self) -> ItemResolver { + pub(crate) fn through_type_aliases(mut self) -> ItemResolver { self.through_type_aliases = true; self } /// Finish configuring and perform the actual item resolution. - pub fn resolve(self, ctx: &BindgenContext) -> &Item { + pub(crate) fn resolve(self, ctx: &BindgenContext) -> &Item { assert!(ctx.collected_typerefs()); let mut id = self.id; @@ -2887,7 +2914,7 @@ impl ItemResolver { /// A type that we are in the middle of parsing. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct PartialType { +pub(crate) struct PartialType { decl: Cursor, // Just an ItemId, and not a TypeId, because we haven't finished this type // yet, so there's still time for things to go wrong. @@ -2896,19 +2923,19 @@ pub struct PartialType { impl PartialType { /// Construct a new `PartialType`. - pub fn new(decl: Cursor, id: ItemId) -> PartialType { + pub(crate) fn new(decl: Cursor, id: ItemId) -> PartialType { // assert!(decl == decl.canonical()); PartialType { decl, id } } /// The cursor pointing to this partial type's declaration location. - pub fn decl(&self) -> &Cursor { + pub(crate) fn decl(&self) -> &Cursor { &self.decl } /// The item ID allocated for this type. This is *NOT* a key for an entry in /// the context's item set yet! - pub fn id(&self) -> ItemId { + pub(crate) fn id(&self) -> ItemId { self.id } } diff --git a/bindgen/ir/derive.rs b/bindgen/ir/derive.rs index 594ce2ab8f..3877b42f8f 100644 --- a/bindgen/ir/derive.rs +++ b/bindgen/ir/derive.rs @@ -18,7 +18,7 @@ use std::ops; /// A trait that encapsulates the logic for whether or not we can derive `Debug` /// for a given thing. -pub trait CanDeriveDebug { +pub(crate) trait CanDeriveDebug { /// Return `true` if `Debug` can be derived for this thing, `false` /// otherwise. fn can_derive_debug(&self, ctx: &BindgenContext) -> bool; @@ -26,7 +26,7 @@ pub trait CanDeriveDebug { /// A trait that encapsulates the logic for whether or not we can derive `Copy` /// for a given thing. -pub trait CanDeriveCopy { +pub(crate) trait CanDeriveCopy { /// Return `true` if `Copy` can be derived for this thing, `false` /// otherwise. fn can_derive_copy(&self, ctx: &BindgenContext) -> bool; @@ -34,7 +34,7 @@ pub trait CanDeriveCopy { /// A trait that encapsulates the logic for whether or not we can derive /// `Default` for a given thing. -pub trait CanDeriveDefault { +pub(crate) trait CanDeriveDefault { /// Return `true` if `Default` can be derived for this thing, `false` /// otherwise. fn can_derive_default(&self, ctx: &BindgenContext) -> bool; @@ -42,7 +42,7 @@ pub trait CanDeriveDefault { /// A trait that encapsulates the logic for whether or not we can derive `Hash` /// for a given thing. -pub trait CanDeriveHash { +pub(crate) trait CanDeriveHash { /// Return `true` if `Hash` can be derived for this thing, `false` /// otherwise. fn can_derive_hash(&self, ctx: &BindgenContext) -> bool; @@ -50,7 +50,7 @@ pub trait CanDeriveHash { /// A trait that encapsulates the logic for whether or not we can derive /// `PartialEq` for a given thing. -pub trait CanDerivePartialEq { +pub(crate) trait CanDerivePartialEq { /// Return `true` if `PartialEq` can be derived for this thing, `false` /// otherwise. fn can_derive_partialeq(&self, ctx: &BindgenContext) -> bool; @@ -58,7 +58,7 @@ pub trait CanDerivePartialEq { /// A trait that encapsulates the logic for whether or not we can derive /// `PartialOrd` for a given thing. -pub trait CanDerivePartialOrd { +pub(crate) trait CanDerivePartialOrd { /// Return `true` if `PartialOrd` can be derived for this thing, `false` /// otherwise. fn can_derive_partialord(&self, ctx: &BindgenContext) -> bool; @@ -66,14 +66,14 @@ pub trait CanDerivePartialOrd { /// A trait that encapsulates the logic for whether or not we can derive `Eq` /// for a given thing. -pub trait CanDeriveEq { +pub(crate) trait CanDeriveEq { /// Return `true` if `Eq` can be derived for this thing, `false` otherwise. fn can_derive_eq(&self, ctx: &BindgenContext) -> bool; } /// A trait that encapsulates the logic for whether or not we can derive `Ord` /// for a given thing. -pub trait CanDeriveOrd { +pub(crate) trait CanDeriveOrd { /// Return `true` if `Ord` can be derived for this thing, `false` otherwise. fn can_derive_ord(&self, ctx: &BindgenContext) -> bool; } @@ -115,7 +115,7 @@ impl Default for CanDerive { impl CanDerive { /// Take the least upper bound of `self` and `rhs`. - pub fn join(self, rhs: Self) -> Self { + pub(crate) fn join(self, rhs: Self) -> Self { cmp::max(self, rhs) } } diff --git a/bindgen/ir/dot.rs b/bindgen/ir/dot.rs index f7d07f19e2..d5c1a42fdc 100644 --- a/bindgen/ir/dot.rs +++ b/bindgen/ir/dot.rs @@ -8,7 +8,7 @@ use std::path::Path; /// A trait for anything that can write attributes as `` rows to a dot /// file. -pub trait DotAttributes { +pub(crate) trait DotAttributes { /// Write this thing's attributes to the given output. Each attribute must /// be its own `...`. fn dot_attributes( @@ -21,7 +21,7 @@ pub trait DotAttributes { } /// Write a graphviz dot file containing our IR. -pub fn write_dot_file

(ctx: &BindgenContext, path: P) -> io::Result<()> +pub(crate) fn write_dot_file

(ctx: &BindgenContext, path: P) -> io::Result<()> where P: AsRef, { diff --git a/bindgen/ir/enum_ty.rs b/bindgen/ir/enum_ty.rs index 63871fd465..70cf0eae88 100644 --- a/bindgen/ir/enum_ty.rs +++ b/bindgen/ir/enum_ty.rs @@ -22,7 +22,7 @@ pub enum EnumVariantCustomBehavior { /// A C/C++ enumeration. #[derive(Debug)] -pub struct Enum { +pub(crate) struct Enum { /// The representation used for this enum; it should be an `IntKind` type or /// an alias to one. /// @@ -36,22 +36,25 @@ pub struct Enum { impl Enum { /// Construct a new `Enum` with the given representation and variants. - pub fn new(repr: Option, variants: Vec) -> Self { + pub(crate) fn new( + repr: Option, + variants: Vec, + ) -> Self { Enum { repr, variants } } /// Get this enumeration's representation. - pub fn repr(&self) -> Option { + pub(crate) fn repr(&self) -> Option { self.repr } /// Get this enumeration's variants. - pub fn variants(&self) -> &[EnumVariant] { + pub(crate) fn variants(&self) -> &[EnumVariant] { &self.variants } /// Construct an enumeration from the given Clang type. - pub fn from_ty( + pub(crate) fn from_ty( ty: &clang::Type, ctx: &mut BindgenContext, ) -> Result { @@ -169,7 +172,7 @@ impl Enum { } /// Returns the final representation of the enum. - pub fn computed_enum_variation( + pub(crate) fn computed_enum_variation( &self, ctx: &BindgenContext, item: &Item, @@ -236,7 +239,7 @@ impl Enum { /// A single enum variant, to be contained only in an enum. #[derive(Debug)] -pub struct EnumVariant { +pub(crate) struct EnumVariant { /// The name of the variant. name: String, @@ -268,7 +271,7 @@ pub enum EnumVariantValue { impl EnumVariant { /// Construct a new enumeration variant from the given parts. - pub fn new( + pub(crate) fn new( name: String, name_for_allowlisting: String, comment: Option, @@ -285,35 +288,35 @@ impl EnumVariant { } /// Get this variant's name. - pub fn name(&self) -> &str { + pub(crate) fn name(&self) -> &str { &self.name } /// Get this variant's name. - pub fn name_for_allowlisting(&self) -> &str { + pub(crate) fn name_for_allowlisting(&self) -> &str { &self.name_for_allowlisting } /// Get this variant's value. - pub fn val(&self) -> EnumVariantValue { + pub(crate) fn val(&self) -> EnumVariantValue { self.val } /// Get this variant's documentation. - pub fn comment(&self) -> Option<&str> { + pub(crate) fn comment(&self) -> Option<&str> { self.comment.as_deref() } /// Returns whether this variant should be enforced to be a constant by code /// generation. - pub fn force_constification(&self) -> bool { + pub(crate) fn force_constification(&self) -> bool { self.custom_behavior .map_or(false, |b| b == EnumVariantCustomBehavior::Constify) } /// Returns whether the current variant should be hidden completely from the /// resulting rust enum. - pub fn hidden(&self) -> bool { + pub(crate) fn hidden(&self) -> bool { self.custom_behavior .map_or(false, |b| b == EnumVariantCustomBehavior::Hide) } diff --git a/bindgen/ir/function.rs b/bindgen/ir/function.rs index baa2c36ca4..dccd9b2467 100644 --- a/bindgen/ir/function.rs +++ b/bindgen/ir/function.rs @@ -20,7 +20,7 @@ const RUST_DERIVE_FUNPTR_LIMIT: usize = 12; /// What kind of a function are we looking at? #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum FunctionKind { +pub(crate) enum FunctionKind { /// A plain, free function. Function, /// A method of some kind. @@ -30,7 +30,7 @@ pub enum FunctionKind { impl FunctionKind { /// Given a clang cursor, return the kind of function it represents, or /// `None` otherwise. - pub fn from_cursor(cursor: &clang::Cursor) -> Option { + pub(crate) fn from_cursor(cursor: &clang::Cursor) -> Option { // FIXME(emilio): Deduplicate logic with `ir::comp`. Some(match cursor.kind() { clang_sys::CXCursor_FunctionDecl => FunctionKind::Function, @@ -64,7 +64,7 @@ impl FunctionKind { /// The style of linkage #[derive(Debug, Clone, Copy)] -pub enum Linkage { +pub(crate) enum Linkage { /// Externally visible and can be linked against External, /// Not exposed externally. 'static inline' functions will have this kind of linkage @@ -76,7 +76,7 @@ pub enum Linkage { /// The argument names vector must be the same length as the ones in the /// signature. #[derive(Debug)] -pub struct Function { +pub(crate) struct Function { /// The name of this function. name: String, @@ -86,9 +86,6 @@ pub struct Function { /// The id pointing to the current function signature. signature: TypeId, - /// The doc comment on the function, if any. - comment: Option, - /// The kind of function this is. kind: FunctionKind, @@ -98,11 +95,10 @@ pub struct Function { impl Function { /// Construct a new function. - pub fn new( + pub(crate) fn new( name: String, mangled_name: Option, signature: TypeId, - comment: Option, kind: FunctionKind, linkage: Linkage, ) -> Self { @@ -110,39 +106,33 @@ impl Function { name, mangled_name, signature, - comment, kind, linkage, } } /// Get this function's name. - pub fn name(&self) -> &str { + pub(crate) fn name(&self) -> &str { &self.name } /// Get this function's name. - pub fn mangled_name(&self) -> Option<&str> { + pub(crate) fn mangled_name(&self) -> Option<&str> { self.mangled_name.as_deref() } /// Get this function's signature type. - pub fn signature(&self) -> TypeId { + pub(crate) fn signature(&self) -> TypeId { self.signature } - /// Get this function's comment. - pub fn comment(&self) -> Option<&str> { - self.comment.as_deref() - } - /// Get this function's kind. - pub fn kind(&self) -> FunctionKind { + pub(crate) fn kind(&self) -> FunctionKind { self.kind } /// Get this function's linkage. - pub fn linkage(&self) -> Linkage { + pub(crate) fn linkage(&self) -> Linkage { self.linkage } } @@ -236,6 +226,7 @@ impl quote::ToTokens for Abi { /// An ABI extracted from a clang cursor. #[derive(Debug, Copy, Clone)] pub(crate) enum ClangAbi { + /// An ABI known by rust. Known(Abi), /// An unknown or invalid ABI. Unknown(CXCallingConv), @@ -262,7 +253,7 @@ impl quote::ToTokens for ClangAbi { /// A function signature. #[derive(Debug)] -pub struct FunctionSig { +pub(crate) struct FunctionSig { /// The return type of the function. return_type: TypeId, @@ -297,7 +288,7 @@ fn get_abi(cc: CXCallingConv) -> ClangAbi { } /// Get the mangled name for the cursor's referent. -pub fn cursor_mangling( +pub(crate) fn cursor_mangling( ctx: &BindgenContext, cursor: &clang::Cursor, ) -> Option { @@ -399,7 +390,7 @@ fn args_from_ty_and_cursor( impl FunctionSig { /// Construct a new function signature from the given Clang type. - pub fn from_ty( + pub(crate) fn from_ty( ty: &clang::Type, cursor: &clang::Cursor, ctx: &mut BindgenContext, @@ -583,12 +574,12 @@ impl FunctionSig { } /// Get this function signature's return type. - pub fn return_type(&self) -> TypeId { + pub(crate) fn return_type(&self) -> TypeId { self.return_type } /// Get this function signature's argument (name, type) pairs. - pub fn argument_types(&self) -> &[(Option, TypeId)] { + pub(crate) fn argument_types(&self) -> &[(Option, TypeId)] { &self.argument_types } @@ -617,7 +608,7 @@ impl FunctionSig { } /// Is this function signature variadic? - pub fn is_variadic(&self) -> bool { + pub(crate) fn is_variadic(&self) -> bool { // Clang reports some functions as variadic when they *might* be // variadic. We do the argument check because rust doesn't codegen well // variadic functions without an initial argument. @@ -625,7 +616,7 @@ impl FunctionSig { } /// Must this function's return value be used? - pub fn must_use(&self) -> bool { + pub(crate) fn must_use(&self) -> bool { self.must_use } @@ -638,7 +629,7 @@ impl FunctionSig { /// * https://github.com/rust-lang/rust-bindgen/issues/547, /// * https://github.com/rust-lang/rust/issues/38848, /// * and https://github.com/rust-lang/rust/issues/40158 - pub fn function_pointers_can_derive(&self) -> bool { + pub(crate) fn function_pointers_can_derive(&self) -> bool { if self.argument_types.len() > RUST_DERIVE_FUNPTR_LIMIT { return false; } @@ -646,6 +637,7 @@ impl FunctionSig { matches!(self.abi, ClangAbi::Known(Abi::C) | ClangAbi::Unknown(..)) } + /// Whether this function has attributes marking it as divergent. pub(crate) fn is_divergent(&self) -> bool { self.is_divergent } @@ -734,10 +726,9 @@ impl ClangSubItemParser for Function { assert!(!name.is_empty(), "Empty function name."); let mangled_name = cursor_mangling(context, &cursor); - let comment = cursor.raw_comment(); let function = - Self::new(name.clone(), mangled_name, sig, comment, kind, linkage); + Self::new(name.clone(), mangled_name, sig, kind, linkage); Ok(ParseResult::New(function, Some(cursor))) } diff --git a/bindgen/ir/int.rs b/bindgen/ir/int.rs index 22838e897c..bb3032dbcf 100644 --- a/bindgen/ir/int.rs +++ b/bindgen/ir/int.rs @@ -87,7 +87,7 @@ pub enum IntKind { impl IntKind { /// Is this integral type signed? - pub fn is_signed(&self) -> bool { + pub(crate) fn is_signed(&self) -> bool { use self::IntKind::*; match *self { // TODO(emilio): wchar_t can in theory be signed, but we have no way @@ -108,7 +108,7 @@ impl IntKind { /// If this type has a known size, return it (in bytes). This is to /// alleviate libclang sometimes not giving us a layout (like in the case /// when an enum is defined inside a class with template parameters). - pub fn known_size(&self) -> Option { + pub(crate) fn known_size(&self) -> Option { use self::IntKind::*; Some(match *self { Bool | UChar | SChar | U8 | I8 | Char { .. } => 1, @@ -121,7 +121,7 @@ impl IntKind { } /// Whether this type's signedness matches the value. - pub fn signedness_matches(&self, val: i64) -> bool { + pub(crate) fn signedness_matches(&self, val: i64) -> bool { val >= 0 || self.is_signed() } } diff --git a/bindgen/ir/item.rs b/bindgen/ir/item.rs index 40f6f7d927..2492fe8fe4 100644 --- a/bindgen/ir/item.rs +++ b/bindgen/ir/item.rs @@ -38,7 +38,7 @@ use std::iter; /// /// This name is required to be safe for Rust, that is, is not expected to /// return any rust keyword from here. -pub trait ItemCanonicalName { +pub(crate) trait ItemCanonicalName { /// Get the canonical name for this item. fn canonical_name(&self, ctx: &BindgenContext) -> String; } @@ -55,7 +55,7 @@ pub trait ItemCanonicalName { /// /// For bar, the canonical path is `vec!["foo", "BAR"]`, while the canonical /// name is just `"BAR"`. -pub trait ItemCanonicalPath { +pub(crate) trait ItemCanonicalPath { /// Get the namespace-aware canonical path for this item. This means that if /// namespaces are disabled, you'll get a single item, and otherwise you get /// the whole path. @@ -69,7 +69,7 @@ pub trait ItemCanonicalPath { } /// A trait for determining if some IR thing is opaque or not. -pub trait IsOpaque { +pub(crate) trait IsOpaque { /// Extra context the IR thing needs to determine if it is opaque or not. type Extra; @@ -80,20 +80,20 @@ pub trait IsOpaque { } /// A trait for determining if some IR thing has type parameter in array or not. -pub trait HasTypeParamInArray { +pub(crate) trait HasTypeParamInArray { /// Returns `true` if the thing has Array, and `false` otherwise. fn has_type_param_in_array(&self, ctx: &BindgenContext) -> bool; } /// A trait for determining if some IR thing has float or not. -pub trait HasFloat { +pub(crate) trait HasFloat { /// Returns `true` if the thing has float, and `false` otherwise. fn has_float(&self, ctx: &BindgenContext) -> bool; } /// A trait for iterating over an item and its parents and up its ancestor chain /// up to (but not including) the implicit root module. -pub trait ItemAncestors { +pub(crate) trait ItemAncestors { /// Get an iterable over this item's ancestors. fn ancestors<'a>(&self, ctx: &'a BindgenContext) -> ItemAncestorsIter<'a>; } @@ -118,7 +118,7 @@ impl DebugOnlyItemSet { } /// An iterator over an item and its ancestors. -pub struct ItemAncestorsIter<'a> { +pub(crate) struct ItemAncestorsIter<'a> { item: ItemId, ctx: &'a BindgenContext, seen: DebugOnlyItemSet, @@ -375,7 +375,7 @@ impl CanDeriveOrd for Item { /// all of them apply to every item. Those rules are described in the /// `annotations` module. #[derive(Debug)] -pub struct Item { +pub(crate) struct Item { /// This item's id. id: ItemId, @@ -426,7 +426,7 @@ impl AsRef for Item { impl Item { /// Construct a new `Item`. - pub fn new( + pub(crate) fn new( id: ItemId, comment: Option, annotations: Option, @@ -450,7 +450,7 @@ impl Item { } /// Construct a new opaque item type. - pub fn new_opaque_type( + pub(crate) fn new_opaque_type( with_id: ItemId, ty: &clang::Type, ctx: &mut BindgenContext, @@ -468,28 +468,31 @@ impl Item { } /// Get this `Item`'s identifier. - pub fn id(&self) -> ItemId { + pub(crate) fn id(&self) -> ItemId { self.id } /// Get this `Item`'s parent's identifier. /// /// For the root module, the parent's ID is its own ID. - pub fn parent_id(&self) -> ItemId { + pub(crate) fn parent_id(&self) -> ItemId { self.parent_id } /// Set this item's parent id. /// /// This is only used so replacements get generated in the proper module. - pub fn set_parent_for_replacement>(&mut self, id: Id) { + pub(crate) fn set_parent_for_replacement>( + &mut self, + id: Id, + ) { self.parent_id = id.into(); } /// Returns the depth this item is indented to. /// /// FIXME(emilio): This may need fixes for the enums within modules stuff. - pub fn codegen_depth(&self, ctx: &BindgenContext) -> usize { + pub(crate) fn codegen_depth(&self, ctx: &BindgenContext) -> usize { if !ctx.options().enable_cxx_namespaces { return 0; } @@ -507,7 +510,7 @@ impl Item { /// Get this `Item`'s comment, if it has any, already preprocessed and with /// the right indentation. - pub fn comment(&self, ctx: &BindgenContext) -> Option { + pub(crate) fn comment(&self, ctx: &BindgenContext) -> Option { if !ctx.options().generate_comments { return None; } @@ -518,17 +521,17 @@ impl Item { } /// What kind of item is this? - pub fn kind(&self) -> &ItemKind { + pub(crate) fn kind(&self) -> &ItemKind { &self.kind } /// Get a mutable reference to this item's kind. - pub fn kind_mut(&mut self) -> &mut ItemKind { + pub(crate) fn kind_mut(&mut self) -> &mut ItemKind { &mut self.kind } /// Where in the source is this item located? - pub fn location(&self) -> Option<&clang::SourceLocation> { + pub(crate) fn location(&self) -> Option<&clang::SourceLocation> { self.location.as_ref() } @@ -537,7 +540,7 @@ impl Item { /// This should stay relatively stable in the face of code motion outside or /// below this item's lexical scope, meaning that this can be useful for /// generating relatively stable identifiers within a scope. - pub fn local_id(&self, ctx: &BindgenContext) -> usize { + pub(crate) fn local_id(&self, ctx: &BindgenContext) -> usize { *self.local_id.borrow_with(|| { let parent = ctx.resolve_item(self.parent_id); parent.next_child_local_id() @@ -550,7 +553,7 @@ impl Item { /// This is currently used for anonymous items, and template instantiation /// tests, in both cases in order to reduce noise when system headers are at /// place. - pub fn next_child_local_id(&self) -> usize { + pub(crate) fn next_child_local_id(&self) -> usize { let local_id = self.next_child_local_id.get(); self.next_child_local_id.set(local_id + 1); local_id @@ -574,7 +577,7 @@ impl Item { /// This function is used to determine when the codegen phase should call /// `codegen` on an item, since any item that is not top-level will be /// generated by its parent. - pub fn is_toplevel(&self, ctx: &BindgenContext) -> bool { + pub(crate) fn is_toplevel(&self, ctx: &BindgenContext) -> bool { // FIXME: Workaround for some types falling behind when parsing weird // stl classes, for example. if ctx.options().enable_cxx_namespaces && @@ -605,36 +608,36 @@ impl Item { /// Get a reference to this item's underlying `Type`. Panic if this is some /// other kind of item. - pub fn expect_type(&self) -> &Type { + pub(crate) fn expect_type(&self) -> &Type { self.kind().expect_type() } /// Get a reference to this item's underlying `Type`, or `None` if this is /// some other kind of item. - pub fn as_type(&self) -> Option<&Type> { + pub(crate) fn as_type(&self) -> Option<&Type> { self.kind().as_type() } /// Get a reference to this item's underlying `Function`. Panic if this is /// some other kind of item. - pub fn expect_function(&self) -> &Function { + pub(crate) fn expect_function(&self) -> &Function { self.kind().expect_function() } /// Is this item a module? - pub fn is_module(&self) -> bool { + pub(crate) fn is_module(&self) -> bool { matches!(self.kind, ItemKind::Module(..)) } /// Get this item's annotations. - pub fn annotations(&self) -> &Annotations { + pub(crate) fn annotations(&self) -> &Annotations { &self.annotations } /// Whether this item should be blocklisted. /// /// This may be due to either annotations or to other kind of configuration. - pub fn is_blocklisted(&self, ctx: &BindgenContext) -> bool { + pub(crate) fn is_blocklisted(&self, ctx: &BindgenContext) -> bool { debug_assert!( ctx.in_codegen_phase(), "You're not supposed to call this yet" @@ -670,18 +673,11 @@ impl Item { } } - /// Is this a reference to another type? - pub fn is_type_ref(&self) -> bool { - self.as_type().map_or(false, |ty| ty.is_type_ref()) - } - - /// Is this item a var type? - pub fn is_var(&self) -> bool { - matches!(*self.kind(), ItemKind::Var(..)) - } - /// Take out item NameOptions - pub fn name<'a>(&'a self, ctx: &'a BindgenContext) -> NameOptions<'a> { + pub(crate) fn name<'a>( + &'a self, + ctx: &'a BindgenContext, + ) -> NameOptions<'a> { NameOptions::new(self, ctx) } @@ -715,7 +711,10 @@ impl Item { /// Create a fully disambiguated name for an item, including template /// parameters if it is a type - pub fn full_disambiguated_name(&self, ctx: &BindgenContext) -> String { + pub(crate) fn full_disambiguated_name( + &self, + ctx: &BindgenContext, + ) -> String { let mut s = String::new(); let level = 0; self.push_disambiguated_name(ctx, &mut s, level); @@ -839,7 +838,7 @@ impl Item { /// If `BindgenOptions::disable_nested_struct_naming` is true then returned /// name is the inner most non-anonymous name plus all the anonymous base names /// that follows. - pub fn real_canonical_name( + pub(crate) fn real_canonical_name( &self, ctx: &BindgenContext, opt: &NameOptions, @@ -941,7 +940,7 @@ impl Item { /// The exposed id that represents an unique id among the siblings of a /// given item. - pub fn exposed_id(&self, ctx: &BindgenContext) -> String { + pub(crate) fn exposed_id(&self, ctx: &BindgenContext) -> String { // Only use local ids for enums, classes, structs and union types. All // other items use their global id. let ty_kind = self.kind().as_type().map(|t| t.kind()); @@ -962,7 +961,7 @@ impl Item { /// Get a reference to this item's `Module`, or `None` if this is not a /// `Module` item. - pub fn as_module(&self) -> Option<&Module> { + pub(crate) fn as_module(&self) -> Option<&Module> { match self.kind { ItemKind::Module(ref module) => Some(module), _ => None, @@ -971,7 +970,7 @@ impl Item { /// Get a mutable reference to this item's `Module`, or `None` if this is /// not a `Module` item. - pub fn as_module_mut(&mut self) -> Option<&mut Module> { + pub(crate) fn as_module_mut(&mut self) -> Option<&mut Module> { match self.kind { ItemKind::Module(ref mut module) => Some(module), _ => None, @@ -1010,7 +1009,7 @@ impl Item { } /// Is this item of a kind that is enabled for code generation? - pub fn is_enabled_for_codegen(&self, ctx: &BindgenContext) -> bool { + pub(crate) fn is_enabled_for_codegen(&self, ctx: &BindgenContext) -> bool { let cc = &ctx.options().codegen_config; match *self.kind() { ItemKind::Module(..) => true, @@ -1036,7 +1035,10 @@ impl Item { /// Returns the path we should use for allowlisting / blocklisting, which /// doesn't include user-mangling. - pub fn path_for_allowlisting(&self, ctx: &BindgenContext) -> &Vec { + pub(crate) fn path_for_allowlisting( + &self, + ctx: &BindgenContext, + ) -> &Vec { self.path_for_allowlisting .borrow_with(|| self.compute_path(ctx, UserMangled::No)) } @@ -1095,7 +1097,7 @@ impl Item { } /// Whether this is a #[must_use] type. - pub fn must_use(&self, ctx: &BindgenContext) -> bool { + pub(crate) fn must_use(&self, ctx: &BindgenContext) -> bool { self.annotations().must_use_type() || ctx.must_use_type_by_name(self) } } @@ -1222,7 +1224,7 @@ impl HasFloat for Item { } /// A set of items. -pub type ItemSet = BTreeSet; +pub(crate) type ItemSet = BTreeSet; impl DotAttributes for Item { fn dot_attributes( @@ -1306,6 +1308,7 @@ fn visit_child( } impl Item { + /// Create a builtin type. pub(crate) fn builtin_type( kind: TypeKind, is_const: bool, @@ -1331,6 +1334,7 @@ impl Item { id.as_type_id_unchecked() } + /// Parse this item from the given Clang cursor. pub(crate) fn parse( cursor: clang::Cursor, parent_id: Option, @@ -1349,6 +1353,7 @@ impl Item { let current_module = ctx.current_module().into(); let relevant_parent_id = parent_id.unwrap_or(current_module); + #[allow(clippy::missing_docs_in_private_items)] macro_rules! try_parse { ($what:ident) => { match $what::parse(cursor, ctx) { @@ -1477,6 +1482,8 @@ impl Item { } } + /// Parse this item from the given Clang type, or if we haven't resolved all + /// the other items this one depends on, an unresolved reference. pub(crate) fn from_ty_or_ref( ty: clang::Type, location: clang::Cursor, @@ -1552,6 +1559,7 @@ impl Item { potential_id.as_type_id_unchecked() } + /// Parse this item from the given Clang type. See [`Item::from_ty_with_id`]. pub(crate) fn from_ty( ty: &clang::Type, location: clang::Cursor, @@ -1978,7 +1986,7 @@ enum UserMangled { /// Builder struct for naming variations, which hold inside different /// flags for naming options. #[derive(Debug)] -pub struct NameOptions<'a> { +pub(crate) struct NameOptions<'a> { item: &'a Item, ctx: &'a BindgenContext, within_namespaces: bool, @@ -1987,7 +1995,7 @@ pub struct NameOptions<'a> { impl<'a> NameOptions<'a> { /// Construct a new `NameOptions` - pub fn new(item: &'a Item, ctx: &'a BindgenContext) -> Self { + pub(crate) fn new(item: &'a Item, ctx: &'a BindgenContext) -> Self { NameOptions { item, ctx, @@ -1998,7 +2006,7 @@ impl<'a> NameOptions<'a> { /// Construct the name without the item's containing C++ namespaces mangled /// into it. In other words, the item's name within the item's namespace. - pub fn within_namespaces(&mut self) -> &mut Self { + pub(crate) fn within_namespaces(&mut self) -> &mut Self { self.within_namespaces = true; self } @@ -2009,7 +2017,7 @@ impl<'a> NameOptions<'a> { } /// Construct a name `String` - pub fn get(&self) -> String { + pub(crate) fn get(&self) -> String { self.item.real_canonical_name(self.ctx, self) } } diff --git a/bindgen/ir/item_kind.rs b/bindgen/ir/item_kind.rs index 4a12fef40d..e8618498ad 100644 --- a/bindgen/ir/item_kind.rs +++ b/bindgen/ir/item_kind.rs @@ -10,7 +10,7 @@ use std::io; /// A item we parse and translate. #[derive(Debug)] -pub enum ItemKind { +pub(crate) enum ItemKind { /// A module, created implicitly once (the root module), or via C++ /// namespaces. Module(Module), @@ -28,7 +28,7 @@ pub enum ItemKind { impl ItemKind { /// Get a reference to this `ItemKind`'s underying `Module`, or `None` if it /// is some other kind. - pub fn as_module(&self) -> Option<&Module> { + pub(crate) fn as_module(&self) -> Option<&Module> { match *self { ItemKind::Module(ref module) => Some(module), _ => None, @@ -36,7 +36,7 @@ impl ItemKind { } /// Transform our `ItemKind` into a string. - pub fn kind_name(&self) -> &'static str { + pub(crate) fn kind_name(&self) -> &'static str { match *self { ItemKind::Module(..) => "Module", ItemKind::Type(..) => "Type", @@ -46,19 +46,13 @@ impl ItemKind { } /// Is this a module? - pub fn is_module(&self) -> bool { + pub(crate) fn is_module(&self) -> bool { self.as_module().is_some() } - /// Get a reference to this `ItemKind`'s underying `Module`, or panic if it - /// is some other kind. - pub fn expect_module(&self) -> &Module { - self.as_module().expect("Not a module") - } - /// Get a reference to this `ItemKind`'s underying `Function`, or `None` if /// it is some other kind. - pub fn as_function(&self) -> Option<&Function> { + pub(crate) fn as_function(&self) -> Option<&Function> { match *self { ItemKind::Function(ref func) => Some(func), _ => None, @@ -66,19 +60,19 @@ impl ItemKind { } /// Is this a function? - pub fn is_function(&self) -> bool { + pub(crate) fn is_function(&self) -> bool { self.as_function().is_some() } /// Get a reference to this `ItemKind`'s underying `Function`, or panic if /// it is some other kind. - pub fn expect_function(&self) -> &Function { + pub(crate) fn expect_function(&self) -> &Function { self.as_function().expect("Not a function") } /// Get a reference to this `ItemKind`'s underying `Type`, or `None` if /// it is some other kind. - pub fn as_type(&self) -> Option<&Type> { + pub(crate) fn as_type(&self) -> Option<&Type> { match *self { ItemKind::Type(ref ty) => Some(ty), _ => None, @@ -87,7 +81,7 @@ impl ItemKind { /// Get a mutable reference to this `ItemKind`'s underying `Type`, or `None` /// if it is some other kind. - pub fn as_type_mut(&mut self) -> Option<&mut Type> { + pub(crate) fn as_type_mut(&mut self) -> Option<&mut Type> { match *self { ItemKind::Type(ref mut ty) => Some(ty), _ => None, @@ -95,19 +89,19 @@ impl ItemKind { } /// Is this a type? - pub fn is_type(&self) -> bool { + pub(crate) fn is_type(&self) -> bool { self.as_type().is_some() } /// Get a reference to this `ItemKind`'s underying `Type`, or panic if it is /// some other kind. - pub fn expect_type(&self) -> &Type { + pub(crate) fn expect_type(&self) -> &Type { self.as_type().expect("Not a type") } /// Get a reference to this `ItemKind`'s underying `Var`, or `None` if it is /// some other kind. - pub fn as_var(&self) -> Option<&Var> { + pub(crate) fn as_var(&self) -> Option<&Var> { match *self { ItemKind::Var(ref v) => Some(v), _ => None, @@ -115,15 +109,9 @@ impl ItemKind { } /// Is this a variable? - pub fn is_var(&self) -> bool { + pub(crate) fn is_var(&self) -> bool { self.as_var().is_some() } - - /// Get a reference to this `ItemKind`'s underying `Var`, or panic if it is - /// some other kind. - pub fn expect_var(&self) -> &Var { - self.as_var().expect("Not a var") - } } impl DotAttributes for ItemKind { diff --git a/bindgen/ir/layout.rs b/bindgen/ir/layout.rs index 6f4503070a..ba944b06bc 100644 --- a/bindgen/ir/layout.rs +++ b/bindgen/ir/layout.rs @@ -8,13 +8,13 @@ use std::cmp; /// A type that represents the struct layout of a type. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Layout { +pub(crate) struct Layout { /// The size (in bytes) of this layout. - pub size: usize, + pub(crate) size: usize, /// The alignment (in bytes) of this layout. - pub align: usize, + pub(crate) align: usize, /// Whether this layout's members are packed or not. - pub packed: bool, + pub(crate) packed: bool, } #[test] @@ -34,7 +34,7 @@ fn test_layout_for_size() { impl Layout { /// Gets the integer type name for a given known size. - pub fn known_type_for_size( + pub(crate) fn known_type_for_size( ctx: &BindgenContext, size: usize, ) -> Option<&'static str> { @@ -50,7 +50,7 @@ impl Layout { /// Construct a new `Layout` with the given `size` and `align`. It is not /// packed. - pub fn new(size: usize, align: usize) -> Self { + pub(crate) fn new(size: usize, align: usize) -> Self { Layout { size, align, @@ -72,33 +72,26 @@ impl Layout { /// Creates a non-packed layout for a given size, trying to use the maximum /// alignment possible. - pub fn for_size(ctx: &BindgenContext, size: usize) -> Self { + pub(crate) fn for_size(ctx: &BindgenContext, size: usize) -> Self { Self::for_size_internal(ctx.target_pointer_size(), size) } - /// Is this a zero-sized layout? - pub fn is_zero(&self) -> bool { - self.size == 0 && self.align == 0 - } - - /// Construct a zero-sized layout. - pub fn zero() -> Self { - Self::new(0, 0) - } - /// Get this layout as an opaque type. - pub fn opaque(&self) -> Opaque { + pub(crate) fn opaque(&self) -> Opaque { Opaque(*self) } } /// When we are treating a type as opaque, it is just a blob with a `Layout`. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct Opaque(pub Layout); +pub(crate) struct Opaque(pub(crate) Layout); impl Opaque { /// Construct a new opaque type from the given clang type. - pub fn from_clang_ty(ty: &clang::Type, ctx: &BindgenContext) -> Type { + pub(crate) fn from_clang_ty( + ty: &clang::Type, + ctx: &BindgenContext, + ) -> Type { let layout = Layout::new(ty.size(ctx), ty.align(ctx)); let ty_kind = TypeKind::Opaque; let is_const = ty.is_const(); @@ -107,7 +100,7 @@ impl Opaque { /// Return the known rust type we should use to create a correctly-aligned /// field with this layout. - pub fn known_rust_type_for_array( + pub(crate) fn known_rust_type_for_array( &self, ctx: &BindgenContext, ) -> Option<&'static str> { @@ -116,7 +109,7 @@ impl Opaque { /// Return the array size that an opaque type for this layout should have if /// we know the correct type for it, or `None` otherwise. - pub fn array_size(&self, ctx: &BindgenContext) -> Option { + pub(crate) fn array_size(&self, ctx: &BindgenContext) -> Option { if self.known_rust_type_for_array(ctx).is_some() { Some(self.0.size / cmp::max(self.0.align, 1)) } else { @@ -127,7 +120,7 @@ impl Opaque { /// Return `true` if this opaque layout's array size will fit within the /// maximum number of array elements that Rust allows deriving traits /// with. Return `false` otherwise. - pub fn array_size_within_derive_limit( + pub(crate) fn array_size_within_derive_limit( &self, ctx: &BindgenContext, ) -> CanDerive { diff --git a/bindgen/ir/mod.rs b/bindgen/ir/mod.rs index 8f6a2dac88..acdb4896cd 100644 --- a/bindgen/ir/mod.rs +++ b/bindgen/ir/mod.rs @@ -2,23 +2,24 @@ //! //! Parsing C/C++ generates the IR, while code generation outputs Rust code from //! the IR. +#![deny(clippy::missing_docs_in_private_items)] -pub mod analysis; -pub mod annotations; -pub mod comment; -pub mod comp; -pub mod context; -pub mod derive; -pub mod dot; -pub mod enum_ty; -pub mod function; -pub mod int; -pub mod item; -pub mod item_kind; -pub mod layout; -pub mod module; -pub mod objc; -pub mod template; -pub mod traversal; -pub mod ty; -pub mod var; +pub(crate) mod analysis; +pub(crate) mod annotations; +pub(crate) mod comment; +pub(crate) mod comp; +pub(crate) mod context; +pub(crate) mod derive; +pub(crate) mod dot; +pub(crate) mod enum_ty; +pub(crate) mod function; +pub(crate) mod int; +pub(crate) mod item; +pub(crate) mod item_kind; +pub(crate) mod layout; +pub(crate) mod module; +pub(crate) mod objc; +pub(crate) mod template; +pub(crate) mod traversal; +pub(crate) mod ty; +pub(crate) mod var; diff --git a/bindgen/ir/module.rs b/bindgen/ir/module.rs index d5aca94a6e..f25ef40f77 100644 --- a/bindgen/ir/module.rs +++ b/bindgen/ir/module.rs @@ -10,7 +10,7 @@ use std::io; /// Whether this module is inline or not. #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum ModuleKind { +pub(crate) enum ModuleKind { /// This module is not inline. Normal, /// This module is inline, as in `inline namespace foo {}`. @@ -19,7 +19,7 @@ pub enum ModuleKind { /// A module, as in, a C++ namespace. #[derive(Clone, Debug)] -pub struct Module { +pub(crate) struct Module { /// The name of the module, or none if it's anonymous. name: Option, /// The kind of module this is. @@ -30,7 +30,7 @@ pub struct Module { impl Module { /// Construct a new `Module`. - pub fn new(name: Option, kind: ModuleKind) -> Self { + pub(crate) fn new(name: Option, kind: ModuleKind) -> Self { Module { name, kind, @@ -39,22 +39,22 @@ impl Module { } /// Get this module's name. - pub fn name(&self) -> Option<&str> { + pub(crate) fn name(&self) -> Option<&str> { self.name.as_deref() } /// Get a mutable reference to this module's children. - pub fn children_mut(&mut self) -> &mut ItemSet { + pub(crate) fn children_mut(&mut self) -> &mut ItemSet { &mut self.children } /// Get this module's children. - pub fn children(&self) -> &ItemSet { + pub(crate) fn children(&self) -> &ItemSet { &self.children } /// Whether this namespace is inline. - pub fn is_inline(&self) -> bool { + pub(crate) fn is_inline(&self) -> bool { self.kind == ModuleKind::Inline } } diff --git a/bindgen/ir/objc.rs b/bindgen/ir/objc.rs index 4f340f6f7a..eaf3b8a545 100644 --- a/bindgen/ir/objc.rs +++ b/bindgen/ir/objc.rs @@ -21,7 +21,7 @@ use proc_macro2::{Ident, Span, TokenStream}; /// /// Also protocols and categories are parsed as this type #[derive(Debug)] -pub struct ObjCInterface { +pub(crate) struct ObjCInterface { /// The name /// like, NSObject name: String, @@ -31,13 +31,13 @@ pub struct ObjCInterface { is_protocol: bool, /// The list of template names almost always, ObjectType or KeyType - pub template_names: Vec, + pub(crate) template_names: Vec, /// The list of protocols that this interface conforms to. - pub conforms_to: Vec, + pub(crate) conforms_to: Vec, /// The direct parent for this interface. - pub parent_class: Option, + pub(crate) parent_class: Option, /// List of the methods defined in this interfae methods: Vec, @@ -47,7 +47,7 @@ pub struct ObjCInterface { /// The objective c methods #[derive(Debug)] -pub struct ObjCMethod { +pub(crate) struct ObjCMethod { /// The original method selector name /// like, dataWithBytes:length: name: String, @@ -78,14 +78,14 @@ impl ObjCInterface { /// The name /// like, NSObject - pub fn name(&self) -> &str { + pub(crate) fn name(&self) -> &str { self.name.as_ref() } /// Formats the name for rust /// Can be like NSObject, but with categories might be like NSObject_NSCoderMethods /// and protocols are like PNSObject - pub fn rust_name(&self) -> String { + pub(crate) fn rust_name(&self) -> String { if let Some(ref cat) = self.category { format!("{}_{}", self.name(), cat) } else if self.is_protocol { @@ -96,32 +96,32 @@ impl ObjCInterface { } /// Is this a template interface? - pub fn is_template(&self) -> bool { + pub(crate) fn is_template(&self) -> bool { !self.template_names.is_empty() } /// List of the methods defined in this interface - pub fn methods(&self) -> &Vec { + pub(crate) fn methods(&self) -> &Vec { &self.methods } /// Is this a protocol? - pub fn is_protocol(&self) -> bool { + pub(crate) fn is_protocol(&self) -> bool { self.is_protocol } /// Is this a category? - pub fn is_category(&self) -> bool { + pub(crate) fn is_category(&self) -> bool { self.category.is_some() } /// List of the class methods defined in this interface - pub fn class_methods(&self) -> &Vec { + pub(crate) fn class_methods(&self) -> &Vec { &self.class_methods } /// Parses the Objective C interface from the cursor - pub fn from_ty( + pub(crate) fn from_ty( cursor: &clang::Cursor, ctx: &mut BindgenContext, ) -> Option { @@ -229,30 +229,27 @@ impl ObjCMethod { } } - /// The original method selector name - /// like, dataWithBytes:length: - pub fn name(&self) -> &str { - self.name.as_ref() - } - /// Method name as converted to rust /// like, dataWithBytes_length_ - pub fn rust_name(&self) -> &str { + pub(crate) fn rust_name(&self) -> &str { self.rust_name.as_ref() } /// Returns the methods signature as FunctionSig - pub fn signature(&self) -> &FunctionSig { + pub(crate) fn signature(&self) -> &FunctionSig { &self.signature } /// Is this a class method? - pub fn is_class_method(&self) -> bool { + pub(crate) fn is_class_method(&self) -> bool { self.is_class_method } /// Formats the method call - pub fn format_method_call(&self, args: &[TokenStream]) -> TokenStream { + pub(crate) fn format_method_call( + &self, + args: &[TokenStream], + ) -> TokenStream { let split_name: Vec> = self .name .split(':') diff --git a/bindgen/ir/template.rs b/bindgen/ir/template.rs index e3ef6a9c96..0a2c269eed 100644 --- a/bindgen/ir/template.rs +++ b/bindgen/ir/template.rs @@ -98,7 +98,7 @@ use crate::clang; /// ... |Wtf | ... | [T] | /// ... |Qux | ... | [] | /// ----+------+-----+----------------------+ -pub trait TemplateParameters: Sized { +pub(crate) trait TemplateParameters: Sized { /// Get the set of `ItemId`s that make up this template declaration's free /// template parameters. /// @@ -163,7 +163,7 @@ pub trait TemplateParameters: Sized { } /// A trait for things which may or may not be a named template type parameter. -pub trait AsTemplateParam { +pub(crate) trait AsTemplateParam { /// Any extra information the implementor might need to make this decision. type Extra; @@ -186,7 +186,7 @@ pub trait AsTemplateParam { /// A concrete instantiation of a generic template. #[derive(Clone, Debug)] -pub struct TemplateInstantiation { +pub(crate) struct TemplateInstantiation { /// The template definition which this is instantiating. definition: TypeId, /// The concrete template arguments, which will be substituted in the @@ -196,7 +196,7 @@ pub struct TemplateInstantiation { impl TemplateInstantiation { /// Construct a new template instantiation from the given parts. - pub fn new(definition: TypeId, args: I) -> TemplateInstantiation + pub(crate) fn new(definition: TypeId, args: I) -> TemplateInstantiation where I: IntoIterator, { @@ -207,17 +207,17 @@ impl TemplateInstantiation { } /// Get the template definition for this instantiation. - pub fn template_definition(&self) -> TypeId { + pub(crate) fn template_definition(&self) -> TypeId { self.definition } /// Get the concrete template arguments used in this instantiation. - pub fn template_arguments(&self) -> &[TypeId] { + pub(crate) fn template_arguments(&self) -> &[TypeId] { &self.args[..] } /// Parse a `TemplateInstantiation` from a clang `Type`. - pub fn from_ty( + pub(crate) fn from_ty( ty: &clang::Type, ctx: &mut BindgenContext, ) -> Option { diff --git a/bindgen/ir/traversal.rs b/bindgen/ir/traversal.rs index f14483f295..17e24f701e 100644 --- a/bindgen/ir/traversal.rs +++ b/bindgen/ir/traversal.rs @@ -12,14 +12,14 @@ use std::collections::{BTreeMap, VecDeque}; /// The `from` is left implicit: it is the concrete `Trace` implementer which /// yielded this outgoing edge. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct Edge { +pub(crate) struct Edge { to: ItemId, kind: EdgeKind, } impl Edge { /// Construct a new edge whose referent is `to` and is of the given `kind`. - pub fn new(to: ItemId, kind: EdgeKind) -> Edge { + pub(crate) fn new(to: ItemId, kind: EdgeKind) -> Edge { Edge { to, kind } } } @@ -33,7 +33,7 @@ impl From for ItemId { /// The kind of edge reference. This is useful when we wish to only consider /// certain kinds of edges for a particular traversal or analysis. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum EdgeKind { +pub(crate) enum EdgeKind { /// A generic, catch-all edge. Generic, @@ -182,12 +182,13 @@ pub enum EdgeKind { /// /// The predicate must return true if the traversal should follow this edge /// and visit everything that is reachable through it. -pub type TraversalPredicate = for<'a> fn(&'a BindgenContext, Edge) -> bool; +pub(crate) type TraversalPredicate = + for<'a> fn(&'a BindgenContext, Edge) -> bool; /// A `TraversalPredicate` implementation that follows all edges, and therefore /// traversals using this predicate will see the whole IR graph reachable from /// the traversal's roots. -pub fn all_edges(_: &BindgenContext, _: Edge) -> bool { +pub(crate) fn all_edges(_: &BindgenContext, _: Edge) -> bool { true } @@ -196,14 +197,14 @@ pub fn all_edges(_: &BindgenContext, _: Edge) -> bool { /// will only visit the traversal's roots and their inner types. This is used /// in no-recursive-allowlist mode, where inner types such as anonymous /// structs/unions still need to be processed. -pub fn only_inner_type_edges(_: &BindgenContext, edge: Edge) -> bool { +pub(crate) fn only_inner_type_edges(_: &BindgenContext, edge: Edge) -> bool { edge.kind == EdgeKind::InnerType } /// A `TraversalPredicate` implementation that only follows edges to items that /// are enabled for code generation. This lets us skip considering items for /// which are not reachable from code generation. -pub fn codegen_edges(ctx: &BindgenContext, edge: Edge) -> bool { +pub(crate) fn codegen_edges(ctx: &BindgenContext, edge: Edge) -> bool { let cc = &ctx.options().codegen_config; match edge.kind { EdgeKind::Generic => { @@ -233,7 +234,7 @@ pub fn codegen_edges(ctx: &BindgenContext, edge: Edge) -> bool { /// The storage for the set of items that have been seen (although their /// outgoing edges might not have been fully traversed yet) in an active /// traversal. -pub trait TraversalStorage<'ctx> { +pub(crate) trait TraversalStorage<'ctx> { /// Construct a new instance of this TraversalStorage, for a new traversal. fn new(ctx: &'ctx BindgenContext) -> Self; @@ -259,7 +260,7 @@ impl<'ctx> TraversalStorage<'ctx> for ItemSet { /// each item. This is useful for providing debug assertions with meaningful /// diagnostic messages about dangling items. #[derive(Debug)] -pub struct Paths<'ctx>(BTreeMap, &'ctx BindgenContext); +pub(crate) struct Paths<'ctx>(BTreeMap, &'ctx BindgenContext); impl<'ctx> TraversalStorage<'ctx> for Paths<'ctx> { fn new(ctx: &'ctx BindgenContext) -> Self { @@ -300,7 +301,7 @@ impl<'ctx> TraversalStorage<'ctx> for Paths<'ctx> { /// Using a FIFO queue with a traversal will yield a breadth-first traversal, /// while using a LIFO queue will result in a depth-first traversal of the IR /// graph. -pub trait TraversalQueue: Default { +pub(crate) trait TraversalQueue: Default { /// Add a newly discovered item to the queue. fn push(&mut self, item: ItemId); @@ -329,7 +330,7 @@ impl TraversalQueue for VecDeque { } /// Something that can receive edges from a `Trace` implementation. -pub trait Tracer { +pub(crate) trait Tracer { /// Note an edge between items. Called from within a `Trace` implementation. fn visit_kind(&mut self, item: ItemId, kind: EdgeKind); @@ -351,7 +352,7 @@ where /// Trace all of the outgoing edges to other items. Implementations should call /// one of `tracer.visit(edge)` or `tracer.visit_kind(edge, EdgeKind::Whatever)` /// for each of their outgoing edges. -pub trait Trace { +pub(crate) trait Trace { /// If a particular type needs extra information beyond what it has in /// `self` and `context` to find its referenced items, its implementation /// can define this associated type, forcing callers to pass the needed @@ -371,7 +372,7 @@ pub trait Trace { /// An graph traversal of the transitive closure of references between items. /// /// See `BindgenContext::allowlisted_items` for more information. -pub struct ItemTraversal<'ctx, Storage, Queue> +pub(crate) struct ItemTraversal<'ctx, Storage, Queue> where Storage: TraversalStorage<'ctx>, Queue: TraversalQueue, @@ -397,7 +398,7 @@ where Queue: TraversalQueue, { /// Begin a new traversal, starting from the given roots. - pub fn new( + pub(crate) fn new( ctx: &'ctx BindgenContext, roots: R, predicate: TraversalPredicate, @@ -474,5 +475,5 @@ where /// /// See `BindgenContext::assert_no_dangling_item_traversal` for more /// information. -pub type AssertNoDanglingItemsTraversal<'ctx> = +pub(crate) type AssertNoDanglingItemsTraversal<'ctx> = ItemTraversal<'ctx, Paths<'ctx>, VecDeque>; diff --git a/bindgen/ir/ty.rs b/bindgen/ir/ty.rs index fef340dee9..ca66e1106b 100644 --- a/bindgen/ir/ty.rs +++ b/bindgen/ir/ty.rs @@ -24,7 +24,7 @@ use std::io; /// (size, alignment and packedness) if known, a `Kind`, which determines which /// kind of type it is, and whether the type is const. #[derive(Debug)] -pub struct Type { +pub(crate) struct Type { /// The name of the type, or None if it was an unnamed struct or union. name: Option, /// The layout of the type, if known. @@ -39,21 +39,12 @@ pub struct Type { /// traits, and so if we have a type containing an array with more than this /// many items, we won't be able to derive common traits on that type. /// -pub const RUST_DERIVE_IN_ARRAY_LIMIT: usize = 32; +pub(crate) const RUST_DERIVE_IN_ARRAY_LIMIT: usize = 32; impl Type { - /// Get the underlying `CompInfo` for this type, or `None` if this is some - /// other kind of type. - pub fn as_comp(&self) -> Option<&CompInfo> { - match self.kind { - TypeKind::Comp(ref ci) => Some(ci), - _ => None, - } - } - /// Get the underlying `CompInfo` for this type as a mutable reference, or /// `None` if this is some other kind of type. - pub fn as_comp_mut(&mut self) -> Option<&mut CompInfo> { + pub(crate) fn as_comp_mut(&mut self) -> Option<&mut CompInfo> { match self.kind { TypeKind::Comp(ref mut ci) => Some(ci), _ => None, @@ -61,7 +52,7 @@ impl Type { } /// Construct a new `Type`. - pub fn new( + pub(crate) fn new( name: Option, layout: Option, kind: TypeKind, @@ -76,37 +67,37 @@ impl Type { } /// Which kind of type is this? - pub fn kind(&self) -> &TypeKind { + pub(crate) fn kind(&self) -> &TypeKind { &self.kind } /// Get a mutable reference to this type's kind. - pub fn kind_mut(&mut self) -> &mut TypeKind { + pub(crate) fn kind_mut(&mut self) -> &mut TypeKind { &mut self.kind } /// Get this type's name. - pub fn name(&self) -> Option<&str> { + pub(crate) fn name(&self) -> Option<&str> { self.name.as_deref() } /// Whether this is a block pointer type. - pub fn is_block_pointer(&self) -> bool { + pub(crate) fn is_block_pointer(&self) -> bool { matches!(self.kind, TypeKind::BlockPointer(..)) } /// Is this an integer type, including `bool` or `char`? - pub fn is_int(&self) -> bool { + pub(crate) fn is_int(&self) -> bool { matches!(self.kind, TypeKind::Int(_)) } /// Is this a compound type? - pub fn is_comp(&self) -> bool { + pub(crate) fn is_comp(&self) -> bool { matches!(self.kind, TypeKind::Comp(..)) } /// Is this a union? - pub fn is_union(&self) -> bool { + pub(crate) fn is_union(&self) -> bool { match self.kind { TypeKind::Comp(ref comp) => comp.is_union(), _ => false, @@ -114,32 +105,27 @@ impl Type { } /// Is this type of kind `TypeKind::TypeParam`? - pub fn is_type_param(&self) -> bool { + pub(crate) fn is_type_param(&self) -> bool { matches!(self.kind, TypeKind::TypeParam) } /// Is this a template instantiation type? - pub fn is_template_instantiation(&self) -> bool { + pub(crate) fn is_template_instantiation(&self) -> bool { matches!(self.kind, TypeKind::TemplateInstantiation(..)) } - /// Is this a template alias type? - pub fn is_template_alias(&self) -> bool { - matches!(self.kind, TypeKind::TemplateAlias(..)) - } - /// Is this a function type? - pub fn is_function(&self) -> bool { + pub(crate) fn is_function(&self) -> bool { matches!(self.kind, TypeKind::Function(..)) } /// Is this an enum type? - pub fn is_enum(&self) -> bool { + pub(crate) fn is_enum(&self) -> bool { matches!(self.kind, TypeKind::Enum(..)) } /// Is this either a builtin or named type? - pub fn is_builtin_or_type_param(&self) -> bool { + pub(crate) fn is_builtin_or_type_param(&self) -> bool { matches!( self.kind, TypeKind::Void | @@ -155,29 +141,29 @@ impl Type { } /// Creates a new named type, with name `name`. - pub fn named(name: String) -> Self { + pub(crate) fn named(name: String) -> Self { let name = if name.is_empty() { None } else { Some(name) }; Self::new(name, None, TypeKind::TypeParam, false) } /// Is this a floating point type? - pub fn is_float(&self) -> bool { + pub(crate) fn is_float(&self) -> bool { matches!(self.kind, TypeKind::Float(..)) } /// Is this a boolean type? - pub fn is_bool(&self) -> bool { + pub(crate) fn is_bool(&self) -> bool { matches!(self.kind, TypeKind::Int(IntKind::Bool)) } /// Is this an integer type? - pub fn is_integer(&self) -> bool { + pub(crate) fn is_integer(&self) -> bool { matches!(self.kind, TypeKind::Int(..)) } /// Cast this type to an integer kind, or `None` if it is not an integer /// type. - pub fn as_integer(&self) -> Option { + pub(crate) fn as_integer(&self) -> Option { match self.kind { TypeKind::Int(int_kind) => Some(int_kind), _ => None, @@ -185,25 +171,20 @@ impl Type { } /// Is this a `const` qualified type? - pub fn is_const(&self) -> bool { + pub(crate) fn is_const(&self) -> bool { self.is_const } - /// Is this a reference to another type? - pub fn is_type_ref(&self) -> bool { - matches!( - self.kind, - TypeKind::ResolvedTypeRef(_) | TypeKind::UnresolvedTypeRef(_, _, _) - ) - } - /// Is this an unresolved reference? - pub fn is_unresolved_ref(&self) -> bool { + pub(crate) fn is_unresolved_ref(&self) -> bool { matches!(self.kind, TypeKind::UnresolvedTypeRef(_, _, _)) } /// Is this a incomplete array type? - pub fn is_incomplete_array(&self, ctx: &BindgenContext) -> Option { + pub(crate) fn is_incomplete_array( + &self, + ctx: &BindgenContext, + ) -> Option { match self.kind { TypeKind::Array(item, len) => { if len == 0 { @@ -220,7 +201,7 @@ impl Type { } /// What is the layout of this type? - pub fn layout(&self, ctx: &BindgenContext) -> Option { + pub(crate) fn layout(&self, ctx: &BindgenContext) -> Option { self.layout.or_else(|| { match self.kind { TypeKind::Comp(ref ci) => ci.layout(ctx), @@ -245,7 +226,7 @@ impl Type { /// avoid generating invalid code with some cases we can't handle, see: /// /// tests/headers/381-decltype-alias.hpp - pub fn is_invalid_type_param(&self) -> bool { + pub(crate) fn is_invalid_type_param(&self) -> bool { match self.kind { TypeKind::TypeParam => { let name = self.name().expect("Unnamed named type?"); @@ -266,7 +247,7 @@ impl Type { } /// Get this type's santizied name. - pub fn sanitized_name<'a>( + pub(crate) fn sanitized_name<'a>( &'a self, ctx: &BindgenContext, ) -> Option> { @@ -289,7 +270,7 @@ impl Type { } /// See safe_canonical_type. - pub fn canonical_type<'tr>( + pub(crate) fn canonical_type<'tr>( &'tr self, ctx: &'tr BindgenContext, ) -> &'tr Type { @@ -302,7 +283,7 @@ impl Type { /// For example, for a `typedef`, the canonical type would be the /// `typedef`ed type, for a template instantiation, would be the template /// its specializing, and so on. Return None if the type is unresolved. - pub fn safe_canonical_type<'tr>( + pub(crate) fn safe_canonical_type<'tr>( &'tr self, ctx: &'tr BindgenContext, ) -> Option<&'tr Type> { @@ -341,7 +322,7 @@ impl Type { /// There are some types we don't want to stop at when finding an opaque /// item, so we can arrive to the proper item that needs to be generated. - pub fn should_be_traced_unconditionally(&self) -> bool { + pub(crate) fn should_be_traced_unconditionally(&self) -> bool { matches!( self.kind, TypeKind::Comp(..) | @@ -570,7 +551,7 @@ impl TemplateParameters for TypeKind { /// The kind of float this type represents. #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum FloatKind { +pub(crate) enum FloatKind { /// A `float`. Float, /// A `double`. @@ -583,7 +564,7 @@ pub enum FloatKind { /// The different kinds of types that we can parse. #[derive(Debug)] -pub enum TypeKind { +pub(crate) enum TypeKind { /// The void type. Void, @@ -680,7 +661,7 @@ impl Type { /// /// It's sort of nasty and full of special-casing, but hopefully the /// comments in every special case justify why they're there. - pub fn from_clang_ty( + pub(crate) fn from_clang_ty( potential_id: ItemId, ty: &clang::Type, location: Cursor, diff --git a/bindgen/ir/var.rs b/bindgen/ir/var.rs index 903e1ff549..b80737627a 100644 --- a/bindgen/ir/var.rs +++ b/bindgen/ir/var.rs @@ -17,7 +17,7 @@ use std::num::Wrapping; /// The type for a constant variable. #[derive(Debug)] -pub enum VarType { +pub(crate) enum VarType { /// A boolean. Bool(bool), /// An integer. @@ -32,7 +32,7 @@ pub enum VarType { /// A `Var` is our intermediate representation of a variable. #[derive(Debug)] -pub struct Var { +pub(crate) struct Var { /// The name of the variable. name: String, /// The mangled name of the variable. @@ -47,7 +47,7 @@ pub struct Var { impl Var { /// Construct a new `Var`. - pub fn new( + pub(crate) fn new( name: String, mangled_name: Option, ty: TypeId, @@ -65,27 +65,27 @@ impl Var { } /// Is this variable `const` qualified? - pub fn is_const(&self) -> bool { + pub(crate) fn is_const(&self) -> bool { self.is_const } /// The value of this constant variable, if any. - pub fn val(&self) -> Option<&VarType> { + pub(crate) fn val(&self) -> Option<&VarType> { self.val.as_ref() } /// Get this variable's type. - pub fn ty(&self) -> TypeId { + pub(crate) fn ty(&self) -> TypeId { self.ty } /// Get this variable's name. - pub fn name(&self) -> &str { + pub(crate) fn name(&self) -> &str { &self.name } /// Get this variable's mangled name. - pub fn mangled_name(&self) -> Option<&str> { + pub(crate) fn mangled_name(&self) -> Option<&str> { self.mangled_name.as_deref() } } diff --git a/bindgen/lib.rs b/bindgen/lib.rs index 14d7a15576..0a89462fce 100644 --- a/bindgen/lib.rs +++ b/bindgen/lib.rs @@ -34,22 +34,6 @@ mod log_stubs; #[macro_use] mod extra_assertions; -// A macro to declare an internal module for which we *must* provide -// documentation for. If we are building with the "testing_only_docs" feature, -// then the module is declared public, and our `#![deny(missing_docs)]` pragma -// applies to it. This feature is used in CI, so we won't let anything slip by -// undocumented. Normal builds, however, will leave the module private, so that -// we don't expose internals to library consumers. -macro_rules! doc_mod { - ($m:ident, $doc_mod_name:ident) => { - #[cfg(feature = "testing_only_docs")] - pub mod $doc_mod_name { - //! Autogenerated documentation module. - pub use super::$m::*; - } - }; -} - macro_rules! fn_with_regex_arg { ($(#[$attrs:meta])* pub fn $($tokens:tt)*) => { $(#[$attrs])* @@ -62,22 +46,17 @@ macro_rules! fn_with_regex_arg { }; } -mod clang; mod codegen; mod deps; -mod features; -pub mod ir; -mod parse; -mod regex_set; mod time; pub mod callbacks; -doc_mod!(clang, clang_docs); -doc_mod!(features, features_docs); -doc_mod!(ir, ir_docs); -doc_mod!(parse, parse_docs); -doc_mod!(regex_set, regex_set_docs); +mod clang; +mod features; +mod ir; +mod parse; +mod regex_set; use codegen::CodegenError; use ir::comment; diff --git a/bindgen/parse.rs b/bindgen/parse.rs index 1fd83cddda..d29b090fcb 100644 --- a/bindgen/parse.rs +++ b/bindgen/parse.rs @@ -1,4 +1,5 @@ //! Common traits and types related to parsing our IR from Clang cursors. +#![deny(clippy::missing_docs_in_private_items)] use crate::clang; use crate::ir::context::{BindgenContext, ItemId}; @@ -6,7 +7,7 @@ use crate::ir::context::{BindgenContext, ItemId}; /// Not so much an error in the traditional sense, but a control flow message /// when walking over Clang's AST with a cursor. #[derive(Debug)] -pub enum ParseError { +pub(crate) enum ParseError { /// Recurse down the current AST node's children. Recurse, /// Continue on to the next sibling AST node, or back up to the parent's @@ -16,7 +17,7 @@ pub enum ParseError { /// The result of parsing a Clang AST node. #[derive(Debug)] -pub enum ParseResult { +pub(crate) enum ParseResult { /// We've already resolved this item before, here is the extant `ItemId` for /// it. AlreadyResolved(ItemId), @@ -28,7 +29,7 @@ pub enum ParseResult { /// An intermediate representation "sub-item" (i.e. one of the types contained /// inside an `ItemKind` variant) that can be parsed from a Clang cursor. -pub trait ClangSubItemParser: Sized { +pub(crate) trait ClangSubItemParser: Sized { /// Attempt to parse this type from the given cursor. /// /// The fact that is a reference guarantees it's held by the context, and diff --git a/bindgen/regex_set.rs b/bindgen/regex_set.rs index 6246dd255b..31da247cbc 100644 --- a/bindgen/regex_set.rs +++ b/bindgen/regex_set.rs @@ -1,4 +1,5 @@ //! A type that represents the union of a set of regular expressions. +#![deny(clippy::missing_docs_in_private_items)] use regex::RegexSet as RxSet; use std::cell::Cell; diff --git a/ci/test.sh b/ci/test.sh index 788c28fe27..835d606ed1 100755 --- a/ci/test.sh +++ b/ci/test.sh @@ -110,9 +110,6 @@ get_cargo_args() { if [ "$BINDGEN_FEATURE_EXTRA_ASSERTS" == "1" ]; then features+=" testing_only_extra_assertions" fi - if [ "$BINDGEN_FEATURE_TESTING_ONLY_DOCS" == "1" ]; then - features+=" testing_only_docs" - fi if [ ! -z "$features" ]; then args+=" --features $(echo $features | tr ' ' ',')" fi diff --git a/clippy.toml b/clippy.toml index 1060a6b4e7..26a0605343 100644 --- a/clippy.toml +++ b/clippy.toml @@ -2,3 +2,4 @@ disallowed-methods = [ { path = "clang_sys::CXCursor_TranslationUnit", reason = "This value was changed in clang 15"}, { path = "clang_sys::CXCursor_LastStmt", reason = "This value was changed in clang 15"} ] +missing-docs-in-crate-items = true