autocxx_parser/
lib.rs

1// Copyright 2020 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9#![forbid(unsafe_code)]
10
11mod config;
12mod directives;
13pub mod file_locations;
14mod multi_bindings;
15mod path;
16mod subclass_attrs;
17
18pub use config::{
19    AllowlistEntry, ExternCppType, IncludeCppConfig, RustFun, Subclass, UnsafePolicy,
20};
21use file_locations::FileLocationStrategy;
22pub use multi_bindings::{MultiBindings, MultiBindingsErr};
23pub use path::RustPath;
24use proc_macro2::TokenStream as TokenStream2;
25pub use subclass_attrs::SubclassAttrs;
26use syn::Result as ParseResult;
27use syn::{
28    parse::{Parse, ParseStream},
29    Macro,
30};
31
32#[doc(hidden)]
33/// Ensure consistency between the `include_cpp!` parser
34/// and the standalone macro discoverer
35pub mod directive_names {
36    pub static EXTERN_RUST_TYPE: &str = "extern_rust_type";
37    pub static EXTERN_RUST_FUN: &str = "extern_rust_function";
38    pub static SUBCLASS: &str = "subclass";
39}
40
41/// Core of the autocxx engine. See `generate` for most details
42/// on how this works.
43pub struct IncludeCpp {
44    config: IncludeCppConfig,
45}
46
47impl Parse for IncludeCpp {
48    fn parse(input: ParseStream) -> ParseResult<Self> {
49        let config = input.parse::<IncludeCppConfig>()?;
50        Ok(Self { config })
51    }
52}
53
54impl IncludeCpp {
55    pub fn new_from_syn(mac: Macro) -> ParseResult<Self> {
56        mac.parse_body::<IncludeCpp>()
57    }
58
59    /// Generate the Rust bindings.
60    pub fn generate_rs(&self) -> TokenStream2 {
61        if self.config.parse_only {
62            return TokenStream2::new();
63        }
64        FileLocationStrategy::new().make_include(&self.config)
65    }
66
67    pub fn get_config(&self) -> &IncludeCppConfig {
68        &self.config
69    }
70}
71
72#[cfg(test)]
73mod parse_tests {
74    use crate::IncludeCpp;
75    use syn::parse_quote;
76
77    #[test]
78    fn test_basic() {
79        let _i: IncludeCpp = parse_quote! {
80            generate_all!()
81        };
82    }
83}