Skip to content

Commit

Permalink
Added formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
jaytaph committed Aug 24, 2024
1 parent b2788c0 commit 695c955
Show file tree
Hide file tree
Showing 18 changed files with 72 additions and 83 deletions.
4 changes: 3 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ build: ## Build the project
section "Cargo build" ;\
cargo build --all

format: ## Fix formatting and clippy errors
fix-format: ## Fix formatting and clippy errors
cargo fmt --all
cargo clippy --all --fix --allow-dirty --allow-staged

check-format: test_clippy test_fmt ## Check the project for clippy and formatting errors

test_unit:
source test-utils.sh ;\
section "Cargo test" ;\
Expand Down
2 changes: 0 additions & 2 deletions benches/tree_iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ fn wikipedia_main_page(c: &mut Criterion) {
let html_file = File::open("tests/data/tree_iterator/wikipedia_main.html").unwrap();
let mut stream = ByteStream::new(None);
let _ = stream.read_from_file(html_file, Some(gosub_shared::byte_stream::Encoding::UTF8));
stream.set_confidence(gosub_shared::byte_stream::Confidence::Certain);

let main_document = DocumentBuilder::new_document(None);
let document = Document::clone(&main_document);
Expand All @@ -43,7 +42,6 @@ fn stackoverflow_home(c: &mut Criterion) {
let html_file = File::open("tests/data/tree_iterator/stackoverflow.html").unwrap();
let mut bytestream = ByteStream::new(None);
let _ = bytestream.read_from_file(html_file, Some(gosub_shared::byte_stream::Encoding::UTF8));
bytestream.set_confidence(gosub_shared::byte_stream::Confidence::Certain);

let main_document = DocumentBuilder::new_document(None);
let document = Document::clone(&main_document);
Expand Down
7 changes: 6 additions & 1 deletion crates/gosub_css3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,12 @@ impl<'stream> Css3<'stream> {

match result {
Ok(Some(node)) => Ok(node),
Ok(None) => Ok(Node::new(NodeType::StyleSheet { children: Vec::new() }, Location::default())),
Ok(None) => Ok(Node::new(
NodeType::StyleSheet {
children: Vec::new(),
},
Location::default(),
)),
Err(e) => Err(e),
}
}
Expand Down
12 changes: 6 additions & 6 deletions crates/gosub_css3/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,12 +156,12 @@ pub enum NodeType {
Container {
children: Vec<Node>,
},
Range {
left: Node,
left_comparison: Node,
middle: Node,
right_comparison: Option<Node>,
right: Option<Node>
Range {
left: Node,
left_comparison: Node,
middle: Node,
right_comparison: Option<Node>,
right: Option<Node>,
},
}

Expand Down
1 change: 0 additions & 1 deletion crates/gosub_css3/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,6 @@ impl Css3<'_> {
pub fn consume_any_ident(&mut self) -> Result<String, Error> {
let t = self.tokenizer.consume();


match t.token_type {
TokenType::Delim('.') => {
let t = self.tokenizer.consume();
Expand Down
31 changes: 12 additions & 19 deletions crates/gosub_css3/src/parser/at_rule/media.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,42 +3,35 @@ use crate::tokenizer::TokenType;
use crate::{Css3, Error};

impl Css3<'_> {

fn parse_media_read_term(&mut self) -> Result<Node, Error> {
self.consume_whitespace_comments();

let loc = self.tokenizer.current_location();

let t = self.consume_any()?;
match t.token_type {
TokenType::Ident(ident) => {
return Ok(Node::new(NodeType::Ident { value: ident }, loc));
}
TokenType::Number(value) => {
return Ok(Node::new(NodeType::Number { value }, loc));
}
TokenType::Ident(ident) => Ok(Node::new(NodeType::Ident { value: ident }, loc)),
TokenType::Number(value) => Ok(Node::new(NodeType::Number { value }, loc)),
TokenType::Dimension { value, unit } => {
return Ok(Node::new(NodeType::Dimension { value, unit }, loc));
Ok(Node::new(NodeType::Dimension { value, unit }, loc))
}
TokenType::Function(name) => {
let name = name.to_lowercase();
let args = self.parse_pseudo_function(name.as_str())?;
self.consume(TokenType::RParen)?;

return Ok(Node::new(
Ok(Node::new(
NodeType::Function {
name,
arguments: vec![args],
},
loc,
));
}
_ => {
return Err(Error::new(
"Expected identifier, number, dimension, or ratio".to_string(),
loc,
));
))
}
_ => Err(Error::new(
"Expected identifier, number, dimension, or ratio".to_string(),
loc,
)),
}
}

Expand Down Expand Up @@ -175,8 +168,8 @@ impl Css3<'_> {

self.consume_whitespace_comments();
self.consume_delim(')')?;
return Ok(Node::new(

Ok(Node::new(
NodeType::Range {
left,
left_comparison,
Expand All @@ -185,7 +178,7 @@ impl Css3<'_> {
right,
},
loc,
));
))
}

pub fn parse_media_feature_or_range(&mut self, kind: FeatureKind) -> Result<Node, Error> {
Expand Down
30 changes: 10 additions & 20 deletions crates/gosub_css3/src/parser/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,10 @@ impl Css3<'_> {

TokenType::AtKeyword(_) => {
self.tokenizer.reconsume();
match self.parse_at_rule(mode == BlockParseMode::StyleBlock)? {
Some(at_rule_node) => {
children.push(at_rule_node);
}
None => {} // No valid at-rule found. Ok since we are ignoring errors here
if let Some(at_rule_node) =
self.parse_at_rule(mode == BlockParseMode::StyleBlock)?
{
children.push(at_rule_node);
}
semicolon_seperated = false;
continue;
Expand All @@ -95,19 +94,13 @@ impl Css3<'_> {
self.tokenizer.reconsume();
if t.is_delim('&') {
let rule = self.parse_consume_rule()?;
match rule {
Some(rule_node) => {
children.push(rule_node);
}
None => {} // No valid rule found. Ok since we are ignoring errors here
if let Some(rule_node) = rule {
children.push(rule_node);
}
} else {
let declaration = self.parse_consume_declaration()?;
match declaration {
Some(declaration_node) => {
children.push(declaration_node);
}
None => {} // No valid declaration found. Ok since we are ignoring errors here
if let Some(declaration_node) = declaration {
children.push(declaration_node);
}
}

Expand All @@ -126,11 +119,8 @@ impl Css3<'_> {
BlockParseMode::RegularBlock => {
self.tokenizer.reconsume();

match self.parse_consume_rule()? {
Some(rule_node) => {
children.push(rule_node);
}
None => {} // No valid rule found. Ok since we are ignoring errors here
if let Some(rule_node) = self.parse_consume_rule()? {
children.push(rule_node);
}

semicolon_seperated = false;
Expand Down
7 changes: 4 additions & 3 deletions crates/gosub_css3/src/parser/declaration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ impl Css3<'_> {
Ok(None)
}


fn parse_declaration_internal(&mut self) -> Result<Node, Error> {
let loc = self.tokenizer.current_location();

Expand Down Expand Up @@ -97,7 +96,10 @@ impl Css3<'_> {
}

fn parse_until_declaration_end(&mut self) {
log::trace!("parse_until_declaration_end, now at: {:?}", self.tokenizer.current_location());
log::trace!(
"parse_until_declaration_end, now at: {:?}",
self.tokenizer.current_location()
);
loop {
let t = self.consume_any();
if t.is_err() {
Expand All @@ -122,4 +124,3 @@ impl Css3<'_> {
}
}
}

3 changes: 1 addition & 2 deletions crates/gosub_css3/src/parser/rule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use crate::tokenizer::TokenType;
use crate::{Css3, Error};

impl Css3<'_> {

// Either the rule parsing succeeds as a whole, or not. When not a valid rule is found, we
// return None if the config.ignore_errors is set to true, otherwise this will return an Err
// and is handled by the caller
Expand Down Expand Up @@ -59,7 +58,7 @@ mod tests {
stream.close();

let mut parser = crate::Css3::new(&mut stream);
let result = parser.$func().unwrap();
let result = parser.$func().unwrap().unwrap();

let w = Walker::new(&result);
assert_eq!(w.walk_to_string(), $expected);
Expand Down
16 changes: 5 additions & 11 deletions crates/gosub_css3/src/parser/stylesheet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,16 @@ impl Css3<'_> {
self.tokenizer.reconsume();

let at_rule = self.parse_at_rule(false)?;
match at_rule {
Some(at_rule_node) => {
children.push(at_rule_node);
}
None => {} // No valid at-rule found. Ok since we are ignoring errors here
if let Some(at_rule_node) = at_rule {
children.push(at_rule_node);
}
}
_ => {
self.tokenizer.reconsume();

let rule = self.parse_rule()?;
match rule {
Some(rule_node) => {
children.push(rule_node);
}
None => {} // No valid rule found. Ok since we are ignoring errors here
if let Some(rule_node) = rule {
children.push(rule_node);
}
}
}
Expand All @@ -58,7 +52,7 @@ impl Css3<'_> {
for t in self.tokenizer.get_tokens() {
log::trace!("{:?}", t);
}

if children.is_empty() {
return Ok(None);
}
Expand Down
10 changes: 4 additions & 6 deletions crates/gosub_css3/src/parser/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,10 @@ impl Css3<'_> {
let node = Node::new(NodeType::Operator(",".into()), t.location);
Ok(Some(node))
}
TokenType::LBracket => {
Err(Error::new(
"Unexpected token [".to_string(),
self.tokenizer.current_location(),
))
}
TokenType::LBracket => Err(Error::new(
"Unexpected token [".to_string(),
self.tokenizer.current_location(),
)),
TokenType::QuotedString(value) => {
let node = Node::new(NodeType::String { value }, t.location);
Ok(Some(node))
Expand Down
2 changes: 1 addition & 1 deletion crates/gosub_css3/src/tokenizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ impl Debug for Token {
"\r" => write!(f, "CR at {:?}", self.location),
"\n" => write!(f, "LF at {:?}", self.location),
_ => write!(f, "{:?} at {:?}", self.token_type, self.location),
}
};
} else {
write!(f, "{:?} at {:?}", self.token_type, self.location)
}
Expand Down
8 changes: 7 additions & 1 deletion crates/gosub_css3/src/walker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,13 @@ fn inner_walk(node: &Node, depth: usize, f: &mut dyn Write) -> Result<(), std::i
}
NodeType::Cdo => {}
NodeType::Cdc => {}
NodeType::Range { left, left_comparison, middle, right_comparison, right } => {
NodeType::Range {
left,
left_comparison,
middle,
right_comparison,
right,
} => {
writeln!(f, "{}[Range]", prefix)?;
inner_walk(left, depth + 1, f)?;
inner_walk(left_comparison, depth + 1, f)?;
Expand Down
4 changes: 2 additions & 2 deletions crates/gosub_shared/src/byte_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ pub struct Config {
/// Current encoding
pub encoding: Encoding,
/// Treat any CRLF pairs as a single LF
pub cr_lf_as_one: bool
pub cr_lf_as_one: bool,
}

impl Default for Config {
Expand Down Expand Up @@ -298,7 +298,7 @@ impl ByteStream {
#[must_use]
pub fn new(config: Option<Config>) -> Self {
Self {
config: config.unwrap_or(Config::default()),
config: config.unwrap_or_default(),
buffer: Vec::new(),
buffer_pos: 0,
u8_buffer: Vec::new(),
Expand Down
15 changes: 11 additions & 4 deletions src/bin/css3-parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,11 @@ fn main() -> Result<()> {
let now = Instant::now();
let result = Css3::parse(css.as_str(), config);
let elapsed_time = now.elapsed();
println!("Running css3 parser of ({}) took {} ms.", byte_size(css.len() as u64), elapsed_time.as_millis());
println!(
"Running css3 parser of ({}) took {} ms.",
byte_size(css.len() as u64),
elapsed_time.as_millis()
);

if result.is_err() {
let err = result.err().unwrap();
Expand Down Expand Up @@ -156,13 +160,16 @@ fn print_tokens(css: String) {
}
}


/// Returns a human-readable byte size
fn byte_size(bytes: u64) -> String {
let sizes = ["B", "KB", "MB", "GB", "TB"];
if bytes == 0 {
return "0 B".to_string();
}
let i = (bytes as f64).log2().floor() as i32 / 10;
format!("{:.2} {}", bytes as f64 / 2_f64.powi(i * 10), sizes[i as usize])
}
format!(
"{:.2} {}",
bytes as f64 / 2_f64.powi(i * 10),
sizes[i as usize]
)
}
1 change: 0 additions & 1 deletion src/wasm/html.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ pub fn html_parser(input: &str, opts: HTMLOptions) -> HTMLOutput {

let mut stream = ByteStream::new(None);
stream.read_from_str(&input, Some(Encoding::UTF8));
stream.set_confidence(Confidence::Certain);
stream.close();

let mut errors = String::new();
Expand Down
1 change: 0 additions & 1 deletion src/wasm/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ async fn renderer_internal(opts: RendererOptions) -> Result<()> {
fn load_html_rendertree(input: &str, url: Url) -> Result<StyleTree> {
let mut stream = ByteStream::new(None);
stream.read_from_str(&input, Some(Encoding::UTF8));
stream.set_confidence(Confidence::Certain);
stream.close();

let doc_handle = DocumentBuilder::new_document(Some(url));
Expand Down
1 change: 0 additions & 1 deletion src/wasm/styles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ pub fn styles_parser(input: &str, opts: StylesOptions) -> StylesOutput {

let mut stream = ByteStream::new(None);
stream.read_from_str(&input, Some(Encoding::UTF8));
stream.set_confidence(Confidence::Certain);
stream.close();

let mut errors = String::new();
Expand Down

0 comments on commit 695c955

Please sign in to comment.