1 /*
2  * Copyright 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <filesystem>
18 #include <fstream>
19 #include <iostream>
20 #include "declarations.h"
21 
generate_rust_packet_preamble(std::ostream & s)22 void generate_rust_packet_preamble(std::ostream& s) {
23   s <<
24       R"(
25 use bytes::{Bytes, BytesMut, BufMut};
26 use num_derive::{FromPrimitive, ToPrimitive};
27 use num_traits::{FromPrimitive, ToPrimitive};
28 use std::convert::TryInto;
29 use thiserror::Error;
30 use std::sync::Arc;
31 
32 type Result<T> = std::result::Result<T, Error>;
33 
34 #[derive(Debug, Error)]
35 pub enum Error {
36   #[error("Packet parsing failed")]
37   InvalidPacketError,
38   #[error("{field} was {value:x}, which is not known")]
39   ConstraintOutOfBounds {
40     field: String,
41     value: u64,
42   },
43   #[error("when parsing {obj}.{field} needed length of {wanted} but got {got}")]
44   InvalidLengthError {
45     obj: String,
46     field: String,
47     wanted: usize,
48     got: usize,
49   },
50   #[error("Due to size restrictions a struct could not be parsed.")]
51   ImpossibleStructError,
52 }
53 
54 pub trait Packet {
55   fn to_bytes(self) -> Bytes;
56   fn to_vec(self) -> Vec<u8>;
57 }
58 
59 )";
60 }
61 
generate_rust_source_one_file(const Declarations & decls,const std::filesystem::path & input_file,const std::filesystem::path & include_dir,const std::filesystem::path & out_dir,const std::string & root_namespace)62 bool generate_rust_source_one_file(
63     const Declarations& decls,
64     const std::filesystem::path& input_file,
65     const std::filesystem::path& include_dir,
66     const std::filesystem::path& out_dir,
67     __attribute__((unused)) const std::string& root_namespace) {
68   auto gen_relative_path = input_file.lexically_relative(include_dir).parent_path();
69 
70   auto input_filename = input_file.filename().string().substr(0, input_file.filename().string().find(".pdl"));
71   auto gen_path = out_dir / gen_relative_path;
72 
73   std::filesystem::create_directories(gen_path);
74 
75   auto gen_file = gen_path / (input_filename + ".rs");
76 
77   std::cout << "generating " << gen_file << std::endl;
78 
79   std::ofstream out_file;
80   out_file.open(gen_file);
81   if (!out_file.is_open()) {
82     std::cerr << "can't open " << gen_file << std::endl;
83     return false;
84   }
85 
86   out_file << "// @generated rust packets from " << input_file.filename().string() << "\n\n";
87 
88   generate_rust_packet_preamble(out_file);
89   if (input_filename == "hci_packets") {
90     out_file << "pub trait CommandExpectations { "
91              << "type ResponseType;"
92              << "fn _to_response_type(pkt: EventPacket) -> Self::ResponseType;"
93              << "}";
94 
95     for (const auto& packet_def : decls.packet_defs_queue_) {
96       auto packet = packet_def.second;
97       if (!packet->HasAncestorNamed("Command")) {
98         continue;
99       }
100       auto constraint = packet->parent_constraints_.find("op_code");
101       if (constraint == packet->parent_constraints_.end()) {
102         continue;
103       }
104       auto opcode = std::get<std::string>(constraint->second);
105       for (const auto& other_packet_def : decls.packet_defs_queue_) {
106         auto other_packet = other_packet_def.second;
107         bool command_status = other_packet->HasAncestorNamed("CommandStatus");
108         bool command_complete = other_packet->HasAncestorNamed("CommandComplete");
109         if (!command_status && !command_complete) {
110           continue;
111         }
112         auto other_constraint = other_packet->parent_constraints_.find("command_op_code");
113         if (other_constraint == other_packet->parent_constraints_.end()) {
114           continue;
115         }
116 
117         auto other_opcode = std::get<std::string>(other_constraint->second);
118         if (opcode == other_opcode) {
119           packet->complement_ = other_packet;
120           break;
121         }
122       }
123     }
124 
125     EnumDef* opcode = nullptr;
126     EnumDef* opcode_index = nullptr;
127     for (const auto& e : decls.type_defs_queue_) {
128       if (e.second->GetDefinitionType() == TypeDef::Type::ENUM) {
129         auto* enum_def = static_cast<EnumDef*>(e.second);
130         if (enum_def->name_ == "OpCode") {
131           opcode = enum_def;
132         } else if (enum_def->name_ == "OpCodeIndex") {
133           opcode_index = enum_def;
134         }
135       }
136     }
137 
138     if (opcode_index != nullptr && opcode != nullptr) {
139       opcode_index->try_from_enum_ = opcode;
140       out_file << "use std::convert::TryFrom;";
141     }
142   }
143 
144   for (const auto& e : decls.type_defs_queue_) {
145     if (e.second->GetDefinitionType() == TypeDef::Type::ENUM) {
146       const auto* enum_def = static_cast<const EnumDef*>(e.second);
147       EnumGen gen(*enum_def);
148       gen.GenRustDef(out_file);
149       out_file << "\n\n";
150     }
151   }
152 
153   for (auto& s : decls.type_defs_queue_) {
154     if (s.second->GetDefinitionType() == TypeDef::Type::STRUCT) {
155       const auto* struct_def = static_cast<const StructDef*>(s.second);
156       struct_def->GenRustDef(out_file);
157       out_file << "\n\n";
158     }
159   }
160 
161   for (const auto& packet_def : decls.packet_defs_queue_) {
162     packet_def.second->GenRustDef(out_file);
163     out_file << "\n\n";
164   }
165 
166   out_file.close();
167   return true;
168 }
169