Skip to content

Commit 37fb1f5

Browse files
authored
Fix compiler-rs lint warnings (#2318)
* Fix clippy warnings and errors * Do not ignore .d.ts files, update wasm module * Update code owners and labeler config
1 parent 365e1a9 commit 37fb1f5

File tree

18 files changed

+95
-78
lines changed

18 files changed

+95
-78
lines changed

.github/CODEOWNERS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
# Specification tooling owners
55
/.github/ @elastic/clients-team
66
/compiler/ @elastic/clients-team
7+
/compiler-rs/ @elastic/clients-team
78
/typescript-generator/ @elastic/clients-team
89
/specification/_json_spec/ @elastic/clients-team
910
/specification/_spec_utils/ @elastic/clients-team

.github/labeler.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ generator:typescript:
99

1010
compiler:
1111
- 'compiler/**/*'
12+
- 'compiler-rs/**/*'

.gitignore

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,6 @@ node_modules
4040
# Build output directory
4141
dist/
4242
flight-recorder-generator/output
43-
*.d.ts
44-
java-generator/*.js
4543
specification/**/*.js
4644
specification/lib
4745

compiler-rs/.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
.idea
2-
target
2+
target/

compiler-rs/clients_schema/src/lib.rs

Lines changed: 25 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
// specific language governing permissions and limitations
1616
// under the License.
1717

18-
use std::cmp::Ordering;
1918
use std::fmt::{Debug, Display, Formatter};
2019
use anyhow::anyhow;
2120
use indexmap::IndexMap;
@@ -37,24 +36,26 @@ const fn is_false(v: &bool) -> bool {
3736
!(*v)
3837
}
3938

39+
// String type where efficient cloning brings significant improvements
40+
// ArcStr is a compact reference counted string that makes cloning a very cheap operation.
41+
// This is particularly important for `TypeName` that is cloned a lot, e.g. for `IndexedModel` keys
42+
// See https://swatinem.de/blog/optimized-strings/ for a general discussion
43+
//
44+
// TODO: interning at deserialization time to reuse identical values (links from values to types)
45+
type FastString = arcstr::ArcStr;
46+
4047
pub trait Documented {
4148
fn doc_url(&self) -> Option<&str>;
4249
fn doc_id(&self) -> Option<&str>;
4350
fn description(&self) -> Option<&str>;
4451
fn since(&self) -> Option<&str>;
4552
}
4653

47-
// ArcStr is a compact reference counted string that makes cloning a very cheap operation.
48-
// This is particularly important for `TypeName` that is cloned a lot, e.g. for `IndexedModel` keys
49-
// See https://swatinem.de/blog/optimized-strings/ for a general discussion
50-
//
51-
// TODO: interning at deserialization time to reuse identical values (links from values to types)
52-
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Hash)]
54+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
5355
pub struct TypeName {
54-
pub namespace: arcstr::ArcStr,
55-
pub name: arcstr::ArcStr,
56-
// pub namespace: String,
57-
// pub name: String,
56+
// Order is important for Ord implementation
57+
pub namespace: FastString,
58+
pub name: FastString,
5859
}
5960

6061
impl TypeName {
@@ -76,15 +77,6 @@ impl Display for TypeName {
7677
}
7778
}
7879

79-
impl Ord for TypeName {
80-
fn cmp(&self, other: &Self) -> Ordering {
81-
match self.namespace.cmp(&other.namespace) {
82-
Ordering::Equal => self.name.cmp(&other.name),
83-
ordering @ _ => ordering,
84-
}
85-
}
86-
}
87-
8880
//-----------------------------------------------------------------------------
8981

9082
///
@@ -318,7 +310,7 @@ impl Flavor {
318310
pub fn visibility(&self, availabilities: &Option<Availabilities>) -> Option<Visibility> {
319311
if let Some(ref availabilities) = availabilities {
320312
// Some availabilities defined
321-
if let Some(ref availability) = availabilities.get(self) {
313+
if let Some(availability) = availabilities.get(self) {
322314
// This one exists. Public by default
323315
availability.visibility.clone().or(Some(Visibility::Public))
324316
} else {
@@ -468,6 +460,7 @@ pub struct Inherits {
468460

469461
#[derive(Debug, Clone, Serialize, Deserialize)]
470462
#[serde(rename_all = "snake_case", tag="kind")]
463+
#[allow(clippy::large_enum_variant)]
471464
pub enum TypeDefinition {
472465
Interface(Interface),
473466
Request(Request),
@@ -1143,22 +1136,22 @@ impl<'a> serde::de::Visitor<'a> for IndexMapVisitor {
11431136
// Conversions between Model and IndexedModel
11441137
//-------------------------------------------------------------------------------------------------
11451138

1146-
impl Into<IndexedModel> for Model {
1147-
fn into(self) -> IndexedModel {
1139+
impl From<Model> for IndexedModel {
1140+
fn from(value: Model) -> Self {
11481141
IndexedModel {
1149-
info: self.info,
1150-
endpoints: self.endpoints,
1151-
types: self.types.into_iter().map(|t| (t.name().clone(), t)).collect(),
1142+
info: value.info,
1143+
endpoints: value.endpoints,
1144+
types: value.types.into_iter().map(|t| (t.name().clone(), t)).collect(),
11521145
}
11531146
}
11541147
}
11551148

1156-
impl Into<Model> for IndexedModel {
1157-
fn into(self) -> Model {
1149+
impl From<IndexedModel> for Model {
1150+
fn from(value: IndexedModel) -> Model {
11581151
Model {
1159-
info: self.info,
1160-
endpoints: self.endpoints,
1161-
types: self.types.into_iter().map(|(_, t)| t).collect(),
1152+
info: value.info,
1153+
endpoints: value.endpoints,
1154+
types: value.types.into_iter().map(|(_, t)| t).collect(),
11621155
}
11631156
}
11641157
}
@@ -1193,7 +1186,7 @@ mod tests {
11931186
let search_type = result.get_type(&search_req).unwrap();
11941187

11951188
match search_type {
1196-
TypeDefinition::Request(r) => assert_eq!(true, !r.path.is_empty()),
1189+
TypeDefinition::Request(r) => assert!(!r.path.is_empty()),
11971190
_ => panic!("Expecting a Request")
11981191
};
11991192
}

compiler-rs/clients_schema/src/transform/availability.rs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,14 @@ use crate::{Availabilities, Body, IndexedModel, Inherits, Property, TypeDefiniti
2020
use crate::transform::Worksheet;
2121

2222
pub struct Availability {
23+
#[allow(clippy::type_complexity)]
2324
avail_filter: Box<dyn Fn(&Option<Availabilities>) -> bool>,
2425
// Note: we could have avoided the use of interior mutability by adding
2526
// a `&mut Worksheet` parameter to all methods.
2627
worksheet: RefCell<Worksheet>,
2728
}
2829

29-
impl <'a> Availability {
30+
impl Availability {
3031
pub fn filter (mut model: IndexedModel, avail_filter: fn(&Option<Availabilities>) -> bool) -> anyhow::Result<IndexedModel> {
3132
let filter = Availability {
3233
avail_filter: Box::new(avail_filter),
@@ -38,8 +39,9 @@ impl <'a> Availability {
3839

3940
// Initialize worksheet with request and response of all retained endpoints
4041
for endpoint in &model.endpoints {
41-
endpoint.request.as_ref().map(|name| filter.filter_type(name));
42-
endpoint.response.as_ref().map(|name| filter.filter_type(name));
42+
for name in [&endpoint.request, &endpoint.response].into_iter().flatten() {
43+
filter.filter_type(name);
44+
}
4345
}
4446

4547
while let Some(name) = {
@@ -57,7 +59,7 @@ impl <'a> Availability {
5759
let ws = filter.worksheet.borrow();
5860
model.types.retain(|k, _| ws.was_visited(k));
5961

60-
return Ok(model);
62+
Ok(model)
6163
}
6264

6365
fn is_available(&self, availabilities: &Option<Availabilities>) -> bool {
@@ -71,7 +73,7 @@ impl <'a> Availability {
7173
fn filter_typedef(&self, typedef: &mut TypeDefinition) {
7274
match typedef {
7375
TypeDefinition::Interface(ref mut itf) => {
74-
itf.inherits.as_ref().map(|i| self.filter_inherits(i));
76+
itf.inherits.iter().for_each(|i| self.filter_inherits(i));
7577
itf.behaviors.iter().for_each(|i| self.filter_behaviors(i));
7678
self.filter_properties(&mut itf.properties);
7779
},
@@ -86,7 +88,7 @@ impl <'a> Availability {
8688
},
8789

8890
TypeDefinition::Request(ref mut request) => {
89-
request.inherits.as_ref().map(|i| self.filter_inherits(i));
91+
request.inherits.iter().for_each(|i| self.filter_inherits(i));
9092
request.behaviors.iter().for_each(|i| self.filter_behaviors(i));
9193
self.filter_properties(&mut request.path);
9294
self.filter_properties(&mut request.query);
@@ -113,7 +115,7 @@ impl <'a> Availability {
113115
fn filter_properties(&self, props: &mut Vec<Property>) {
114116
props.retain(|p| self.is_available(&p.availability));
115117
for prop in props {
116-
self.filter_value_of(&mut prop.typ);
118+
self.filter_value_of(&prop.typ);
117119
}
118120
}
119121

compiler-rs/clients_schema/src/transform/expand_generics.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,9 @@ pub fn expand_generics(
4646
let mut ctx = Ctx::default();
4747

4848
for endpoint in &model.endpoints {
49-
endpoint.request.as_ref().map(|t| expand_root_type(&t, &model, &mut ctx));
50-
endpoint.response.as_ref().map(|t| expand_root_type(&t, &model, &mut ctx));
49+
for name in [&endpoint.request, &endpoint.response].into_iter().flatten() {
50+
expand_root_type(name, &model, &mut ctx)?;
51+
}
5152
}
5253

5354
// Add new types that were created to the model
@@ -210,7 +211,7 @@ pub fn expand_generics(
210211
// We keep the generic parameters of behaviors, but expand their value
211212
for behavior in behaviors {
212213
for arg in &mut behavior.generics {
213-
*arg = expand_valueof(arg, &mappings, model, ctx)?;
214+
*arg = expand_valueof(arg, mappings, model, ctx)?;
214215
}
215216
}
216217
Ok(())
@@ -309,7 +310,7 @@ pub fn expand_generics(
309310
/// Builds the mapping from generic parameter name to actual value
310311
///
311312
fn param_mapping(generics: &GenericParams, args: GenericArgs) -> GenericMapping {
312-
generics.iter().map(|name| name.clone()).zip(args).collect()
313+
generics.iter().cloned().zip(args).collect()
313314
}
314315

315316
///
@@ -394,10 +395,10 @@ mod tests {
394395
if canonical_json != json_no_generics {
395396
std::fs::create_dir("test-output")?;
396397
let mut out = std::fs::File::create("test-output/schema-no-generics-canonical.json")?;
397-
out.write(canonical_json.as_bytes())?;
398+
out.write_all(canonical_json.as_bytes())?;
398399

399400
let mut out = std::fs::File::create("test-output/schema-no-generics-new.json")?;
400-
out.write(json_no_generics.as_bytes())?;
401+
out.write_all(json_no_generics.as_bytes())?;
401402

402403
panic!("Output differs from the canonical version. Both were written to 'test-output'");
403404
}

compiler-rs/clients_schema/src/transform/mod.rs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,20 +47,24 @@ impl Worksheet {
4747
}
4848
}
4949

50+
/// Has this type name been visited?
51+
pub fn was_visited(&self, name: &TypeName) -> bool {
52+
self.visited.contains(name)
53+
}
54+
}
55+
56+
impl Iterator for Worksheet {
57+
type Item = TypeName;
58+
5059
/// Retrieves a type name from the work list, if some are left. This assumes the caller will
5160
/// process the corresponding type, and thus adds it to the list of visited type names.
52-
pub fn next(&mut self) -> Option<TypeName> {
61+
fn next(&mut self) -> Option<Self::Item> {
5362
let result = self.pending.pop();
5463
if let Some(ref name) = result {
5564
self.visited.insert(name.clone());
5665
}
5766
result
5867
}
59-
60-
/// Has this type name been visited?
61-
pub fn was_visited(&self, name: &TypeName) -> bool {
62-
self.visited.contains(name)
63-
}
6468
}
6569

6670
/// Transform a model to only keep the endpoints and types that match a predicate on the `availability`

compiler-rs/clients_schema_to_openapi/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ pub fn convert_schema_file(
3939
// Parsing from a string is faster than using a buffered reader when there is a need for look-ahead
4040
// See https://github.com/serde-rs/json/issues/160
4141
let json = &std::fs::read_to_string(path)?;
42-
let json_deser = &mut serde_json::Deserializer::from_str(&json);
42+
let json_deser = &mut serde_json::Deserializer::from_str(json);
4343

4444
let mut unused = HashSet::new();
4545
let mut model: IndexedModel = serde_ignored::deserialize(json_deser, |path| {
@@ -95,7 +95,7 @@ pub fn convert_schema(
9595
extensions: Default::default(),
9696
};
9797

98-
let mut tac = TypesAndComponents::new(&model, openapi.components.as_mut().unwrap());
98+
let mut tac = TypesAndComponents::new(model, openapi.components.as_mut().unwrap());
9999

100100
// Endpoints
101101
for endpoint in &model.endpoints {

compiler-rs/clients_schema_to_openapi/src/paths.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ pub fn add_endpoint(endpoint: &clients_schema::Endpoint, tac: &mut TypesAndCompo
4848
//};
4949

5050
// Will we produce multiple paths? If true, we will register components for reuse across paths
51-
let is_multipath = endpoint.urls.len() > 1 || endpoint.urls.iter().find(|u| u.methods.len() > 1).is_some();
51+
let is_multipath = endpoint.urls.len() > 1 || endpoint.urls.iter().any(|u| u.methods.len() > 1);
5252

5353
let request = tac.model.get_request(endpoint.request.as_ref().unwrap())?;
5454

compiler-rs/clients_schema_to_openapi/src/schemas.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ impl <'a> TypesAndComponents<'a> {
292292
// A container is represented by an object will all optional properties and exactly one that
293293
// needs to be set.
294294
let mut schema = ObjectType {
295-
properties: self.convert_properties(variant_props.iter().map(|p| *p))?,
295+
properties: self.convert_properties(variant_props.iter().copied())?,
296296
required: vec![],
297297
additional_properties: None,
298298
min_properties: Some(1),
@@ -302,8 +302,8 @@ impl <'a> TypesAndComponents<'a> {
302302
if !container_props.is_empty() {
303303
// Create a schema for the container property, and group it in an "allOf" with variants
304304
let container_props_schema = ObjectType {
305-
properties: self.convert_properties(container_props.iter().map(|p| *p))?,
306-
required: self.required_properties(container_props.iter().map(|p| *p)),
305+
properties: self.convert_properties(container_props.iter().copied())?,
306+
required: self.required_properties(container_props.iter().copied()),
307307
additional_properties: None,
308308
min_properties: None,
309309
max_properties: None,
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
/* tslint:disable */
2+
/* eslint-disable */
3+
/**
4+
* @param {string} json
5+
* @param {string} flavor
6+
* @returns {string}
7+
*/
8+
export function convert_schema_to_openapi(json: string, flavor: string): string;
Binary file not shown.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
/* tslint:disable */
2+
/* eslint-disable */
3+
export const memory: WebAssembly.Memory;
4+
export function convert_schema_to_openapi(a: number, b: number, c: number, d: number, e: number): void;
5+
export function __wbindgen_add_to_stack_pointer(a: number): number;
6+
export function __wbindgen_malloc(a: number, b: number): number;
7+
export function __wbindgen_realloc(a: number, b: number, c: number, d: number): number;
8+
export function __wbindgen_free(a: number, b: number, c: number): void;

compiler-rs/openapi_to_clients_schema/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,14 +53,14 @@ fn generate_types(
5353
if let Some(ref components) = open_api.components {
5454
let mut types = types::Types::default();
5555
for (id, schema) in &components.schemas {
56-
let result = types::generate_type(open_api, &id, &schema.into(), &mut types);
56+
let result = types::generate_type(open_api, id, &schema.into(), &mut types);
5757

5858
if let Err(err) = result {
5959
warn!("Problem with type '{id}'\n {err}\n Definition: {:?}", &schema);
6060
}
6161
}
6262
let _ = types.check_tracker(); // TODO: actually fail
63-
model.types = types.types();
63+
model.types = types.types().into_iter().map(|t| (t.name().clone(), t)).collect();
6464
}
6565

6666
Ok(())

0 commit comments

Comments
 (0)