1 // Copyright 2022 Google, Inc.
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 // http://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
15 use std::env;
16 use std::fs::File;
17 use std::io::Write;
18 use std::path::{Path, PathBuf};
19
main()20 fn main() {
21 install_generated_module(
22 "lmp_packets.rs",
23 "LMP_PACKETS_PREBUILT",
24 &PathBuf::from("lmp_packets.pdl").canonicalize().unwrap(),
25 );
26 install_generated_module(
27 "llcp_packets.rs",
28 "LLCP_PACKETS_PREBUILT",
29 &PathBuf::from("llcp_packets.pdl").canonicalize().unwrap(),
30 );
31 install_generated_module(
32 "hci_packets.rs",
33 "HCI_PACKETS_PREBUILT",
34 &PathBuf::from("../packets/hci_packets.pdl").canonicalize().unwrap(),
35 );
36 }
37
install_generated_module(module_name: &str, prebuilt_var: &str, pdl_name: &PathBuf)38 fn install_generated_module(module_name: &str, prebuilt_var: &str, pdl_name: &PathBuf) {
39 let module_prebuilt = match env::var(prebuilt_var) {
40 Ok(dir) => PathBuf::from(dir),
41 Err(_) => PathBuf::from(module_name),
42 };
43
44 if Path::new(module_prebuilt.as_os_str()).exists() {
45 let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
46 std::fs::copy(
47 module_prebuilt.as_os_str().to_str().unwrap(),
48 out_dir.join(module_name).as_os_str().to_str().unwrap(),
49 )
50 .unwrap();
51 } else {
52 generate_module(pdl_name);
53 }
54 }
55
generate_module(in_file: &Path)56 fn generate_module(in_file: &Path) {
57 let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
58 let mut out_file =
59 File::create(out_dir.join(in_file.file_name().unwrap()).with_extension("rs")).unwrap();
60
61 println!("cargo:rerun-if-changed={}", in_file.display());
62
63 let mut sources = pdl_compiler::ast::SourceDatabase::new();
64 let parsed_file = pdl_compiler::parser::parse_file(
65 &mut sources,
66 in_file.to_str().expect("Filename is not UTF-8"),
67 )
68 .expect("PDL parse failed");
69 let analyzed_file = pdl_compiler::analyzer::analyze(&parsed_file).expect("PDL analysis failed");
70 let rust_source = pdl_compiler::backends::rust_legacy::generate(&sources, &analyzed_file);
71 out_file.write_all(rust_source.as_bytes()).expect("Could not write to output file");
72 }
73