Skip to content

Commit

Permalink
clippy (#66)
Browse files Browse the repository at this point in the history
  • Loading branch information
flying-sheep authored Feb 27, 2025
1 parent 7e1d6e0 commit 930e849
Show file tree
Hide file tree
Showing 16 changed files with 461 additions and 445 deletions.
32 changes: 16 additions & 16 deletions document_tree/src/attribute_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,14 @@ pub enum Measure {
impl FromStr for AlignHV {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use self::AlignHV::*;
use self::AlignHV as A;
Ok(match s {
"top" => Top,
"middle" => Middle,
"bottom" => Bottom,
"left" => Left,
"center" => Center,
"right" => Right,
"top" => A::Top,
"middle" => A::Middle,
"bottom" => A::Bottom,
"left" => A::Left,
"center" => A::Center,
"right" => A::Right,
s => bail!("Invalid Alignment {}", s),
})
}
Expand All @@ -119,22 +119,22 @@ impl From<&str> for NameToken {
impl FromStr for Measure {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use self::Measure::*;
use self::Measure as M;
let re =
Regex::new(r"(?P<float>\d+\.\d*|\.?\d+)\s*(?P<unit>em|ex|mm|cm|in|px|pt|pc)").unwrap();
let caps: regex::Captures = re
.captures(s)
.ok_or_else(|| format_err!("Invalid measure"))?;
let value: f64 = caps["float"].parse()?;
Ok(match &caps["unit"] {
"em" => Em(value),
"ex" => Ex(value),
"mm" => Mm(value),
"cm" => Cm(value),
"in" => In(value),
"px" => Px(value),
"pt" => Pt(value),
"pc" => Pc(value),
"em" => M::Em(value),
"ex" => M::Ex(value),
"mm" => M::Mm(value),
"cm" => M::Cm(value),
"in" => M::In(value),
"px" => M::Px(value),
"pt" => M::Pt(value),
"pc" => M::Pc(value),
_ => unreachable!(),
})
}
Expand Down
1 change: 1 addition & 0 deletions document_tree/src/element_categories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::fmt::{self, Debug, Formatter};

use serde_derive::Serialize;

#[allow(clippy::wildcard_imports)]
use crate::elements::*;

pub trait HasChildren<C> {
Expand Down
2 changes: 2 additions & 0 deletions document_tree/src/elements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use serde_derive::Serialize;
use std::path::PathBuf;

use crate::attribute_types::{CanBeEmpty, ID, NameToken};
#[allow(clippy::wildcard_imports)]
use crate::element_categories::*;
use crate::extra_attributes::{self, ExtraAttributes};

Expand Down Expand Up @@ -132,6 +133,7 @@ macro_rules! impl_new {(
$(#[$fattr])* $field: $typ,
)* }
impl $name {
#[must_use]
pub fn new( $( $field: $typ, )* ) -> $name { $name { $( $field, )* } }
}
)}
Expand Down
1 change: 1 addition & 0 deletions document_tree/src/extra_attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ impl_extra!(RawInline { space: FixedSpace, format: Vec<NameToken> });
pub type ImageInline = Image;

impl Image {
#[must_use]
pub fn new(uri: Url) -> Image {
Image {
uri,
Expand Down
5 changes: 3 additions & 2 deletions document_tree/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![warn(clippy::pedantic)]
#![recursion_limit = "256"]

//! See [doctree][] reference.
Expand Down Expand Up @@ -33,7 +34,7 @@ mod tests {
title.append_child(image);
doc.append_child(title);

println!("{:?}", doc);
println!("{doc:?}");
}

#[test]
Expand All @@ -49,6 +50,6 @@ mod tests {
.into(),
]);

println!("{:?}", doc);
println!("{doc:?}");
}
}
11 changes: 11 additions & 0 deletions document_tree/src/url.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,19 @@ fn starts_with_scheme(input: &str) -> bool {
pub struct Url(String);

impl Url {
/// Parse an absolute URL.
///
/// # Errors
/// Returns an error if the string is not a valid absolute URL.
pub fn parse_absolute(input: &str) -> Result<Self, ParseError> {
Ok(url::Url::parse(input)?.into())
}

/// Parse a relative path as URL.
///
/// # Errors
/// Returns an error if the string is not a relative path or can’t be converted to an url.
#[allow(clippy::missing_panics_doc)]
pub fn parse_relative(input: &str) -> Result<Self, ParseError> {
// We're assuming that any scheme through which RsT documents are being
// accessed is a hierarchical scheme, and so we can parse relative to a
Expand All @@ -49,6 +59,7 @@ impl Url {
Err(ParseError::SetHostOnCannotBeABaseUrl)
}
}
#[must_use]
pub fn as_str(&self) -> &str {
self.0.as_str()
}
Expand Down
14 changes: 6 additions & 8 deletions parser/src/conversion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ use crate::pest_rst::Rule;

fn ssubel_to_section_unchecked_mut(ssubel: &mut c::StructuralSubElement) -> &mut e::Section {
match ssubel {
c::StructuralSubElement::SubStructure(b) => match **b {
c::SubStructure::Section(ref mut s) => s,
c::StructuralSubElement::SubStructure(b) => match b.as_mut() {
c::SubStructure::Section(s) => s,
_ => unreachable!(),
},
_ => unreachable!(),
Expand All @@ -27,16 +27,14 @@ fn get_level<'tl>(
section_idxs: &[Option<usize>],
) -> &'tl mut Vec<c::StructuralSubElement> {
let mut level = toplevel;
for maybe_i in section_idxs {
if let Some(i) = *maybe_i {
level = ssubel_to_section_unchecked_mut(&mut level[i]).children_mut();
}
for i in section_idxs.iter().flatten().copied() {
level = ssubel_to_section_unchecked_mut(&mut level[i]).children_mut();
}
level
}

pub fn convert_document(pairs: Pairs<Rule>) -> Result<e::Document, Error> {
use self::block::TitleOrSsubel::*;
use self::block::TitleOrSsubel::{Ssubel, Title};

let mut toplevel: Vec<c::StructuralSubElement> = vec![];
// The kinds of section titles encountered.
Expand All @@ -60,7 +58,7 @@ pub fn convert_document(pairs: Pairs<Rule>) -> Result<e::Document, Error> {
// If idx > len: Add None for skipped levels
// TODO: test skipped levels
while section_idxs.len() < idx {
section_idxs.push(None)
section_idxs.push(None);
}
}
None => kinds.push(kind),
Expand Down
23 changes: 12 additions & 11 deletions parser/src/conversion/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub(super) enum TitleOrSsubel {
}

pub(super) fn convert_ssubel(pair: Pair<Rule>) -> Result<Option<TitleOrSsubel>, Error> {
use self::TitleOrSsubel::*;
use self::TitleOrSsubel::{Ssubel, Title};
Ok(Some(match pair.as_rule() {
Rule::title => {
let (t, k) = convert_title(pair)?;
Expand All @@ -48,7 +48,7 @@ fn convert_body_elem(pair: Pair<Rule>) -> Result<c::BodyElement, Error> {
Rule::target => convert_target(pair)?.into(),
Rule::substitution_def => convert_substitution_def(pair)?.into(),
Rule::block_quote_directive => convert_block_quote_directive(pair)?.into(),
Rule::admonition_gen => convert_admonition_gen(pair)?,
Rule::admonition_gen => convert_admonition_gen(pair),
Rule::image => convert_image::<e::Image>(pair)?.into(),
Rule::bullet_list => convert_bullet_list(pair)?.into(),
Rule::block_quote => convert_block_quote(pair)?.into(),
Expand All @@ -74,7 +74,7 @@ fn convert_title(pair: Pair<Rule>) -> Result<(e::Title, TitleKind), Error> {
title_inlines = Some(convert_inlines(p)?);
}
Rule::adornments => {
adornment_char = Some(p.as_str().chars().next().expect("Empty adornment?"))
adornment_char = Some(p.as_str().chars().next().expect("Empty adornment?"));
}
rule => unimplemented!("Unexpected rule in title: {:?}", rule),
};
Expand All @@ -100,7 +100,7 @@ fn convert_paragraph(pair: Pair<Rule>) -> Result<e::Paragraph, Error> {
}

fn convert_target(pair: Pair<Rule>) -> Result<e::Target, Error> {
let mut elem: e::Target = Default::default();
let mut elem = e::Target::default();
elem.extra_mut().anonymous = false;
for p in pair.into_inner() {
match p.as_rule() {
Expand All @@ -110,7 +110,7 @@ fn convert_target(pair: Pair<Rule>) -> Result<e::Target, Error> {
}
// TODO: also handle non-urls
Rule::link_target => elem.extra_mut().refuri = Some(p.parse()?),
rule => panic!("Unexpected rule in target: {:?}", rule),
rule => panic!("Unexpected rule in target: {rule:?}"),
}
}
Ok(elem)
Expand All @@ -123,7 +123,7 @@ fn convert_substitution_def(pair: Pair<Rule>) -> Result<e::SubstitutionDefinitio
let inner: Vec<c::TextOrInlineElement> = match inner_pair.as_rule() {
Rule::replace => convert_replace(inner_pair)?,
Rule::image => vec![convert_image::<e::ImageInline>(inner_pair)?.into()],
rule => panic!("Unknown substitution rule {:?}", rule),
rule => panic!("Unknown substitution rule {rule:?}"),
};
let mut subst_def = e::SubstitutionDefinition::with_children(inner);
subst_def.names_mut().push(at::NameToken(name));
Expand Down Expand Up @@ -164,13 +164,14 @@ where
}

fn parse_scale(pair: &Pair<Rule>) -> Result<u8, Error> {
use pest::error::{Error, ErrorVariant};

let input = pair.as_str().trim();
let input = if let Some(percentage) = input.strip_suffix('%') {
percentage.trim_end()
} else {
input
};
use pest::error::{Error, ErrorVariant};
Ok(input.parse().map_err(|e: std::num::ParseIntError| {
let var: ErrorVariant<Rule> = ErrorVariant::CustomError {
message: e.to_string(),
Expand All @@ -179,14 +180,14 @@ fn parse_scale(pair: &Pair<Rule>) -> Result<u8, Error> {
})?)
}

fn convert_admonition_gen(pair: Pair<Rule>) -> Result<c::BodyElement, Error> {
fn convert_admonition_gen(pair: Pair<Rule>) -> document_tree::element_categories::BodyElement {
let mut iter = pair.into_inner();
let typ = iter.next().unwrap().as_str();
// TODO: in reality it contains body elements.
let children: Vec<c::BodyElement> = iter
.map(|p| e::Paragraph::with_children(vec![p.as_str().into()]).into())
.collect();
Ok(match typ {
match typ {
"attention" => e::Attention::with_children(children).into(),
"hint" => e::Hint::with_children(children).into(),
"note" => e::Note::with_children(children).into(),
Expand All @@ -196,8 +197,8 @@ fn convert_admonition_gen(pair: Pair<Rule>) -> Result<c::BodyElement, Error> {
"important" => e::Important::with_children(children).into(),
"tip" => e::Tip::with_children(children).into(),
"warning" => e::Warning::with_children(children).into(),
typ => panic!("Unknown admontion type {}!", typ),
})
typ => panic!("Unknown admontion type {typ}!"),
}
}

fn convert_bullet_list(pair: Pair<Rule>) -> Result<e::BulletList, Error> {
Expand Down
Loading

0 comments on commit 930e849

Please sign in to comment.