Adopt and apply nightly clippy configuration

This commit is contained in:
Juno Takano 2026-02-16 23:31:18 -03:00
commit 5b5541c28f
33 changed files with 233 additions and 139 deletions

View file

@ -69,7 +69,7 @@ alias f := format
# Lint
[group: 'develop']
lint:
cargo clippy
cargo +nightly clippy
alias l := lint
@ -94,9 +94,16 @@ rustc-fix:
alias rf := rustc-fix
# Apply clippy lint fixes
[group: 'develop']
clippy-fix:
cargo +nightly clippy --fix --allow-dirty
alias cf := clippy-fix
# Apply all automatic fixes
[group: 'develop']
fix: rustc-fix format
fix: rustc-fix clippy-fix format
alias x := fix
@ -169,8 +176,9 @@ alias fc := format-assess
# Assess production lints
[group: 'assess']
lint-assess:
cargo clippy -- \
-D clippy::dbg_macro -D clippy::print_stdout -D clippy::print_stderr \
cargo +nightly clippy -- \
-D clippy::dbg_macro -D clippy::use_debug \
-D clippy::print_stdout -D clippy::print_stderr \
-D clippy::todo -D clippy::unimplemented -D clippy::unreachable
alias la := lint-assess

View file

@ -34,101 +34,205 @@ let_underscore= { level = "warn", priority = 10 }
nonstandard-style = "warn"
future-incompatible = "warn"
keyword-idents = "warn"
non_ascii_idents = "warn"
[lints.clippy]
# levels: allow, warn, deny, forbid
manual_non_exhaustive = "allow"
collapsible_if = "allow"
collapsible_else_if = "allow"
field_reassign_with_default = "allow"
# pedantic
allow_attributes = "warn"
arithmetic_side_effects = "warn"
as_conversions = "warn"
as_pointer_underscore = "warn"
as_underscore = "warn"
assigning_clones = "warn"
borrow_as_ptr = "warn"
branches_sharing_code = "warn"
case_sensitive_file_extension_comparisons = "warn"
cast_lossless = "warn"
cast_possible_truncation = "warn"
cast_possible_wrap = "warn"
cast_ptr_alignment = "warn"
cast_precision_loss = "warn"
cast_sign_loss = "warn"
checked_conversions = "warn"
clear_with_drain = "warn"
cloned_instead_of_copied = "warn"
coerce_container_to_any = "warn"
collapsible_else_if = "allow"
collapsible_if = "allow"
collection_is_never_read = "warn"
comparison_chain = "warn"
copy_iterator = "warn"
default_trait_access = "warn"
deref_by_slicing = "warn"
derive_partial_eq_without_eq = "warn"
doc_broken_link = "warn"
doc_comment_double_space_linebreaks = "warn"
doc_include_without_cfg = "warn"
doc_link_code = "warn"
doc_link_with_quotes = "warn"
doc_markdown = "warn"
doc_paragraphs_missing_punctuation = "warn"
duration_suboptimal_units = "warn"
empty_drop = "warn"
empty_enum_variants_with_brackets = "warn"
empty_enums = "warn"
empty_structs_with_brackets = "warn"
equatable_if_let = "warn"
error_impl_error = "warn"
exit = "warn"
expect_used = "warn"
expl_impl_clone_on_copy = "warn"
explicit_deref_methods = "warn"
explicit_into_iter_loop = "warn"
explicit_iter_loop = "warn"
fallible_impl_from = "warn"
field_reassign_with_default = "allow"
filetype_is_file = "warn"
filter_map_next = "warn"
flat_map_option = "warn"
float_cmp = "warn"
float_cmp_const = "warn"
fn_to_numeric_cast_any = "warn"
format_collect = "warn"
format_push_string = "warn"
from_iter_instead_of_collect = "warn"
get_unwrap = "warn"
if_not_else = "warn"
if_then_some_else_none = "warn"
ignore_without_reason = "warn"
ignored_unit_patterns = "warn"
implicit_clone = "warn"
implicit_hasher = "warn"
imprecise_flops = "warn"
inconsistent_struct_constructor = "warn"
index_refutable_slice = "warn"
indexing_slicing = "warn"
inefficient_to_string = "warn"
infinite_loop = "warn"
integer_division = "warn"
integer_division_remainder_used = "warn"
into_iter_without_iter = "warn"
invalid_upcast_comparisons = "warn"
ip_constant = "warn"
iter_filter_is_ok = "warn"
iter_filter_is_some = "warn"
iter_not_returning_iterator = "warn"
iter_on_empty_collections = "warn"
iter_on_single_items = "warn"
iter_with_drain = "warn"
iter_without_into_iter = "warn"
large_digit_groups = "warn"
large_futures = "warn"
large_stack_arrays = "warn"
large_types_passed_by_value = "warn"
let_underscore_must_use = "warn"
linkedlist = "warn"
literal_string_with_formatting_args = "warn"
lossy_float_literal = "warn"
macro_use_imports = "warn"
manual_assert = "warn"
manual_ilog2 = "warn"
manual_instant_elapsed = "warn"
manual_is_power_of_two = "warn"
manual_is_variant_and = "warn"
manual_let_else = "warn"
manual_midpoint = "warn"
manual_non_exhaustive = "allow"
manual_string_new = "warn"
many_single_char_names = "warn"
map_unwrap_or = "warn"
map_err_ignore = "warn"
map_with_unused_argument_over_ranges = "warn"
match_bool = "warn"
match_same_arms = "warn"
match_wild_err_arm = "warn"
match_wildcard_for_single_variants = "warn"
maybe_infinite_iter = "warn"
mem_forget = "warn"
mismatching_type_param_order = "warn"
missing_assert_message = "warn"
missing_asserts_for_indexing = "warn"
missing_const_for_fn = "warn"
missing_errors_doc = "warn"
missing_fields_in_debug = "warn"
missing_panics_doc = "warn"
mixed_read_write_in_expression = "warn"
mod_module_files = "warn"
module_name_repetitions = "warn"
multiple_inherent_impl = "warn"
mut_mut = "warn"
mutex_atomic = "warn"
mutex_integer = "warn"
naive_bytecount = "warn"
needless_collect = "warn"
needless_continue = "warn"
needless_for_each = "warn"
needless_pass_by_ref_mut = "warn"
needless_pass_by_value = "warn"
needless_raw_string_hashes = "warn"
needless_raw_strings = "warn"
needless_type_cast = "warn"
no_effect_underscore_binding = "warn"
non_send_fields_in_send_ty = "warn"
non_std_lazy_statics = "warn"
non_zero_suggestions = "warn"
nonstandard_macro_braces = "warn"
option_as_ref_cloned = "warn"
option_option = "warn"
ptr_as_ptr = "warn"
ptr_cast_constness = "warn"
panic_in_result_fn = "warn"
path_buf_push_overwrite = "warn"
pathbuf_init_then_push = "warn"
pub_underscore_fields = "warn"
pub_without_shorthand = "warn"
range_minus_one = "warn"
range_plus_one = "warn"
rc_buffer = "warn"
rc_mutex = "warn"
read_zero_byte_vec = "warn"
redundant_clone = "warn"
redundant_closure_for_method_calls = "warn"
ref_as_ptr = "warn"
redundant_pub_crate = "warn"
redundant_test_prefix = "warn"
redundant_type_annotations = "warn"
ref_binding_to_reference = "warn"
ref_option = "warn"
ref_option_ref = "warn"
renamed_function_params = "warn"
rest_pat_in_fully_bound_structs = "warn"
return_and_then = "warn"
return_self_not_must_use = "warn"
same_functions_in_if_condition = "warn"
same_length_and_capacity = "warn"
same_name_method = "warn"
search_is_some = "warn"
self_only_used_in_recursion = "warn"
semicolon_if_nothing_returned = "warn"
semicolon_inside_block = "warn"
set_contains_or_insert = "warn"
shadow_reuse = "warn"
shadow_same = "warn"
shadow_unrelated = "warn"
should_panic_without_expect = "warn"
similar_names = "warn"
single_char_pattern = "warn"
single_match_else = "warn"
single_option_map = "warn"
stable_sort_primitive = "warn"
str_split_at_newline = "warn"
string_add = "warn"
string_add_assign = "warn"
string_lit_as_bytes = "warn"
string_lit_chars_any = "warn"
string_slice = "warn"
struct_field_names = "warn"
suboptimal_flops = "warn"
suspicious_operation_groupings = "warn"
suspicious_xor_used_as_pow = "warn"
tests_outside_test_module = "warn"
too_long_first_doc_paragraph = "warn"
trait_duplication_in_bounds = "warn"
trivially_copy_pass_by_ref = "warn"
try_err = "warn"
tuple_array_conversions = "warn"
type_repetition_in_bounds = "warn"
unchecked_time_subtraction = "warn"
unicode_not_nfc = "warn"
uninlined_format_args = "warn"
@ -136,72 +240,34 @@ unnecessary_box_returns = "warn"
unnecessary_debug_formatting = "warn"
unnecessary_join = "warn"
unnecessary_literal_bound = "warn"
unnecessary_self_imports = "warn"
unnecessary_semicolon = "warn"
unnecessary_struct_initialization = "warn"
unnecessary_wraps = "warn"
unneeded_field_pattern = "warn"
unnested_or_patterns = "warn"
unreadable_literal = "warn"
unsafe_derive_deserialize = "warn"
unseparated_literal_suffix = "warn"
unused_async = "warn"
unused_peekable = "warn"
unused_result_ok = "warn"
unused_rounding = "warn"
unused_self = "warn"
unused_trait_names = "warn"
unwrap_in_result = "warn"
unwrap_used = "warn"
used_underscore_binding = "warn"
used_underscore_items = "warn"
useless_let_if_seq = "warn"
verbose_file_reads = "warn"
volatile_composites = "warn"
wildcard_enum_match_arm = "warn"
wildcard_imports = "warn"
zero_sized_map_values = "warn"
# restrictive
arithmetic_side_effects = "warn"
as_conversions = "warn"
as_pointer_underscore = "warn"
as_underscore = "warn"
deref_by_slicing = "warn"
empty_drop = "warn"
empty_enum_variants_with_brackets = "warn"
error_impl_error = "warn"
exit = "warn"
expect_used = "warn"
filetype_is_file = "warn"
float_cmp_const = "warn"
fn_to_numeric_cast_any = "warn"
if_then_some_else_none = "warn"
indexing_slicing = "warn"
infinite_loop = "warn"
integer_division = "warn"
integer_division_remainder_used = "warn"
let_underscore_must_use = "warn"
let_underscore_untyped = "warn"
lossy_float_literal = "warn"
map_err_ignore = "warn"
map_with_unused_argument_over_ranges = "warn"
missing_assert_message = "warn"
missing_asserts_for_indexing = "warn"
mixed_read_write_in_expression = "warn"
module_name_repetitions = "warn"
multiple_inherent_impl = "warn"
needless_raw_strings = "warn"
non_zero_suggestions = "warn"
panic_in_result_fn = "warn"
pathbuf_init_then_push = "warn"
pub_without_shorthand = "warn"
redundant_test_prefix = "warn"
redundant_type_annotations = "warn"
renamed_function_params = "warn"
rest_pat_in_fully_bound_structs = "warn"
return_and_then = "warn"
same_name_method = "warn"
semicolon_outside_block = "warn"
shadow_reuse = "warn"
shadow_same = "warn"
shadow_unrelated = "warn"
string_add = "warn"
string_lit_chars_any = "warn"
unnecessary_self_imports = "warn"
unneeded_field_pattern = "warn"
unseparated_literal_suffix = "warn"
unused_result_ok = "warn"
unused_trait_names = "warn"
unwrap_used = "warn"
verbose_file_reads = "warn"
wildcard_enum_match_arm = "warn"
# cargo
negative_feature_names = "warn"
redundant_feature_names = "warn"
multiple_crate_versions = "warn"
wildcard_dependencies = "warn"

View file

@ -78,7 +78,7 @@ impl Graph {
}
}
/// Takes a file path to a TOML file and returns a modulated Graph
/// Takes a file path to a TOML file and returns a modulated Graph.
///
/// If `path` is None, it will fallback to CLI arguments or their defaults.
///
@ -99,11 +99,18 @@ impl Graph {
let cli_path = Arguments::default().parse().graph_path;
let path = in_path.map_or(cli_path, PathBuf::from);
let toml_source = match std::fs::read_to_string(path) {
let toml_source = match std::fs::read_to_string(&path) {
Ok(s) => s,
Err(e) => {
log!(ERROR, "Failed reading {e}");
return Err("Failed reading file at {path}".to_string());
log!(
ERROR,
"Error reading path {}: {e}",
path.as_path().display(),
);
return Err(format!(
"Failed reading file at {}",
path.as_path().display(),
));
},
};
@ -192,7 +199,7 @@ impl Graph {
tlog!(&instant, "Parsed configuration");
}
/// Construct a `HashMap` with incoming connections (reversed edges)
/// Construct a `HashMap` with incoming connections (reversed edges).
fn map_incoming(&mut self) {
for node in self.nodes.clone().into_values() {
for edge in node.connections.clone().values() {
@ -372,7 +379,7 @@ impl Graph {
}
}
/// Increments detached node statistics for the given node ID
/// Increments detached node statistics for the given node ID.
///
/// Performs checked arithmetic to the following effect:
/// - Stats will saturate at `u32::MAX`
@ -392,7 +399,7 @@ impl Graph {
}
pub fn find_node(&self, query: &str) -> QueryResult {
let collapsed_query = query.trim().replace(" ", "");
let collapsed_query = query.trim().replace(' ', "");
if query == collapsed_query {
log!(VERBOSE, "Chasing candidate for query {query}");

View file

@ -105,9 +105,9 @@ impl Default for Config {
}
// See: https://github.com/serde-rs/serde/issues/368
fn mktrue() -> bool { true }
fn mkfalse() -> bool { false }
fn mk8() -> u16 { 8 }
const fn mktrue() -> bool { true }
const fn mkfalse() -> bool { false }
const fn mk8() -> u16 { 8 }
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub struct Version {
@ -148,7 +148,7 @@ impl Version {
Version::from_text(env!("CARGO_PKG_VERSION"))
}
/// Parses a string into a Version struct
/// Parses a string into a Version struct.
///
/// It is expected for the version string to contain exactly three
/// dot-separated numeric values with an optional leading `v` character.

View file

@ -4,7 +4,7 @@ pub mod prelude {
pub use crate::{
log,
log::{Level::*, now},
tlog,
tlog, write_log,
};
}

View file

@ -4,7 +4,7 @@ pub use level::*;
mod level;
/// Strings in this slice suppress logging if found in the stack trace
/// Strings in this slice suppress logging if found in the stack trace.
pub const EXCLUSIONS: &[&str] = &["en::graph::Graph::parse_config"];
#[derive(Debug)]
@ -46,7 +46,7 @@ impl Data {
&& !excluded_by_env
&& matches_filter;
#[allow(clippy::print_stderr)]
#[expect(clippy::print_stderr)]
if env_level == Level::META {
eprintln!(
"Log decision for message from {path}: {should_log} given\n\
@ -79,7 +79,7 @@ pub fn env_level() -> Level {
}
}
#[allow(clippy::print_stderr)]
#[expect(clippy::print_stderr)]
pub fn print_state() {
let env_level = env_level();
let version = env!("CARGO_PKG_VERSION");
@ -90,7 +90,7 @@ pub fn print_state() {
}
}
#[allow(clippy::print_stderr)]
#[expect(clippy::print_stderr)]
pub fn timed(past: &Instant, message: &str) -> Instant {
let now = Instant::now();
let env_level = env_level();
@ -120,7 +120,7 @@ macro_rules! tlog {
pub fn now() -> Instant { Instant::now() }
#[allow(clippy::print_stderr)]
#[expect(clippy::print_stderr, clippy::use_debug)]
pub fn elog(function: &str, message: &str) {
eprintln!("{:?} [{function}] {message}", crate::ONSET.elapsed());
}
@ -214,6 +214,17 @@ pub fn wrap(s: &str) -> String {
symbolize(&quote(&escape(s)))
}
#[macro_export]
macro_rules! write_log {
($buffer:expr, $format_string:expr $(, $format_args:expr)* $(,)?) => {{
use std::fmt::Write as _;
let result = write!($buffer, $format_string $(, $format_args)*);
if let Err(error) = result {
log!(ERROR, "Unexpected error writing into {}: ${error}", $buffer);
}
}};
}
#[cfg(test)]
mod tests {
use super::*;
@ -239,7 +250,7 @@ mod tests {
}
fn run_in_debug_level(level: &str) {
#[allow(unsafe_code)]
#[expect(unsafe_code)]
unsafe {
std::env::set_var("DEBUG", level);
log!("Debug is set to {level}");

View file

@ -3,7 +3,7 @@ use std::{backtrace, io, panic};
use en::{ONSET, graph::Graph, log, prelude::*, syntax};
#[tokio::main]
#[allow(clippy::print_stderr, clippy::print_stdout)]
#[expect(clippy::print_stderr, clippy::print_stdout, clippy::use_debug)]
async fn main() -> io::Result<()> {
log::print_state();
let mut instant = now();

View file

@ -37,13 +37,10 @@ pub async fn node(
"node",
&context,
if found { 500 } else { 404 },
Some(
format!(
"Failed to generate page for node {} (ID {}).",
node.title, id
)
.to_owned(),
),
Some(format!(
"Failed to generate page for node {} (ID {}).",
node.title, id
)),
!found,
)
}

View file

@ -33,7 +33,7 @@ pub async fn data(State(state): State<GlobalState>) -> Response<Body> {
let mut detached_pairs: Vec<(String, u32)> =
state.graph.stats.detached.clone().into_iter().collect();
detached_pairs.sort_by(|a, b| b.1.cmp(&a.1));
detached_pairs.sort_by_key(|b| std::cmp::Reverse(b.1));
let mut context = tera::Context::default();
context.insert("graph", &state.graph);

View file

@ -8,7 +8,7 @@ use crate::{
router::{GlobalState, handlers::raw::make_response},
};
/// Assembles a response containing the graph as its only context
/// Assembles a response containing the graph as its only context.
///
/// The template name **must not** contain the extension.
#[expect(clippy::unused_async)]
@ -38,7 +38,7 @@ pub(in crate::router::handlers) fn with_context(
make_response(&body, status_code, &[(header::CONTENT_TYPE, "text/html")])
}
/// Renderes a template into a String and error code
/// Renderes a template into a String and error code.
///
/// The template name **must not** contain the extension (e.g. `.html`).
pub(in crate::router::handlers) fn render(

View file

@ -7,7 +7,7 @@ use crate::prelude::*;
static FIRST_PARSE: AtomicBool = AtomicBool::new(true);
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Arguments {
pub hostname: String,
pub port: u16,

View file

@ -33,7 +33,7 @@ pub(super) fn rich_read(input: &str, graph: &Graph) -> TokenOutput {
}
/// Apply end-to-end point and inline parsing for nested formatting, such as
/// inside the display text of anchors and list items
/// inside the display text of anchors and list items.
pub fn format(input: &str, graph: &Graph) -> (String, Vec<Token>) {
let tokens = lex(input, LEXMAP, graph, false).tokens;
(parse(&tokens), tokens)

View file

@ -61,7 +61,7 @@ pub fn parse(
&& !lexeme.match_next_char('|')
{
log!(VERBOSE, "End: Plural anchor");
candidate.set_destination(Some(&candidate.text().clone()));
candidate.set_destination(Some(&candidate.text()));
candidate.text_push("s");
if lexeme.last() {
push(None, tokens, state, graph);
@ -73,7 +73,7 @@ pub fn parse(
if candidate.text().contains(':') {
candidate.set_external(true);
}
push(Some(&candidate.text().clone()), tokens, state, graph);
push(Some(&candidate.text()), tokens, state, graph);
} else {
push(Some(&buffer.destination.clone()), tokens, state, graph);
}

View file

@ -112,7 +112,7 @@ pub fn parse(
iterator.next();
return true;
} else if lexeme.match_char('\n') {
tokens.push(Token::LineBreak(LineBreak::default()));
tokens.push(Token::LineBreak(LineBreak));
return true;
}
},

View file

@ -48,11 +48,10 @@ pub fn parse(
log!(VERBOSE, "Inline Context: Code -> None on {lexeme}");
state.context.inline = Inline::None;
tokens.push(Token::Code(Code::new(false)));
return true;
} else {
tokens.push(Token::Literal(Literal::lex(lexeme)));
return true;
}
return true;
},
Inline::Anchor => {
if context::anchor::parse(lexeme, state, tokens, graph) {

View file

@ -30,7 +30,7 @@ pub fn parse(
let candidate = &mut buffer.candidate;
let item_candidate = &mut buffer.item_candidate;
#[allow(clippy::wildcard_enum_match_arm)]
#[expect(clippy::wildcard_enum_match_arm)]
match state.context.block {
Block::List => {
if lexeme.match_char(' ') && item_candidate.depth.is_none() {

View file

@ -26,7 +26,7 @@ pub fn parse(
let buffer = &mut state.buffers.quote;
let candidate = &mut buffer.candidate;
#[allow(clippy::wildcard_enum_match_arm)]
#[expect(clippy::wildcard_enum_match_arm)]
match state.context.block {
Block::Quote => {
if Quote::probe_end(lexeme) {

View file

@ -32,7 +32,7 @@ pub fn parse(
parsed_text
};
#[allow(clippy::wildcard_enum_match_arm)]
#[expect(clippy::wildcard_enum_match_arm)]
match state.context.block {
Block::Table => {
if Table::probe_end(lexeme) {

View file

@ -26,9 +26,9 @@ impl Lexeme {
pub fn next(&self) -> String { self.next.clone() }
pub fn last(&self) -> bool { self.last }
pub const fn last(&self) -> bool { self.last }
pub fn first(&self) -> bool { self.first }
pub const fn first(&self) -> bool { self.first }
pub fn mutate_text(&mut self, new: &str) { self.text = new.to_string(); }
@ -146,7 +146,7 @@ impl Lexeme {
}
/// # Panics
/// Panics if number of chars for a single lexeme exceeds `i32::MAX`
/// Panics if number of chars for a single lexeme exceeds `i32::MAX`.
pub fn count_char(&self, c: char) -> i32 {
let count = self.text().chars().filter(|&n| n == c).count();
match i32::try_from(count) {

View file

@ -17,9 +17,9 @@ pub fn parse(
tokens: &mut Vec<Token>,
iterator: &mut Peekable<Iter<'_, Lexeme>>,
) -> bool {
if let super::context::Block::PreFormat = state.context.block {
return false;
} else if let super::context::Inline::Code = state.context.inline {
if matches!(state.context.block, super::context::Block::PreFormat)
|| matches!(state.context.inline, super::context::Inline::Code)
{
return false;
}

View file

@ -28,15 +28,21 @@ impl Anchor {
self.route();
}
pub fn balanced(&self) -> bool { self.balanced }
pub const fn balanced(&self) -> bool { self.balanced }
pub fn set_balanced(&mut self, balanced: bool) { self.balanced = balanced; }
pub const fn set_balanced(&mut self, balanced: bool) {
self.balanced = balanced;
}
pub fn external(&self) -> bool { self.external }
pub const fn external(&self) -> bool { self.external }
pub fn set_external(&mut self, external: bool) { self.external = external; }
pub const fn set_external(&mut self, external: bool) {
self.external = external;
}
pub fn set_leading(&mut self, leading: bool) { self.leading = leading; }
pub const fn set_leading(&mut self, leading: bool) {
self.leading = leading;
}
pub fn node(&self) -> Option<Node> { self.node.clone() }
@ -52,7 +58,7 @@ impl Anchor {
fn route(&mut self) {
self.destination = if let Some(destination) = self.destination.clone() {
if destination.contains(":") || destination.contains("/") {
if destination.contains(':') || destination.contains('/') {
Some(destination)
} else if destination.is_empty() && self.text.is_empty() {
None

View file

@ -6,7 +6,7 @@ pub struct Bold {
}
impl Bold {
pub fn new(open: bool) -> Bold { Bold { open } }
pub const fn new(open: bool) -> Bold { Bold { open } }
}
impl Parseable for Bold {

View file

@ -6,7 +6,7 @@ pub struct CheckBox {
}
impl CheckBox {
pub fn new(checked: bool) -> CheckBox { CheckBox { checked } }
pub const fn new(checked: bool) -> CheckBox { CheckBox { checked } }
}
impl Parseable for CheckBox {

View file

@ -6,7 +6,7 @@ pub struct Code {
}
impl Code {
pub fn new(open: bool) -> Code { Code { open } }
pub const fn new(open: bool) -> Code { Code { open } }
}
impl Parseable for Code {

View file

@ -32,7 +32,7 @@ impl Header {
) -> String {
let base_id = if !config.ascii_dom_ids || next_lexeme.next().is_ascii()
{
next_lexeme.next().clone()
next_lexeme.next()
} else {
String::from("h")
};
@ -60,7 +60,7 @@ impl Header {
}
}
pub fn level(&self) -> u8 {
pub const fn level(&self) -> u8 {
match self.level {
Level::One => 1,
Level::Two => 2,
@ -147,7 +147,7 @@ pub enum Level {
}
impl Level {
fn from_u8(u: u8) -> Level {
const fn from_u8(u: u8) -> Level {
if u <= 1 {
Level::One
} else if u == 2 {

View file

@ -1,7 +1,7 @@
use crate::syntax::content::{Parseable, parser::Lexeme};
#[derive(Default, Debug, Clone, Eq, PartialEq)]
pub struct LineBreak {}
pub struct LineBreak;
impl Parseable for LineBreak {
fn probe(lexeme: &Lexeme) -> bool {

View file

@ -43,19 +43,19 @@ impl Parseable for List {
.unwrap_or(0)
.strict_div(scale);
output.push_str(&format!("<li>{}", item.text));
write_log!(output, "<li>{}", item.text);
if next_level > level {
// open nested lists
for _ in 0..(next_level.saturating_sub(level)) {
output.push_str(&format!("<{tag}>\n"));
write_log!(output, "<{tag}>\n");
}
} else {
// close current item
output.push_str("</li>");
// close nested lists
for _ in 0..(level.saturating_sub(next_level)) {
output.push_str(&format!("</{tag}></li>"));
write_log!(output, "</{tag}></li>");
}
output.push('\n');
}
@ -70,7 +70,7 @@ impl Parseable for List {
}
impl List {
pub fn new(ordered: bool) -> List {
pub const fn new(ordered: bool) -> List {
List {
ordered,
items: vec![],
@ -202,7 +202,7 @@ mod tests {
fn token_display() {
let list = List::new(false);
assert_eq!(
format!("{}", Token::List(list.clone())),
format!("{}", Token::List(list)),
"Tk:List [0 unordered items]"
);
}

View file

@ -6,7 +6,7 @@ pub struct Oblique {
}
impl Oblique {
pub fn new(open: bool) -> Oblique { Oblique { open } }
pub const fn new(open: bool) -> Oblique { Oblique { open } }
}
impl Parseable for Oblique {

View file

@ -6,7 +6,7 @@ pub struct Paragraph {
}
impl Paragraph {
pub fn new(open: bool) -> Paragraph { Paragraph { open: Some(open) } }
pub const fn new(open: bool) -> Paragraph { Paragraph { open: Some(open) } }
pub fn probe_end(lexeme: &Lexeme) -> bool {
lexeme.match_char('\n') && lexeme.match_next_char('\n')

View file

@ -6,7 +6,7 @@ pub struct PreFormat {
}
impl PreFormat {
pub fn new(open: bool) -> PreFormat { PreFormat { open: Some(open) } }
pub const fn new(open: bool) -> PreFormat { PreFormat { open: Some(open) } }
}
impl std::fmt::Display for PreFormat {

View file

@ -6,7 +6,7 @@ pub struct Strike {
}
impl Strike {
pub fn new(open: bool) -> Strike { Strike { open } }
pub const fn new(open: bool) -> Strike { Strike { open } }
}
impl Parseable for Strike {

View file

@ -6,7 +6,7 @@ pub struct Underline {
}
impl Underline {
pub fn new(open: bool) -> Underline { Underline { open } }
pub const fn new(open: bool) -> Underline { Underline { open } }
}
impl Parseable for Underline {

View file

@ -7,7 +7,7 @@ pub struct Verse {
}
impl Verse {
pub fn new(open: bool) -> Verse {
pub const fn new(open: bool) -> Verse {
Verse {
open: Some(open),
citation: None,