/ compiler / ast / src / common / imported_modules.rs
imported_modules.rs
 1  // Copyright (C) 2019-2025 ADnet Contributors
 2  // This file is part of the ADL library.
 3  
 4  // The ADL library is free software: you can redistribute it and/or modify
 5  // it under the terms of the GNU General Public License as published by
 6  // the Free Software Foundation, either version 3 of the License, or
 7  // (at your option) any later version.
 8  
 9  // The ADL library is distributed in the hope that it will be useful,
10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  // GNU General Public License for more details.
13  
14  // You should have received a copy of the GNU General Public License
15  // along with the ADL library. If not, see <https://www.gnu.org/licenses/>.
16  
17  use crate::Program;
18  
19  use adl_span::{Symbol, with_session_globals};
20  
21  use indexmap::IndexMap;
22  use serde::{Deserialize, Deserializer, Serialize, Serializer};
23  
24  #[allow(clippy::ptr_arg)]
25  pub fn serialize<S: Serializer>(
26      imported_modules: &IndexMap<Vec<Symbol>, Program>,
27      serializer: S,
28  ) -> Result<S::Ok, S::Error> {
29      let joined: IndexMap<String, Program> = with_session_globals(|s| {
30          imported_modules
31              .into_iter()
32              .map(|(package, program)| {
33                  let package = package.iter().map(|x| x.as_str(s, |s| s.to_owned())).collect::<Vec<_>>();
34                  (package.join("."), program.clone())
35              })
36              .collect()
37      });
38  
39      joined.serialize(serializer)
40  }
41  
42  pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<IndexMap<Vec<Symbol>, Program>, D::Error> {
43      Ok(IndexMap::<String, Program>::deserialize(deserializer)?
44          .into_iter()
45          .map(|(package, program)| (package.split('.').map(Symbol::intern).collect(), program))
46          .collect())
47  }