Thx clippy, main.rs takes file as pos arg

This commit is contained in:
niku 2023-05-20 20:40:53 +02:00
parent 1b45767cae
commit 37707fa5aa
4 changed files with 47 additions and 63 deletions

View File

@ -18,7 +18,7 @@ impl Parser {
while !self.eof() && test(self.next_char()) { while !self.eof() && test(self.next_char()) {
result.push(self.consume_char()); result.push(self.consume_char());
} }
return result; result
} }
fn next_char(&self) -> char { fn next_char(&self) -> char {
@ -30,7 +30,7 @@ impl Parser {
let (_, cur_char) = iter.next().unwrap(); let (_, cur_char) = iter.next().unwrap();
let (next_pos, _) = iter.next().unwrap_or((1, ' ')); let (next_pos, _) = iter.next().unwrap_or((1, ' '));
self.pos += next_pos; self.pos += next_pos;
return cur_char; cur_char
} }
fn consume_whitespace(&mut self) { fn consume_whitespace(&mut self) {
@ -60,14 +60,14 @@ impl Parser {
break; break;
} }
c => { c => {
if c.is_ascii_alphanumeric() == false { if !c.is_ascii_alphanumeric() {
break; break;
} }
selector.tag_name = Some(self.parse_identifier()); selector.tag_name = Some(self.parse_identifier());
} }
} }
} }
return selector; selector
} }
fn parse_identifier(&mut self) -> String { fn parse_identifier(&mut self) -> String {
@ -95,7 +95,7 @@ impl Parser {
c => panic!("Unexpected character {} in selector list", c), c => panic!("Unexpected character {} in selector list", c),
} }
} }
return selectors; selectors
} }
fn parse_declarations(&mut self) -> Vec<Declaration> { fn parse_declarations(&mut self) -> Vec<Declaration> {
@ -107,19 +107,16 @@ impl Parser {
self.consume_char(); self.consume_char();
break; break;
} }
let identifier = self.parse_identifier(); let name = self.parse_identifier();
self.consume_whitespace(); self.consume_whitespace();
assert!(self.consume_char() == ':'); assert!(self.consume_char() == ':');
self.consume_whitespace(); self.consume_whitespace();
let value = self.parse_declaration_value(); let value = self.parse_declaration_value();
result.push(Declaration { result.push(Declaration { name, value });
name: identifier,
value: value,
});
self.consume_whitespace(); self.consume_whitespace();
assert!(self.consume_char() == ';'); assert!(self.consume_char() == ';');
} }
return result; result
} }
fn parse_declaration_value(&mut self) -> Value { fn parse_declaration_value(&mut self) -> Value {
@ -138,7 +135,7 @@ impl Parser {
fn parse_color(&mut self) -> Value { fn parse_color(&mut self) -> Value {
assert_eq!(self.consume_char(), '#'); assert_eq!(self.consume_char(), '#');
Value::Color(ColorValue::RGBA( Value::Color(ColorValue::Rgba(
self.parse_hex_pair(), self.parse_hex_pair(),
self.parse_hex_pair(), self.parse_hex_pair(),
self.parse_hex_pair(), self.parse_hex_pair(),
@ -151,10 +148,7 @@ impl Parser {
} }
fn parse_float(&mut self) -> f32 { fn parse_float(&mut self) -> f32 {
let s = self.consume_while(|c| match c { let s = self.consume_while(|c| matches!(c, '0'..='9' | '.'));
'0'..='9' | '.' => true,
_ => false,
});
s.parse().unwrap() s.parse().unwrap()
} }
@ -176,10 +170,7 @@ impl Parser {
} }
pub fn parse(input: String) -> StyleSheet { pub fn parse(input: String) -> StyleSheet {
let mut parser = Parser { let mut parser = Parser { pos: 0, input };
pos: 0,
input: input,
};
StyleSheet { StyleSheet {
rules: parser.parse_rules(), rules: parser.parse_rules(),
} }
@ -204,7 +195,7 @@ impl fmt::Display for Selector {
if let Some(tag_name) = &selector.tag_name { if let Some(tag_name) = &selector.tag_name {
write!(f, "{}", tag_name).unwrap(); write!(f, "{}", tag_name).unwrap();
} }
if selector.classes.len() > 0 { if selector.classes.is_empty() {
write!(f, ".{}", selector.classes.join(".")).unwrap(); write!(f, ".{}", selector.classes.join(".")).unwrap();
} }
if let Some(id) = &selector.id { if let Some(id) = &selector.id {
@ -241,13 +232,13 @@ impl fmt::Display for Value {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
enum ColorValue { enum ColorValue {
RGBA(u8, u8, u8, u8), Rgba(u8, u8, u8, u8),
} }
impl fmt::Display for ColorValue { impl fmt::Display for ColorValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self { match &self {
Self::RGBA(r, g, b, a) => write!(f, "rgba({}, {}, {}, {})", r, g, b, a), Self::Rgba(r, g, b, a) => write!(f, "rgba({}, {}, {}, {})", r, g, b, a),
} }
} }
} }
@ -309,7 +300,7 @@ pub struct StyleSheet {
impl fmt::Display for StyleSheet { impl fmt::Display for StyleSheet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.rules.len() > 0 { if self.rules.is_empty() {
let rules = self let rules = self
.rules .rules
.iter() .iter()

View File

@ -22,7 +22,7 @@ impl fmt::Display for AttrMap {
.iter() .iter()
.map(|(key, value)| match &value { .map(|(key, value)| match &value {
AttrValue::Text(text) => format!("{}=\"{}\"", key, text), AttrValue::Text(text) => format!("{}=\"{}\"", key, text),
AttrValue::Implicit => format!("{}", key), AttrValue::Implicit => key.to_string(),
}) })
.collect::<Vec<String>>(); .collect::<Vec<String>>();
write!(f, "{}", i.join(" ")) write!(f, "{}", i.join(" "))
@ -38,10 +38,10 @@ pub struct ElementData {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum NodeType { pub enum NodeType {
ElementNode(ElementData), Element(ElementData),
TextNode(String), Text(String),
CommentNode(String), Comment(String),
DocumentNode(DocumentData), Document(DocumentData),
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -53,14 +53,14 @@ impl Node {
fn pretty_print(&self, f: &mut fmt::Formatter<'_>, indent: usize) { fn pretty_print(&self, f: &mut fmt::Formatter<'_>, indent: usize) {
let prepadding = " ".repeat(indent); let prepadding = " ".repeat(indent);
match &self.node_type { match &self.node_type {
NodeType::ElementNode(data) => { NodeType::Element(data) => {
write!(f, "{}<{}", prepadding, data.tag_name).unwrap(); write!(f, "{}<{}", prepadding, data.tag_name).unwrap();
if data.attributes.0.len() > 0 { if data.attributes.0.is_empty() {
write!(f, " {}", data.attributes).unwrap(); write!(f, " {}", data.attributes).unwrap();
} }
if data.child_nodes.len() == 0 { if data.child_nodes.is_empty() {
writeln!(f, "></{}>", data.tag_name).unwrap(); writeln!(f, "></{}>", data.tag_name).unwrap();
return; return;
} }
@ -74,11 +74,11 @@ impl Node {
writeln!(f, "{}</{}>", prepadding, data.tag_name).unwrap(); writeln!(f, "{}</{}>", prepadding, data.tag_name).unwrap();
} }
NodeType::TextNode(text) => { NodeType::Text(text) => {
writeln!(f, "{}{}", prepadding, text).unwrap(); writeln!(f, "{}{}", prepadding, text).unwrap();
} }
NodeType::CommentNode(text) => writeln!(f, "{}<!-- {} -->", prepadding, text).unwrap(), NodeType::Comment(text) => writeln!(f, "{}<!-- {} -->", prepadding, text).unwrap(),
NodeType::DocumentNode(_) => {} NodeType::Document(_) => {}
} }
} }
} }
@ -116,13 +116,13 @@ impl DocumentData {
pub fn text(data: String) -> Node { pub fn text(data: String) -> Node {
Node { Node {
node_type: NodeType::TextNode(data), node_type: NodeType::Text(data),
} }
} }
pub fn element(name: String, attrs: AttrMap, children: Vec<Node>) -> Node { pub fn element(name: String, attrs: AttrMap, children: Vec<Node>) -> Node {
Node { Node {
node_type: NodeType::ElementNode(ElementData { node_type: NodeType::Element(ElementData {
tag_name: name, tag_name: name,
attributes: attrs, attributes: attrs,
child_nodes: children, child_nodes: children,
@ -132,7 +132,7 @@ pub fn element(name: String, attrs: AttrMap, children: Vec<Node>) -> Node {
pub fn comment(text: String) -> Node { pub fn comment(text: String) -> Node {
Node { Node {
node_type: NodeType::CommentNode(text), node_type: NodeType::Comment(text),
} }
} }
@ -140,6 +140,6 @@ pub fn parse(document: String) -> Node {
let mut context = DocumentData::new(); let mut context = DocumentData::new();
context.load_document(document); context.load_document(document);
Node { Node {
node_type: NodeType::DocumentNode(context), node_type: NodeType::Document(context),
} }
} }

View File

@ -27,7 +27,7 @@ impl Parser<'_> {
let (_, cur_char) = iter.next().unwrap(); let (_, cur_char) = iter.next().unwrap();
let (next_pos, _) = iter.next().unwrap_or((1, ' ')); let (next_pos, _) = iter.next().unwrap_or((1, ' '));
self.pos += next_pos; self.pos += next_pos;
return cur_char; cur_char
} }
fn consume_while<F>(&mut self, test: F) -> String fn consume_while<F>(&mut self, test: F) -> String
@ -38,7 +38,7 @@ impl Parser<'_> {
while !self.eof() && test(self.next_char()) { while !self.eof() && test(self.next_char()) {
result.push(self.consume_char()); result.push(self.consume_char());
} }
return result; result
} }
fn consume_whitespace(&mut self) { fn consume_whitespace(&mut self) {
@ -83,7 +83,7 @@ impl Parser<'_> {
if tag_name == "style" { if tag_name == "style" {
let inner_node = children.first().unwrap(); let inner_node = children.first().unwrap();
if let NodeType::TextNode(styling) = &inner_node.node_type { if let NodeType::Text(styling) = &inner_node.node_type {
self.context.load_css(styling.clone()); self.context.load_css(styling.clone());
} }
} }
@ -94,7 +94,7 @@ impl Parser<'_> {
assert!(self.parse_tag_name() == tag_name); assert!(self.parse_tag_name() == tag_name);
assert!(self.consume_char() == '>'); assert!(self.consume_char() == '>');
return element(tag_name, attrs, children); element(tag_name, attrs, children)
} }
fn parse_comment(&mut self) -> Node { fn parse_comment(&mut self) -> Node {
@ -127,13 +127,13 @@ impl Parser<'_> {
} }
let (name, value) = self.parse_attr(); let (name, value) = self.parse_attr();
if value.len() > 0 { if value.is_empty() {
attributes.insert(name, AttrValue::Text(value)); attributes.insert(name, AttrValue::Text(value));
} else { } else {
attributes.insert(name, AttrValue::Implicit); attributes.insert(name, AttrValue::Implicit);
} }
} }
return AttrMap(attributes); AttrMap(attributes)
} }
fn parse_attr_value(&mut self) -> String { fn parse_attr_value(&mut self) -> String {
@ -141,7 +141,7 @@ impl Parser<'_> {
assert!(open_quote == '"' || open_quote == '\''); assert!(open_quote == '"' || open_quote == '\'');
let value = self.consume_while(|c| c != open_quote); let value = self.consume_while(|c| c != open_quote);
assert!(self.consume_char() == open_quote); assert!(self.consume_char() == open_quote);
return value; value
} }
fn parse_attr(&mut self) -> (String, String) { fn parse_attr(&mut self) -> (String, String) {
@ -151,7 +151,7 @@ impl Parser<'_> {
return (name, value); return (name, value);
} }
return (name, String::new()); (name, String::new())
} }
fn parse_nodes(&mut self) -> Vec<Node> { fn parse_nodes(&mut self) -> Vec<Node> {
@ -163,15 +163,15 @@ impl Parser<'_> {
} }
nodes.push(self.parse_node()); nodes.push(self.parse_node());
} }
return nodes; nodes
} }
} }
pub fn parse(source: String, context: &mut DocumentData) -> Node { pub fn parse(input: String, context: &mut DocumentData) -> Node {
let mut parser = Parser { let mut parser = Parser {
pos: 0, pos: 0,
input: source, input,
context: context, context,
}; };
let mut nodes = parser.parse_nodes(); let mut nodes = parser.parse_nodes();

View File

@ -1,19 +1,12 @@
use std::io; use std::{env, fs};
use dom::NodeType;
mod css; mod css;
mod dom; mod dom;
mod html; mod html;
fn main() { fn main() {
let mut input = String::new(); let file_path = env::args().nth(1).unwrap();
let stdin = io::stdin(); let contents = fs::read_to_string(file_path).unwrap();
stdin.read_line(&mut input).unwrap(); let node = dom::parse(contents);
// let input = "<html><head><title>Document</title><style>h1{font-size: 14px;}</style></head><body><h1>Hello</h1></body></html>".into(); println!("{:#?}", node);
let node = dom::parse(input);
if let NodeType::DocumentNode(data) = node.node_type {
println!("{}", data.stylesheets[0]);
}
} }