Fix all clippy lint errors

This commit is contained in:
Keavon Chambers 2021-12-30 23:05:54 -08:00
parent d0dcc0e42f
commit 5b3cbb30fc
18 changed files with 123 additions and 140 deletions

View File

@ -3,6 +3,7 @@
"matklad.rust-analyzer", "matklad.rust-analyzer",
"dbaeumer.vscode-eslint", "dbaeumer.vscode-eslint",
"octref.vetur", "octref.vetur",
"formulahendry.auto-close-tag" "formulahendry.auto-close-tag",
"aaron-bond.better-comments"
] ]
} }

View File

@ -1,7 +1,7 @@
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
#[test] // #[test]
fn it_works() { // fn it_works() {
assert_eq!(2 + 2, 4); // assert_eq!(2 + 2, 4);
} // }
} }

View File

@ -7,6 +7,7 @@ pub use crate::tool::ToolMessageHandler;
use crate::global::GlobalMessageHandler; use crate::global::GlobalMessageHandler;
use std::collections::VecDeque; use std::collections::VecDeque;
#[derive(Debug, Default)]
pub struct Dispatcher { pub struct Dispatcher {
input_preprocessor: InputPreprocessor, input_preprocessor: InputPreprocessor,
input_mapper: InputMapper, input_mapper: InputMapper,
@ -30,6 +31,10 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
]; ];
impl Dispatcher { impl Dispatcher {
pub fn new() -> Self {
Self::default()
}
pub fn handle_message<T: Into<Message>>(&mut self, message: T) { pub fn handle_message<T: Into<Message>>(&mut self, message: T) {
self.messages.push_back(message.into()); self.messages.push_back(message.into());
@ -68,18 +73,6 @@ impl Dispatcher {
list list
} }
pub fn new() -> Dispatcher {
Dispatcher {
input_preprocessor: InputPreprocessor::default(),
global_message_handler: GlobalMessageHandler::new(),
input_mapper: InputMapper::default(),
documents_message_handler: DocumentsMessageHandler::default(),
tool_message_handler: ToolMessageHandler::default(),
messages: VecDeque::new(),
responses: vec![],
}
}
fn log_message(&self, message: &Message) { fn log_message(&self, message: &Message) {
use Message::*; use Message::*;
if log::max_level() == log::LevelFilter::Trace if log::max_level() == log::LevelFilter::Trace

View File

@ -1,7 +1,6 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::VecDeque; use std::collections::VecDeque;
use super::document_message_handler::CopyBufferEntry;
pub use super::layer_panel::*; pub use super::layer_panel::*;
use super::movement_handler::{MovementMessage, MovementMessageHandler}; use super::movement_handler::{MovementMessage, MovementMessageHandler};
use super::overlay_message_handler::OverlayMessageHandler; use super::overlay_message_handler::OverlayMessageHandler;
@ -187,7 +186,7 @@ impl DocumentMessageHandler {
} }
pub fn deserialize_document(serialized_content: &str) -> Result<Self, DocumentError> { pub fn deserialize_document(serialized_content: &str) -> Result<Self, DocumentError> {
log::info!("Deserialising: {:?}", serialized_content); log::info!("Deserializing: {:?}", serialized_content);
serde_json::from_str(serialized_content).map_err(|e| DocumentError::InvalidFile(e.to_string())) serde_json::from_str(serialized_content).map_err(|e| DocumentError::InvalidFile(e.to_string()))
} }
@ -210,8 +209,8 @@ impl DocumentMessageHandler {
pub fn is_unmodified_default(&self) -> bool { pub fn is_unmodified_default(&self) -> bool {
self.serialize_root().len() == Self::default().serialize_root().len() self.serialize_root().len() == Self::default().serialize_root().len()
&& self.document_undo_history.len() == 0 && self.document_undo_history.is_empty()
&& self.document_redo_history.len() == 0 && self.document_redo_history.is_empty()
&& self.name.starts_with(DEFAULT_DOCUMENT_NAME) && self.name.starts_with(DEFAULT_DOCUMENT_NAME)
} }
@ -437,7 +436,7 @@ impl DocumentMessageHandler {
Some((document, layer_data)) => { Some((document, layer_data)) => {
let document = std::mem::replace(&mut self.graphene_document, document); let document = std::mem::replace(&mut self.graphene_document, document);
let layer_data = std::mem::replace(&mut self.layer_data, layer_data); let layer_data = std::mem::replace(&mut self.layer_data, layer_data);
self.document_undo_history.push((document.clone(), layer_data.clone())); self.document_undo_history.push((document, layer_data));
Ok(()) Ok(())
} }
None => Err(EditorError::NoTransactionInProgress), None => Err(EditorError::NoTransactionInProgress),
@ -645,7 +644,7 @@ impl MessageHandler<DocumentMessage, &InputPreprocessor> for DocumentMessageHand
// Fill the selection range // Fill the selection range
self.layer_data self.layer_data
.iter() .iter()
.filter(|(target, _)| self.graphene_document.layer_is_between(&target, &selected, &self.layer_range_selection_reference)) .filter(|(target, _)| self.graphene_document.layer_is_between(target, &selected, &self.layer_range_selection_reference))
.for_each(|(layer_path, _)| { .for_each(|(layer_path, _)| {
paths.push(layer_path.clone()); paths.push(layer_path.clone());
}); });
@ -664,7 +663,7 @@ impl MessageHandler<DocumentMessage, &InputPreprocessor> for DocumentMessageHand
} }
// Don't create messages for empty operations // Don't create messages for empty operations
if paths.len() > 0 { if !paths.is_empty() {
// Add or set our selected layers // Add or set our selected layers
if ctrl { if ctrl {
responses.push_front(AddSelectedLayers(paths).into()); responses.push_front(AddSelectedLayers(paths).into());

View File

@ -249,7 +249,7 @@ impl MessageHandler<DocumentsMessage, &InputPreprocessor> for DocumentsMessageHa
.document_ids .document_ids
.iter() .iter()
.filter_map(|id| { .filter_map(|id| {
self.documents.get(&id).map(|doc| FrontendDocumentDetails { self.documents.get(id).map(|doc| FrontendDocumentDetails {
is_saved: doc.is_saved(), is_saved: doc.is_saved(),
id: *id, id: *id,
name: doc.name.clone(), name: doc.name.clone(),
@ -314,7 +314,7 @@ impl MessageHandler<DocumentsMessage, &InputPreprocessor> for DocumentsMessageHa
.document_ids .document_ids
.iter() .iter()
.filter_map(|id| { .filter_map(|id| {
self.documents.get(&id).map(|doc| FrontendDocumentDetails { self.documents.get(id).map(|doc| FrontendDocumentDetails {
is_saved: doc.is_saved(), is_saved: doc.is_saved(),
id: *id, id: *id,
name: doc.name.clone(), name: doc.name.clone(),
@ -356,7 +356,7 @@ impl MessageHandler<DocumentsMessage, &InputPreprocessor> for DocumentsMessageHa
self.copy_buffer[clipboard as usize].clear(); self.copy_buffer[clipboard as usize].clear();
for path in paths { for path in paths {
let document = self.active_document(); let document = self.active_document();
match (document.graphene_document.layer(&path).map(|t| t.clone()), document.layer_data(&path).clone()) { match (document.graphene_document.layer(&path).map(|t| t.clone()), *document.layer_data(&path)) {
(Ok(layer), layer_data) => { (Ok(layer), layer_data) => {
self.copy_buffer[clipboard as usize].push(CopyBufferEntry { layer, layer_data }); self.copy_buffer[clipboard as usize].push(CopyBufferEntry { layer, layer_data });
} }

View File

@ -30,8 +30,8 @@ pub struct OverlayMessageHandler {
} }
impl MessageHandler<OverlayMessage, (&mut LayerData, &Document, &InputPreprocessor)> for OverlayMessageHandler { impl MessageHandler<OverlayMessage, (&mut LayerData, &Document, &InputPreprocessor)> for OverlayMessageHandler {
fn process_action(&mut self, message: OverlayMessage, data: (&mut LayerData, &Document, &InputPreprocessor), responses: &mut VecDeque<Message>) { fn process_action(&mut self, message: OverlayMessage, _data: (&mut LayerData, &Document, &InputPreprocessor), responses: &mut VecDeque<Message>) {
let (layer_data, document, ipp) = data; // let (layer_data, document, ipp) = data;
use OverlayMessage::*; use OverlayMessage::*;
match message { match message {
DispatchOperation(operation) => match self.overlays_graphene_document.handle_operation(&operation) { DispatchOperation(operation) => match self.overlays_graphene_document.handle_operation(&operation) {

View File

@ -13,12 +13,6 @@ pub enum GlobalMessage {
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct GlobalMessageHandler {} pub struct GlobalMessageHandler {}
impl GlobalMessageHandler {
pub fn new() -> Self {
Self::default()
}
}
impl MessageHandler<GlobalMessage, ()> for GlobalMessageHandler { impl MessageHandler<GlobalMessage, ()> for GlobalMessageHandler {
fn process_action(&mut self, message: GlobalMessage, _data: (), _responses: &mut VecDeque<Message>) { fn process_action(&mut self, message: GlobalMessage, _data: (), _responses: &mut VecDeque<Message>) {
use GlobalMessage::*; use GlobalMessage::*;

View File

@ -197,7 +197,7 @@ macro_rules! bit_ops {
macro_rules! bit_ops_assign { macro_rules! bit_ops_assign {
($(($op:ident, $func:ident)),* $(,)?) => { ($(($op:ident, $func:ident)),* $(,)?) => {
$(impl<const LENGTH: usize> $op for BitVector<LENGTH> { $(impl<const LENGTH: usize> $op for BitVector<LENGTH> {
fn $func(&mut self, right: Self) { fn $func(&mut self, right: Self) {
for (left, right) in self.0.iter_mut().zip(right.0.iter()) { for (left, right) in self.0.iter_mut().zip(right.0.iter()) {
$op::$func(left, right); $op::$func(left, right);
} }

View File

@ -31,6 +31,7 @@ impl ViewportBounds {
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Hash, Serialize, Deserialize)] #[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct ScrollDelta { pub struct ScrollDelta {
// TODO: Switch these to `f64` values (not trivial because floats don't provide PartialEq, Eq, and Hash)
pub x: i32, pub x: i32,
pub y: i32, pub y: i32,
pub z: i32, pub z: i32,

View File

@ -58,13 +58,11 @@ impl SnapHandler {
.unwrap_or(0.), .unwrap_or(0.),
); );
// Do not move if over snap tolerance // Clamp, do not move if over snap tolerance
let clamped_closest_move = DVec2::new( DVec2::new(
if closest_move.x.abs() > SNAP_TOLERANCE { 0. } else { closest_move.x }, if closest_move.x.abs() > SNAP_TOLERANCE { 0. } else { closest_move.x },
if closest_move.y.abs() > SNAP_TOLERANCE { 0. } else { closest_move.y }, if closest_move.y.abs() > SNAP_TOLERANCE { 0. } else { closest_move.y },
); )
clamped_closest_move
} else { } else {
DVec2::ZERO DVec2::ZERO
} }

View File

@ -42,7 +42,7 @@ impl<'a> MessageHandler<ToolMessage, ToolActionHandlerData<'a>> for Line {
fn actions(&self) -> ActionList { fn actions(&self) -> ActionList {
use LineToolFsmState::*; use LineToolFsmState::*;
match self.fsm_state { match self.fsm_state {
Ready => actions!(LineMessageDiscriminant; DragStart), Ready => actions!(LineMessageDiscriminant; DragStart),
Drawing => actions!(LineMessageDiscriminant; DragStop, Redraw, Abort), Drawing => actions!(LineMessageDiscriminant; DragStop, Redraw, Abort),
} }
} }

View File

@ -303,7 +303,7 @@ impl Fsm for PathToolFsmState {
} }
} }
fn calculate_total_overlays_per_type(shapes_to_draw: &Vec<VectorManipulatorShape>) -> (usize, usize, usize) { fn calculate_total_overlays_per_type(shapes_to_draw: &[VectorManipulatorShape]) -> (usize, usize, usize) {
let (mut total_anchors, mut total_handles, mut total_anchor_handle_lines) = (0, 0, 0); let (mut total_anchors, mut total_handles, mut total_anchor_handle_lines) = (0, 0, 0);
for shape_to_draw in shapes_to_draw { for shape_to_draw in shapes_to_draw {

View File

@ -114,7 +114,7 @@ import { defineComponent, PropType } from "vue";
const lerp = (x: number, y: number, a: number) => x * (1 - a) + y * a; const lerp = (x: number, y: number, a: number) => x * (1 - a) + y * a;
// Convert the position of the handle (0-1) to the position on the track (0-1). // Convert the position of the handle (0-1) to the position on the track (0-1).
// This includes the 1/2 handle length gap of the possible handle positionson each side so the end of the handle doesn't go off the track. // This includes the 1/2 handle length gap of the possible handle positionson each side so the end of the handle doesn't go off the track.
const handleToTrack = (handleLen: number, handlePos: number) => lerp(handleLen / 2, 1 - handleLen / 2, handlePos); const handleToTrack = (handleLen: number, handlePos: number) => lerp(handleLen / 2, 1 - handleLen / 2, handlePos);
const pointerPosition = (direction: ScrollbarDirection, e: PointerEvent) => (direction === ScrollbarDirection.Vertical ? e.clientY : e.clientX); const pointerPosition = (direction: ScrollbarDirection, e: PointerEvent) => (direction === ScrollbarDirection.Vertical ? e.clientY : e.clientX);

View File

@ -32,6 +32,7 @@ pub struct JsEditorHandle {
} }
#[wasm_bindgen] #[wasm_bindgen]
#[allow(clippy::too_many_arguments)]
impl JsEditorHandle { impl JsEditorHandle {
#[wasm_bindgen(constructor)] #[wasm_bindgen(constructor)]
pub fn new(handle_response: js_sys::Function) -> Self { pub fn new(handle_response: js_sys::Function) -> Self {

View File

@ -4,7 +4,7 @@ use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser); wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test] // #[wasm_bindgen_test]
fn pass() { // fn pass() {
assert_eq!(1 + 1, 2); // assert_eq!(1 + 1, 2);
} // }

View File

@ -1,7 +1,7 @@
use crate::color::Color; use crate::color::Color;
// Document // Document
pub const GRAPHENE_DOCUMENT_VERSION: &'static str = "0.0.1"; pub const GRAPHENE_DOCUMENT_VERSION: &str = "0.0.1";
// RENDERING // RENDERING
pub const LAYER_OUTLINE_STROKE_COLOR: Color = Color::BLACK; pub const LAYER_OUTLINE_STROKE_COLOR: Color = Color::BLACK;

View File

@ -115,7 +115,7 @@ impl Document {
// Determines which layer is closer to the root, if path_a return true, if path_b return false // Determines which layer is closer to the root, if path_a return true, if path_b return false
// Answers the question: Is A closer to the root than B? // Answers the question: Is A closer to the root than B?
pub fn layer_closer_to_root(&self, path_a: &Vec<u64>, path_b: &Vec<u64>) -> bool { pub fn layer_closer_to_root(&self, path_a: &[u64], path_b: &[u64]) -> bool {
// Convert UUIDs to indices // Convert UUIDs to indices
let indices_for_path_a = self.indices_for_path(path_a).unwrap(); let indices_for_path_a = self.indices_for_path(path_a).unwrap();
let indices_for_path_b = self.indices_for_path(path_b).unwrap(); let indices_for_path_b = self.indices_for_path(path_b).unwrap();
@ -126,24 +126,20 @@ impl Document {
let index_a = *indices_for_path_a.get(i).unwrap_or(&usize::MAX) as i32; let index_a = *indices_for_path_a.get(i).unwrap_or(&usize::MAX) as i32;
let index_b = *indices_for_path_b.get(i).unwrap_or(&usize::MAX) as i32; let index_b = *indices_for_path_b.get(i).unwrap_or(&usize::MAX) as i32;
// index_a == index_b -> true, this means the "2" indices being compared are within the same folder // At the point at which the two paths first differ, compare to see which is closer to the root
// eg -> [2, X] == [2, X] since we are only comparing the "2" in this iteration if index_a != index_b {
// Continue onto comparing the X indices. // If index_a is smaller, index_a is closer to the root
if index_a == index_b { return index_a < index_b;
continue;
} }
// If index_a is smaller, index_a is closer to the root
return index_a < index_b;
} }
return false; false
} }
// Is the target layer between a <-> b layers, inclusive // Is the target layer between a <-> b layers, inclusive
pub fn layer_is_between(&self, target: &Vec<u64>, path_a: &Vec<u64>, path_b: &Vec<u64>) -> bool { pub fn layer_is_between(&self, target: &[u64], path_a: &[u64], path_b: &[u64]) -> bool {
// If the target is a nonsense path, it isn't between // If the target is a nonsense path, it isn't between
if target.len() < 1 { if target.is_empty() {
return false; return false;
} }
@ -156,8 +152,8 @@ impl Document {
let layer_vs_a = self.layer_closer_to_root(target, path_a); let layer_vs_a = self.layer_closer_to_root(target, path_a);
let layer_vs_b = self.layer_closer_to_root(target, path_b); let layer_vs_b = self.layer_closer_to_root(target, path_b);
// To be inbetween you need to be above A and below B or vice versa // To be in-between you need to be above A and below B or vice versa
return layer_vs_a != layer_vs_b; layer_vs_a != layer_vs_b
} }
/// Given a path to a layer, returns a vector of the indices in the layer tree /// Given a path to a layer, returns a vector of the indices in the layer tree

View File

@ -19,12 +19,12 @@ use syn::parse_macro_input;
/// ///
/// This derive macro is enum-only. /// This derive macro is enum-only.
/// ///
/// The discriminant enum is a copy of the input enum with all fields of every variant removed.\ /// The discriminant enum is a copy of the input enum with all fields of every variant removed.
/// *) The exception to that rule is the `#[child]` attribute /// The exception to that rule is the `#[child]` attribute.
/// ///
/// # Helper attributes /// # Helper attributes
/// - `#[sub_discriminant]`: only usable on variants with a single field; instead of no fields, the discriminant of the single field will be included in the discriminant, /// - `#[sub_discriminant]`: only usable on variants with a single field; instead of no fields, the discriminant of the single field will be included in the discriminant,
/// acting as a sub-discriminant. /// acting as a sub-discriminant.
/// - `#[discriminant_attr(…)]`: usable on the enum itself or on any variant; applies `#[…]` in its place on the discriminant. /// - `#[discriminant_attr(…)]`: usable on the enum itself or on any variant; applies `#[…]` in its place on the discriminant.
/// ///
/// # Attributes on the Discriminant /// # Attributes on the Discriminant
@ -40,20 +40,20 @@ use syn::parse_macro_input;
/// #[derive(ToDiscriminant)] /// #[derive(ToDiscriminant)]
/// #[discriminant_attr(derive(Debug, Eq, PartialEq))] /// #[discriminant_attr(derive(Debug, Eq, PartialEq))]
/// pub enum EnumA { /// pub enum EnumA {
/// A(u8), /// A(u8),
/// #[sub_discriminant] /// #[sub_discriminant]
/// B(EnumB) /// B(EnumB)
/// } /// }
/// ///
/// #[derive(ToDiscriminant)] /// #[derive(ToDiscriminant)]
/// #[discriminant_attr(derive(Debug, Eq, PartialEq))] /// #[discriminant_attr(derive(Debug, Eq, PartialEq))]
/// #[discriminant_attr(repr(u8))] /// #[discriminant_attr(repr(u8))]
/// pub enum EnumB { /// pub enum EnumB {
/// Foo(u8), /// Foo(u8),
/// Bar(String), /// Bar(String),
/// #[cfg(feature = "some-feature")] /// #[cfg(feature = "some-feature")]
/// #[discriminant_attr(cfg(feature = "some-feature"))] /// #[discriminant_attr(cfg(feature = "some-feature"))]
/// WindowsBar(OsString) /// WindowsBar(OsString)
/// } /// }
/// ///
/// let a = EnumA::A(1); /// let a = EnumA::A(1);
@ -73,7 +73,7 @@ pub fn derive_discriminant(input_item: TokenStream) -> TokenStream {
/// ///
/// # Helper Attributes /// # Helper Attributes
/// - `#[parent(<Type>, <Expr>)]` (**required**): declare the parent type (`<Type>`) /// - `#[parent(<Type>, <Expr>)]` (**required**): declare the parent type (`<Type>`)
/// and a function (`<Expr>`, has to evaluate to a single arg function) for converting a value of this type to the parent type /// and a function (`<Expr>`, has to evaluate to a single arg function) for converting a value of this type to the parent type
/// - `#[parent_is_top]`: Denote that the parent type has no further parent type (this is required because otherwise the `From` impls for parent and top parent would overlap) /// - `#[parent_is_top]`: Denote that the parent type has no further parent type (this is required because otherwise the `From` impls for parent and top parent would overlap)
/// ///
/// # Example /// # Example
@ -85,23 +85,23 @@ pub fn derive_discriminant(input_item: TokenStream) -> TokenStream {
/// struct A { u: u8, b: B }; /// struct A { u: u8, b: B };
/// ///
/// impl A { /// impl A {
/// pub fn from_b(b: B) -> Self { /// pub fn from_b(b: B) -> Self {
/// Self { u: 7, b } /// Self { u: 7, b }
/// } /// }
/// } /// }
/// ///
/// impl TransitiveChild for A { /// impl TransitiveChild for A {
/// type Parent = Self; /// type Parent = Self;
/// type TopParent = Self; /// type TopParent = Self;
/// } /// }
/// ///
/// #[derive(TransitiveChild, Debug, Eq, PartialEq)] /// #[derive(TransitiveChild, Debug, Eq, PartialEq)]
/// #[parent(A, A::from_b)] /// #[parent(A, A::from_b)]
/// #[parent_is_top] /// #[parent_is_top]
/// enum B { /// enum B {
/// Foo, /// Foo,
/// Bar, /// Bar,
/// Child(C) /// Child(C)
/// } /// }
/// ///
/// #[derive(TransitiveChild, Debug, Eq, PartialEq)] /// #[derive(TransitiveChild, Debug, Eq, PartialEq)]
@ -134,41 +134,41 @@ pub fn derive_transitive_child(input_item: TokenStream) -> TokenStream {
/// ///
/// #[derive(AsMessage)] /// #[derive(AsMessage)]
/// pub enum TopMessage { /// pub enum TopMessage {
/// A(u8), /// A(u8),
/// B(u16), /// B(u16),
/// #[child] /// #[child]
/// C(MessageC), /// C(MessageC),
/// #[child] /// #[child]
/// D(MessageD) /// D(MessageD)
/// } /// }
/// ///
/// impl TransitiveChild for TopMessage { /// impl TransitiveChild for TopMessage {
/// type Parent = Self; /// type Parent = Self;
/// type TopParent = Self; /// type TopParent = Self;
/// } /// }
/// ///
/// #[derive(TransitiveChild, AsMessage, Copy, Clone)] /// #[derive(TransitiveChild, AsMessage, Copy, Clone)]
/// #[parent(TopMessage, TopMessage::C)] /// #[parent(TopMessage, TopMessage::C)]
/// #[parent_is_top] /// #[parent_is_top]
/// pub enum MessageC { /// pub enum MessageC {
/// X1, /// X1,
/// X2 /// X2
/// } /// }
/// ///
/// #[derive(TransitiveChild, AsMessage, Copy, Clone)] /// #[derive(TransitiveChild, AsMessage, Copy, Clone)]
/// #[parent(TopMessage, TopMessage::D)] /// #[parent(TopMessage, TopMessage::D)]
/// #[parent_is_top] /// #[parent_is_top]
/// pub enum MessageD { /// pub enum MessageD {
/// Y1, /// Y1,
/// #[child] /// #[child]
/// Y2(MessageE) /// Y2(MessageE)
/// } /// }
/// ///
/// #[derive(TransitiveChild, AsMessage, Copy, Clone)] /// #[derive(TransitiveChild, AsMessage, Copy, Clone)]
/// #[parent(MessageD, MessageD::Y2)] /// #[parent(MessageD, MessageD::Y2)]
/// pub enum MessageE { /// pub enum MessageE {
/// Alpha, /// Alpha,
/// Beta /// Beta
/// } /// }
/// ///
/// let c = MessageC::X1; /// let c = MessageC::X1;
@ -195,18 +195,18 @@ pub fn derive_message(input_item: TokenStream) -> TokenStream {
/// # Usage /// # Usage
/// There are three possible argument syntaxes you can use: /// There are three possible argument syntaxes you can use:
/// 1. no arguments: this is for the top-level message enum. It derives `ToDiscriminant`, `AsMessage` on the discriminant, and implements `TransitiveChild` on both /// 1. no arguments: this is for the top-level message enum. It derives `ToDiscriminant`, `AsMessage` on the discriminant, and implements `TransitiveChild` on both
/// (the parent and top parent being the respective types themselves). /// (the parent and top parent being the respective types themselves).
/// It also derives the following `std` traits on the discriminant: `Debug, Copy, Clone, PartialEq, Eq, Hash`. /// It also derives the following `std` traits on the discriminant: `Debug, Copy, Clone, PartialEq, Eq, Hash`.
/// 2. two arguments: this is for message enums whose direct parent is the top level message enum. The syntax is `#[impl_message(<Type>, <Ident>)]`, /// 2. two arguments: this is for message enums whose direct parent is the top level message enum. The syntax is `#[impl_message(<Type>, <Ident>)]`,
/// where `<Type>` is the parent message type and `<Ident>` is the identifier of the variant used to construct this child. /// where `<Type>` is the parent message type and `<Ident>` is the identifier of the variant used to construct this child.
/// It derives `ToDiscriminant`, `AsMessage` on the discriminant, and `TransitiveChild` on both (adding `#[parent_is_top]` to both). /// It derives `ToDiscriminant`, `AsMessage` on the discriminant, and `TransitiveChild` on both (adding `#[parent_is_top]` to both).
/// It also derives the following `std` traits on the discriminant: `Debug, Copy, Clone, PartialEq, Eq, Hash`. /// It also derives the following `std` traits on the discriminant: `Debug, Copy, Clone, PartialEq, Eq, Hash`.
/// 3. three arguments: this is for all other message enums that are transitive children of the top level message enum. The syntax is /// 3. three arguments: this is for all other message enums that are transitive children of the top level message enum. The syntax is
/// `#[impl_message(<Type>, <Type>, <Ident>)]`, where the first `<Type>` is the top parent message type, the second `<Type>` is the parent message type /// `#[impl_message(<Type>, <Type>, <Ident>)]`, where the first `<Type>` is the top parent message type, the second `<Type>` is the parent message type
/// and `<Ident>` is the identifier of the variant used to construct this child. /// and `<Ident>` is the identifier of the variant used to construct this child.
/// It derives `ToDiscriminant`, `AsMessage` on the discriminant, and `TransitiveChild` on both. /// It derives `ToDiscriminant`, `AsMessage` on the discriminant, and `TransitiveChild` on both.
/// It also derives the following `std` traits on the discriminant: `Debug, Copy, Clone, PartialEq, Eq, Hash`. /// It also derives the following `std` traits on the discriminant: `Debug, Copy, Clone, PartialEq, Eq, Hash`.
/// **This third option will likely change in the future** /// **This third option will likely change in the future**
#[proc_macro_attribute] #[proc_macro_attribute]
pub fn impl_message(attr: TokenStream, input_item: TokenStream) -> TokenStream { pub fn impl_message(attr: TokenStream, input_item: TokenStream) -> TokenStream {
TokenStream::from(combined_message_attrs_impl(attr.into(), input_item.into()).unwrap_or_else(|err| err.to_compile_error())) TokenStream::from(combined_message_attrs_impl(attr.into(), input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
@ -221,12 +221,12 @@ pub fn impl_message(attr: TokenStream, input_item: TokenStream) -> TokenStream {
/// ///
/// #[derive(Hint)] /// #[derive(Hint)]
/// pub enum StateMachine { /// pub enum StateMachine {
/// #[hint(rmb = "foo", lmb = "bar")] /// #[hint(rmb = "foo", lmb = "bar")]
/// Ready, /// Ready,
/// #[hint(alt = "baz")] /// #[hint(alt = "baz")]
/// RMBDown, /// RMBDown,
/// // no hint (also ok) /// // no hint (also ok)
/// LMBDown /// LMBDown
/// } /// }
/// ``` /// ```
#[proc_macro_derive(Hint, attributes(hint))] #[proc_macro_derive(Hint, attributes(hint))]
@ -239,30 +239,30 @@ pub fn derive_hint(input_item: TokenStream) -> TokenStream {
/// # Example /// # Example
/// ```ignore /// ```ignore
/// match (example_tool_state, event) { /// match (example_tool_state, event) {
/// (ToolState::Ready, Event::MouseDown(mouse_state)) if *mouse_state == MouseState::Left => { /// (ToolState::Ready, Event::MouseDown(mouse_state)) if *mouse_state == MouseState::Left => {
/// #[edge("LMB Down")] /// #[edge("LMB Down")]
/// ToolState::Pending /// ToolState::Pending
/// } /// }
/// (SelectToolState::Pending, Event::MouseUp(mouse_state)) if *mouse_state == MouseState::Left => { /// (SelectToolState::Pending, Event::MouseUp(mouse_state)) if *mouse_state == MouseState::Left => {
/// #[edge("LMB Up: Select Object")] /// #[edge("LMB Up: Select Object")]
/// SelectToolState::Ready /// SelectToolState::Ready
/// } /// }
/// (SelectToolState::Pending, Event::MouseMove(x,y)) => { /// (SelectToolState::Pending, Event::MouseMove(x,y)) => {
/// #[edge("Mouse Move")] /// #[edge("Mouse Move")]
/// SelectToolState::TransformSelected /// SelectToolState::TransformSelected
/// } /// }
/// (SelectToolState::TransformSelected, Event::MouseMove(x,y)) => { /// (SelectToolState::TransformSelected, Event::MouseMove(x,y)) => {
/// #[egde("Mouse Move")] /// #[edge("Mouse Move")]
/// SelectToolState::TransformSelected /// SelectToolState::TransformSelected
/// } /// }
/// (SelectToolState::TransformSelected, Event::MouseUp(mouse_state)) if *mouse_state == MouseState::Left => { /// (SelectToolState::TransformSelected, Event::MouseUp(mouse_state)) if *mouse_state == MouseState::Left => {
/// #[edge("LMB Up")] /// #[edge("LMB Up")]
/// SelectToolState::Ready /// SelectToolState::Ready
/// } /// }
/// (state, _) => { /// (state, _) => {
/// // Do nothing /// // Do nothing
/// state /// state
/// } /// }
/// } /// }
/// ``` /// ```
#[proc_macro_attribute] #[proc_macro_attribute]