1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5use std::io::Write;
6
7use crate::bindgen::cdecl;
8use crate::bindgen::config::Config;
9use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver;
10use crate::bindgen::dependencies::Dependencies;
11use crate::bindgen::ir::{AnnotationSet, Cfg, Documentation, Item, ItemContainer, Path, Type};
12use crate::bindgen::library::Library;
13use crate::bindgen::writer::{Source, SourceWriter};
14
15#[derive(Debug, Clone)]
16pub struct Static {
17 pub path: Path,
18 pub export_name: String,
19 pub ty: Type,
20 pub mutable: bool,
21 pub cfg: Option<Cfg>,
22 pub annotations: AnnotationSet,
23 pub documentation: Documentation,
24}
25
26impl Static {
27 pub fn load(
28 path: Path,
29 item: &syn::ItemStatic,
30 mod_cfg: Option<&Cfg>,
31 ) -> Result<Static, String> {
32 let ty = Type::load(&item.ty)?;
33
34 if ty.is_none() {
35 return Err("Cannot have a zero sized static definition.".to_owned());
36 }
37
38 Ok(Static::new(
39 path,
40 ty.unwrap(),
41 item.mutability.is_some(),
42 Cfg::append(mod_cfg, Cfg::load(&item.attrs)),
43 AnnotationSet::load(&item.attrs)?,
44 Documentation::load(&item.attrs),
45 ))
46 }
47
48 pub fn new(
49 path: Path,
50 ty: Type,
51 mutable: bool,
52 cfg: Option<Cfg>,
53 annotations: AnnotationSet,
54 documentation: Documentation,
55 ) -> Self {
56 let export_name = path.name().to_owned();
57 Self {
58 path,
59 export_name,
60 ty,
61 mutable,
62 cfg,
63 annotations,
64 documentation,
65 }
66 }
67
68 pub fn simplify_standard_types(&mut self, config: &Config) {
69 self.ty.simplify_standard_types(config);
70 }
71}
72
73impl Item for Static {
74 fn path(&self) -> &Path {
75 &self.path
76 }
77
78 fn export_name(&self) -> &str {
79 &self.export_name
80 }
81
82 fn cfg(&self) -> Option<&Cfg> {
83 self.cfg.as_ref()
84 }
85
86 fn annotations(&self) -> &AnnotationSet {
87 &self.annotations
88 }
89
90 fn annotations_mut(&mut self) -> &mut AnnotationSet {
91 &mut self.annotations
92 }
93
94 fn container(&self) -> ItemContainer {
95 ItemContainer::Static(self.clone())
96 }
97
98 fn rename_for_config(&mut self, config: &Config) {
99 self.ty.rename_for_config(config, &Default::default());
100 }
101
102 fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) {
103 self.ty.resolve_declaration_types(resolver);
104 }
105
106 fn add_dependencies(&self, library: &Library, out: &mut Dependencies) {
107 self.ty.add_dependencies(library, out);
108 }
109}
110
111impl Source for Static {
112 fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
113 out.write(text:"extern ");
114 if let Type::Ptr { is_const: true, .. } = self.ty {
115 } else if !self.mutable {
116 out.write(text:"const ");
117 }
118 cdecl::write_field(out, &self.ty, &self.export_name, config);
119 out.write(text:";");
120 }
121}
122