autocxx_engine/conversion/
apivec.rs

1// Copyright 2022 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//    https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use indexmap::set::IndexSet as HashSet;
16
17use crate::{
18    conversion::{api::ApiName, convert_error::ErrorContext, ConvertErrorFromCpp},
19    types::QualifiedName,
20};
21
22use super::api::{AnalysisPhase, Api};
23
24/// Newtype wrapper for a list of APIs, which enforces the invariant
25/// that each API has a unique name.
26///
27/// Specifically, each API should have a unique [`QualifiedName`] which is kept
28/// within an [`ApiName`]. The [`QualifiedName`] is used to refer to this API
29/// from others, e.g. to represent edges in the graph used for garbage collection,
30/// so that's why this uniqueness is so important.
31///
32/// At present, this type also refuses to allow mutation of an API once it
33/// has been added to a set. This is because the autocxx engine is
34/// fundamentally organized into lots of analysis phases, each one _adding_
35/// fields rather than mutating earlier fields. The idea here is that it's
36/// impossible for stupid future maintainers (i.e. me) to make errors by
37/// referring to fields before they're filled in. If a field exists, it's
38/// correct.
39///
40/// While this is currently the case, it's possible that in future we could
41/// see legitimate reasons to break this latter invariant and allow mutation
42/// of APIs within an existing `ApiVec`. But it's extremely important that
43/// the naming-uniqueness-invariant remains, so any such mutation should
44/// allow mutation only of other fields, not the name.
45#[derive(Debug)]
46pub(crate) struct ApiVec<P: AnalysisPhase> {
47    apis: Vec<Api<P>>,
48    names: HashSet<QualifiedName>,
49}
50
51impl<P: AnalysisPhase> ApiVec<P> {
52    pub(crate) fn push(&mut self, api: Api<P>) {
53        let name = api.name();
54        let already_contains = self.already_contains(name);
55        if already_contains {
56            if api.discard_duplicates() {
57                // This is already an IgnoredItem or something else where
58                // we can silently drop it.
59                log::info!("Discarding duplicate API for {}", name);
60            } else {
61                log::info!(
62                    "Duplicate API for {} - removing all of them and replacing with an IgnoredItem.",
63                    name
64                );
65                self.retain(|api| api.name() != name);
66                self.push(Api::IgnoredItem {
67                    name: ApiName::new_from_qualified_name(name.clone()),
68                    err: ConvertErrorFromCpp::DuplicateItemsFoundInParsing,
69                    ctx: Some(ErrorContext::new_for_item(name.get_final_ident())),
70                })
71            }
72        } else {
73            self.names.insert(name.clone());
74            self.apis.push(api)
75        }
76    }
77
78    fn already_contains(&self, name: &QualifiedName) -> bool {
79        self.names.contains(name)
80    }
81
82    pub(crate) fn new() -> Self {
83        Self::default()
84    }
85
86    pub(crate) fn append(&mut self, more: &mut ApiVec<P>) {
87        self.extend(more.apis.drain(..))
88    }
89
90    pub(crate) fn extend(&mut self, it: impl Iterator<Item = Api<P>>) {
91        // Could be optimized in future
92        for api in it {
93            self.push(api)
94        }
95    }
96
97    pub(crate) fn iter(&self) -> impl Iterator<Item = &Api<P>> {
98        self.apis.iter()
99    }
100
101    pub(crate) fn into_iter(self) -> impl Iterator<Item = Api<P>> {
102        self.apis.into_iter()
103    }
104
105    pub(crate) fn is_empty(&self) -> bool {
106        self.apis.is_empty()
107    }
108
109    pub fn retain<F>(&mut self, f: F)
110    where
111        F: FnMut(&Api<P>) -> bool,
112    {
113        self.apis.retain(f);
114        self.names.clear();
115        self.names
116            .extend(self.apis.iter().map(|api| api.name()).cloned());
117    }
118}
119
120impl<P: AnalysisPhase> Default for ApiVec<P> {
121    fn default() -> Self {
122        Self {
123            apis: Default::default(),
124            names: Default::default(),
125        }
126    }
127}
128
129impl<P: AnalysisPhase> FromIterator<Api<P>> for ApiVec<P> {
130    fn from_iter<I: IntoIterator<Item = Api<P>>>(iter: I) -> Self {
131        let mut this = ApiVec::new();
132        for i in iter {
133            // Could be optimized in future
134            this.push(i);
135        }
136        this
137    }
138}