Skip to content

Commit

Permalink
Fix lints suggested by clippy (#309)
Browse files Browse the repository at this point in the history
  • Loading branch information
aljazerzen authored Apr 9, 2024
1 parent 4f55df7 commit aec9760
Show file tree
Hide file tree
Showing 52 changed files with 482 additions and 530 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,10 @@
__pycache__
/Cargo.lock
/.idea
/.vscode

# nix stuff
/flake.nix
/flake.lock
/.envrc
/.direnv
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"rust-analyzer.cargo.features": ["unstable", "chrono"]
}
4 changes: 2 additions & 2 deletions edgedb-derive/src/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ pub fn derive(item: &syn::Item) -> syn::Result<TokenStream> {
{
let json: ::edgedb_protocol::model::Json =
::edgedb_protocol::queryable::Queryable::decode(decoder, buf)?;
Ok(::serde_json::from_str(json.as_ref())
.map_err(::edgedb_protocol::errors::decode_error)?)
::serde_json::from_str(json.as_ref())
.map_err(::edgedb_protocol::errors::decode_error)
}
fn check_descriptor(
ctx: &::edgedb_protocol::queryable::DescriptorContext,
Expand Down
8 changes: 4 additions & 4 deletions edgedb-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ let query_res: Vec<JsonData> = client.query(query, &()).await?;
extern crate proc_macro;

use proc_macro::TokenStream;
use syn::{self, parse_macro_input};
use syn::parse_macro_input;

mod attrib;
mod enums;
Expand All @@ -105,18 +105,18 @@ fn derive(item: &syn::Item) -> syn::Result<proc_macro2::TokenStream> {
));
}
};
let attrs = attrib::ContainerAttrs::from_syn(&attrs)?;
let attrs = attrib::ContainerAttrs::from_syn(attrs)?;
if attrs.json {
json::derive(item)
} else {
match item {
syn::Item::Struct(s) => shape::derive_struct(s),
syn::Item::Enum(s) => enums::derive_enum(s),
_ => {
return Err(syn::Error::new_spanned(item,
Err(syn::Error::new_spanned(item,
"can only derive Queryable for a struct and enum \
in non-JSON mode"
));
))
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions edgedb-derive/src/shape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ pub fn derive_struct(s: &syn::ItemStruct) -> syn::Result<TokenStream> {
}
});
let field_decoders = fields.iter().map(|field| {
let ref fieldname = field.name;
let fieldname = &field.name;
if field.attrs.json {
quote!{
let #fieldname: ::edgedb_protocol::model::Json =
Expand All @@ -99,15 +99,15 @@ pub fn derive_struct(s: &syn::ItemStruct) -> syn::Result<TokenStream> {
}
}).collect::<TokenStream>();
let field_checks = fields.iter().map(|field| {
let ref name_str = field.str_name;
let name_str = &field.str_name;
let mut result = quote!{
let el = &shape.elements[idx];
if(el.name != #name_str) {
return Err(ctx.wrong_field(#name_str, &el.name));
}
idx += 1;
};
let ref fieldtype = field.ty;
let fieldtype = &field.ty;
if field.attrs.json {
result.extend(quote!{
<::edgedb_protocol::model::Json as
Expand Down
2 changes: 1 addition & 1 deletion edgedb-derive/tests/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ fn old_decoder() -> Decoder {
let mut dec = Decoder::default();
dec.has_implicit_id = true;
dec.has_implicit_tid = true;
return dec;
dec
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion edgedb-derive/tests/list_scalar_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ fn old_decoder() -> Decoder {
let mut dec = Decoder::default();
dec.has_implicit_id = true;
dec.has_implicit_tid = true;
return dec;
dec
}

#[test]
Expand Down
14 changes: 7 additions & 7 deletions edgedb-errors/src/bin/edgedb_gen_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,18 @@ use std::env::args;
fn find_tag<'x>(template: &'x str, tag: &str) -> (usize, usize, &'x str) {
let tag_line = format!("// <{}>\n", tag);
let pos = template.find(&tag_line)
.expect(&format!("missing tag <{}>", tag));
let indent = template[..pos].rfind("\n").unwrap_or(0) + 1;
.unwrap_or_else(|| panic!("missing tag <{}>", tag));
let indent = template[..pos].rfind('\n').unwrap_or(0) + 1;
(pos, pos + tag_line.len(), &template[indent..pos])
}

fn find_macro<'x>(template: &'x str, name: &str) -> &'x str {
let macro_line = format!("macro_rules! {} {{", name);
let pos = template.find(&macro_line)
.map(|pos| pos + macro_line.len())
.expect(&format!("missing macro {}", name));
.unwrap_or_else(|| panic!("missing macro {}", name));
let body = template[pos..]
.find("{").map(|x| pos + x + 1)
.find('{').map(|x| pos + x + 1)
.and_then(|open| {
let mut level = 0;
for (idx, c) in template[open..].char_indices() {
Expand All @@ -32,11 +32,11 @@ fn find_macro<'x>(template: &'x str, name: &str) -> &'x str {
})
.map(|(begin, end)| template[begin..end].trim())
.expect("invalid macro");
return body;
body
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
let filename = args().skip(1).next().expect("single argument");
let filename = args().nth(1).expect("single argument");
let mut all_errors = Vec::new();
let mut all_tags = BTreeSet::<&str>::new();
let data = fs::read_to_string(filename)?;
Expand All @@ -49,7 +49,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let code = u32::from_str_radix(
&parts.next().expect("code always specified")
.strip_prefix("0x").expect("code contains 0x")
.replace("_", ""),
.replace('_', ""),
16
).expect("code is valid hex");
let name = parts.next().expect("name always specified");
Expand Down
13 changes: 4 additions & 9 deletions edgedb-errors/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::fmt;
use std::str;

use crate::kinds::{tag_check, error_name};
use crate::kinds::{UserError};
use crate::kinds::UserError;
use crate::traits::{ErrorKind, Field};


Expand Down Expand Up @@ -53,9 +53,6 @@ pub(crate) struct Inner {
pub fields: HashMap<(&'static str, TypeId), Box<dyn Any + Send + Sync>>,
}

trait Assert: Send + Sync + 'static {}
impl Assert for Error {}

impl Error {
pub fn is<T: ErrorKind>(&self) -> bool {
T::is_superclass_of(self.0.code)
Expand Down Expand Up @@ -182,12 +179,10 @@ impl fmt::Display for Error {
}
}

} else if let Some(last) = self.0.messages.last() {
write!(f, "{}: {}", kind, last)?;
} else {
if let Some(last) = self.0.messages.last() {
write!(f, "{}: {}", kind, last)?;
} else {
write!(f, "{}", kind)?;
}
write!(f, "{}", kind)?;
}
if let Some((line, col)) = self.line().zip(self.column()) {
write!(f, " (on line {}, column {})", line, col)?;
Expand Down
3 changes: 1 addition & 2 deletions edgedb-errors/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,7 @@ pub trait Sealed {
const TAGS: u32;
// TODO(tailhook) use uuids of errors instead
fn is_superclass_of(code: u32) -> bool {
let mask = 0xFFFFFFFF_u32
<< (Self::CODE.trailing_zeros() / 8)*8;
let mask = 0xFFFFFFFF_u32 << ((Self::CODE.trailing_zeros() / 8)*8);
code & mask == Self::CODE
}
fn has_tag(bit: u32) -> bool {
Expand Down
4 changes: 2 additions & 2 deletions edgedb-protocol/src/client_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -738,7 +738,7 @@ impl Decode for Restore {
let jobs = buf.get_u16();

let data = buf.copy_to_bytes(buf.remaining());
return Ok(Restore { jobs, headers, data })
Ok(Restore { jobs, headers, data })
}
}

Expand All @@ -754,7 +754,7 @@ impl Encode for RestoreBlock {
impl Decode for RestoreBlock {
fn decode(buf: &mut Input) -> Result<Self, DecodeError> {
let data = buf.copy_to_bytes(buf.remaining());
return Ok(RestoreBlock { data })
Ok(RestoreBlock { data })
}
}

Expand Down
28 changes: 14 additions & 14 deletions edgedb-protocol/src/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,14 +247,14 @@ impl ObjectShape {
impl Deref for ObjectShape {
type Target = ObjectShapeInfo;
fn deref(&self) -> &ObjectShapeInfo {
&*self.0
&self.0
}
}

impl Deref for NamedTupleShape {
type Target = NamedTupleShapeInfo;
fn deref(&self) -> &NamedTupleShapeInfo {
&*self.0
&self.0
}
}

Expand Down Expand Up @@ -293,7 +293,7 @@ impl<'a> CodecBuilder<'a> {
D::TypeAnnotation(..) => unreachable!(),
}
} else {
return errors::UnexpectedTypePos { position: pos.0 }.fail()?;
errors::UnexpectedTypePos { position: pos.0 }.fail()?
}
}
}
Expand Down Expand Up @@ -332,7 +332,7 @@ pub fn scalar_codec(uuid: &UuidVal) -> Result<Arc<dyn Codec>, CodecError> {
STD_BIGINT => Ok(Arc::new(BigInt {})),
CFG_MEMORY => Ok(Arc::new(ConfigMemory {})),
PGVECTOR_VECTOR => Ok(Arc::new(Vector {})),
_ => return errors::UndefinedBaseScalar { uuid: uuid.clone() }.fail()?,
_ => errors::UndefinedBaseScalar { uuid: uuid.clone() }.fail()?,
}
}

Expand Down Expand Up @@ -607,7 +607,7 @@ impl Tuple {
fn build(d: &descriptors::TupleTypeDescriptor, dec: &CodecBuilder)
-> Result<Tuple, CodecError>
{
return Ok(Tuple {
Ok(Tuple {
elements: d.element_types.iter()
.map(|&t| dec.build(t))
.collect::<Result<_, _>>()?,
Expand All @@ -628,14 +628,14 @@ impl NamedTuple {
}
}

fn decode_tuple<'t>(mut elements:DecodeTupleLike, codecs:&Vec<Arc<dyn Codec>>) -> Result<Vec<Value>, DecodeError>{
fn decode_tuple(mut elements:DecodeTupleLike, codecs: &[Arc<dyn Codec>]) -> Result<Vec<Value>, DecodeError>{
codecs
.iter()
.map(|codec| codec.decode(elements.read()?.ok_or_else(|| errors::MissingRequiredElement.build())?))
.collect::<Result<Vec<Value>, DecodeError>>()
}

fn decode_array_like<'t>(elements: DecodeArrayLike<'t>, codec:&dyn Codec) -> Result<Vec<Value>, DecodeError>{
fn decode_array_like(elements: DecodeArrayLike<'_>, codec:&dyn Codec) -> Result<Vec<Value>, DecodeError>{
elements
.map(|element| codec.decode(element?))
.collect::<Result<Vec<Value>, DecodeError>>()
Expand Down Expand Up @@ -763,7 +763,7 @@ impl Codec for ArrayAdapter {
let len = buf.get_i32() as usize;
ensure!(buf.remaining() >= len, errors::Underflow);
ensure!(buf.remaining() <= len, errors::ExtraData);
return self.0.decode(buf);
self.0.decode(buf)
}
fn encode(&self, buf: &mut BytesMut, val: &Value)
-> Result<(), EncodeError>
Expand Down Expand Up @@ -831,7 +831,7 @@ impl From<&str> for EnumValue {
impl std::ops::Deref for EnumValue {
type Target = str;
fn deref(&self) -> &str {
&*self.0
&self.0
}
}

Expand Down Expand Up @@ -1068,7 +1068,7 @@ pub(crate) fn encode_local_time(buf: &mut BytesMut, val: &model::LocalTime)

impl Codec for Json {
fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
RawCodec::decode(buf).map(|json: model::Json| Value::Json(json.into()))
RawCodec::decode(buf).map(|json: model::Json| Value::Json(json))
}
fn encode(&self, buf: &mut BytesMut, val: &Value)
-> Result<(), EncodeError>
Expand Down Expand Up @@ -1099,7 +1099,7 @@ impl Codec for Tuple {
fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
let elements = DecodeTupleLike::new_object(buf, self.elements.len())?;
let items = decode_tuple(elements, &self.elements)?;
return Ok(Value::Tuple(items))
Ok(Value::Tuple(items))
}
fn encode(&self, buf: &mut BytesMut, val: &Value)
-> Result<(), EncodeError>
Expand Down Expand Up @@ -1132,7 +1132,7 @@ impl Codec for NamedTuple {
fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
let elements = DecodeTupleLike::new_tuple(buf, self.codecs.len())?;
let fields = decode_tuple(elements, &self.codecs)?;
return Ok(Value::NamedTuple {
Ok(Value::NamedTuple {
shape: self.shape.clone(),
fields,
})
Expand Down Expand Up @@ -1296,7 +1296,7 @@ impl Codec for Range {
let pos = buf.len();
buf.reserve(4);
buf.put_u32(0); // replaced after serializing a value
self.element.encode(buf, &lower)?;
self.element.encode(buf, lower)?;
let len = buf.len()-pos-4;
buf[pos..pos+4].copy_from_slice(
&u32::try_from(len)
Expand All @@ -1308,7 +1308,7 @@ impl Codec for Range {
let pos = buf.len();
buf.reserve(4);
buf.put_u32(0); // replaced after serializing a value
self.element.encode(buf, &upper)?;
self.element.encode(buf, upper)?;
let len = buf.len()-pos-4;
buf[pos..pos+4].copy_from_slice(
&u32::try_from(len)
Expand Down
4 changes: 2 additions & 2 deletions edgedb-protocol/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ impl RawTypedesc {
}
}
pub fn decode(&self) -> Result<Typedesc, DecodeError> {
let ref mut cur = Input::new(
let cur = &mut Input::new(
self.proto.clone(),
self.data.clone(),
);
Expand Down Expand Up @@ -134,6 +134,6 @@ impl CompilationOptions {
cflags |= CompilationFlags::INJECT_OUTPUT_TYPE_IDS;
}
// TODO(tailhook) object ids
return cflags;
cflags
}
}
2 changes: 1 addition & 1 deletion edgedb-protocol/src/descriptors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ fn serialize_variables(enc: &mut Encoder, variables: &BTreeMap<String, Value>,
let mut serialized = 0;
for (idx, el) in desc.elements.iter().enumerate() {
if let Some(value) = variables.get(&el.name) {
value.check_descriptor(&enc.ctx, el.type_pos)?;
value.check_descriptor(enc.ctx, el.type_pos)?;
serialized += 1;
enc.buf.reserve(8);
enc.buf.put_u32(idx as u32);
Expand Down
8 changes: 4 additions & 4 deletions edgedb-protocol/src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ impl Output<'_> {
}
}
pub fn proto(&self) -> &ProtocolVersion {
&self.proto
self.proto
}
pub fn reserve(&mut self, size: usize) {
self.bytes.reserve(size)
Expand Down Expand Up @@ -170,10 +170,10 @@ impl Decode for String {
ensure!(buf.remaining() >= len, errors::Underflow);
let mut data = vec![0u8; len];
buf.copy_to_slice(&mut data[..]);
let result = String::from_utf8(data)

String::from_utf8(data)
.map_err(|e| e.utf8_error())
.context(errors::InvalidUtf8);
return result;
.context(errors::InvalidUtf8)
}
}

Expand Down
Loading

0 comments on commit aec9760

Please sign in to comment.