1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use paste::paste;
use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;

use std::borrow::Cow;
use std::fmt;

use crate::parse::ast::Spanned;
use crate::parse::token::{
    Checksum as ParsedChecksum, Comment as ParsedComment, Field as ParsedField,
    InlineComment as ParsedInlineComment, Newline as ParsedNewline, Percent as ParsedPercent,
    Value as ParsedValue, Whitespace as ParsedWhitespace,
};

#[derive(Clone, PartialEq, Debug)]
/// The output struct for gcode emission implementing [std::fmt::Display]
///
/// Any strings here are expected to have escaped characters, see <https://www.reprap.org/wiki/G-code#Quoted_strings>
pub enum Token<'a> {
    Field(Field<'a>),
    Comment {
        is_inline: bool,
        inner: Cow<'a, str>,
    },
    Checksum(u8),
    Whitespace(Cow<'a, str>),
    Newline {
        is_crlf: bool,
    },
    Percent,
}

impl<'input> From<&ParsedField<'input>> for Token<'input> {
    fn from(field: &ParsedField<'input>) -> Self {
        Self::Field(field.into())
    }
}

impl<'a, 'input: 'a> From<&'a ParsedInlineComment<'input>> for Token<'a> {
    fn from(comment: &'a ParsedInlineComment<'input>) -> Self {
        Self::Comment {
            is_inline: true,
            inner: Cow::Borrowed(
                comment
                    .inner
                    .strip_prefix("(")
                    .unwrap()
                    .strip_suffix(")")
                    .unwrap(),
            ),
        }
    }
}

impl<'input> From<&ParsedComment<'input>> for Token<'input> {
    fn from(comment: &ParsedComment<'input>) -> Self {
        Self::Comment {
            is_inline: false,
            inner: Cow::Borrowed(comment.inner.strip_prefix(";").unwrap()),
        }
    }
}

impl<'input> From<&ParsedChecksum> for Token<'input> {
    fn from(checksum: &ParsedChecksum) -> Self {
        Self::Checksum(checksum.inner)
    }
}

impl<'input> From<&ParsedWhitespace<'input>> for Token<'input> {
    fn from(whitespace: &ParsedWhitespace<'input>) -> Self {
        Self::Whitespace(Cow::Borrowed(whitespace.inner))
    }
}

impl<'input> From<&ParsedNewline> for Token<'input> {
    fn from(newline: &ParsedNewline) -> Self {
        Self::Newline {
            is_crlf: newline.span().len() == 2,
        }
    }
}

impl<'input> From<&ParsedPercent> for Token<'input> {
    fn from(_percent: &ParsedPercent) -> Self {
        Self::Percent
    }
}

impl fmt::Display for Token<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use Token::*;
        match self {
            Field(field) => write!(f, "{}", field),
            Comment { is_inline, inner } => match is_inline {
                true => write!(f, "({})", inner),
                false => write!(f, ";{}", inner),
            },
            Checksum(c) => write!(f, "{}", c),
            Whitespace(w) => write!(f, "{}", w),
            Newline { is_crlf: true } => write!(f, "\r\n"),
            Newline { is_crlf: false } => write!(f, "\n"),
            Percent => write!(f, "%"),
        }
    }
}

/// Fundamental unit of g-code: a descriptive letter followed by a value.
///
/// Field type supports owned and partially-borrowed representations using [Cow].
#[derive(Clone, PartialEq, Debug)]
pub struct Field<'a> {
    pub letters: Cow<'a, str>,
    pub value: Value<'a>,
}

impl<'a> fmt::Display for Field<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}", self.letters, self.value)
    }
}

impl<'input> From<&ParsedField<'input>> for Field<'input> {
    fn from(field: &ParsedField<'input>) -> Self {
        Self {
            letters: field.letters.into(),
            value: Value::from(&field.value),
        }
    }
}

impl<'a> From<Field<'a>> for Token<'a> {
    fn from(field: Field<'a>) -> Token<'a> {
        Self::Field(field)
    }
}

impl<'a> Field<'a> {
    /// Returns an owned representation of the Field valid for the `'static` lifetime.
    ///
    /// This will allocate any string types.
    pub fn into_owned(self) -> Field<'static> {
        Field {
            letters: self.letters.into_owned().into(),
            value: self.value.into_owned(),
        }
    }
}

/// All the possible variations of a field's value.
/// Some flavors of g-code also allow for strings.
///
/// Any strings here are expected to have escaped characters, see <https://www.reprap.org/wiki/G-code#Quoted_strings>
#[derive(Clone, PartialEq, Debug)]
pub enum Value<'a> {
    Rational(Decimal),
    Float(f64),
    Integer(usize),
    String(Cow<'a, str>),
}

impl Value<'_> {
    /// Interpret the value as an [f64]
    ///
    /// Returns [Option::None] for [Value::String] or a [Value::Rational] that can't be converted.
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Self::Rational(r) => r.to_f64(),
            Self::Integer(i) => Some(*i as f64),
            Self::Float(f) => Some(*f),
            Self::String(_) => None,
        }
    }

    /// Returns an owned representation of the Value valid for the `'static` lifetime.
    ///
    /// This will allocate a string for a [Value::String].
    pub fn into_owned(self) -> Value<'static> {
        match self {
            Self::String(s) => Value::String(s.into_owned().into()),
            Self::Rational(r) => Value::Rational(r),
            Self::Integer(i) => Value::Integer(i),
            Self::Float(f) => Value::Float(f),
        }
    }
}

impl<'input> From<&ParsedValue<'input>> for Value<'input> {
    fn from(val: &ParsedValue<'input>) -> Self {
        use ParsedValue::*;
        match val {
            Rational(r) => Self::Rational(*r),
            Integer(i) => Self::Integer(*i),
            String(s) => {
                // Remove enclosing quotes
                Self::String(Cow::Borrowed(
                    s.strip_prefix('"').unwrap().strip_suffix('"').unwrap(),
                ))
            }
        }
    }
}

impl fmt::Display for Value<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Rational(r) => {
                write!(f, "{}", r)?;
                // The only way this could've been interpreted
                // as rational is if there is a trailing decimal point,
                // so add it back in.
                if r.fract().is_zero() {
                    write!(f, ".")?;
                }
                Ok(())
            }
            Self::Float(float) => write!(f, "{}", float),
            Self::Integer(i) => write!(f, "{}", i),
            Self::String(s) => write!(f, "\"{}\"", s),
        }
    }
}

/// A macro for quickly instantiating a float-valued command
///
/// For instance:
///
/// ```
/// use g_code::command;
/// assert_eq!(command!(RapidPositioning { X: 0., Y: 1., }).iter().fold(String::default(), |s, f| s + &f.to_string()), "G0X0Y1");
/// ```
#[macro_export]
macro_rules! command {
    ($commandName: ident {
        $($arg: ident : $value: expr,)*
    }) => {
        {
            paste::expr!{
                g_code::emit::[<$commandName:snake:lower>](
                    vec![$(
                        g_code::emit::Field {
                            letters: std::borrow::Cow::Borrowed(stringify!([<$arg:upper>])),
                            value: g_code::emit::Value::Float($value),
                        }
                    ,)*].drain(..)
                )
            }
        }
    };
}

macro_rules! impl_commands {
    ($($(#[$outer:meta])* $commandName: ident {$letters: expr, $value: literal, {$($(#[$inner:meta])* $arg: ident), *} },)*) => {

        paste! {
            $(
                $(#[$outer])*
                ///
                /// Call this function to instantiate the command.
                pub fn [<$commandName:snake:lower>]<'a, I: Iterator<Item = Field<'a>>>(args: I) -> Command<'a> {
                    Command {
                        name: [<$commandName:snake:upper _FIELD>].clone(),
                        args: args.filter(|arg| {
                            match arg.letters.to_ascii_uppercase().as_str() {
                                $(stringify!($arg) => true,)*
                                _ => false
                            }
                        }).collect(),
                    }
                }

                /// Constant for this command's name used to reduce allocations.
                pub const [<$commandName:snake:upper _FIELD>]: Field<'static> = Field {
                    letters: std::borrow::Cow::Borrowed($letters),
                    value: crate::emit::Value::Integer($value),
                };
            )*
        }

        /// Commands are the operational unit of g-code
        ///
        /// They consist of a G, M, or other top-level field followed by field arguments
        #[derive(Clone, PartialEq, Debug)]
        pub struct Command<'a> {
            name: Field<'a>,
            args: Vec<Field<'a>>,
        }

        impl<'a> Command<'a> {
            /// Add a field to the command.
            ///
            /// Returns [Err] if the Field's letters aren't recognized.
            pub fn push(&mut self, arg: Field<'a>) -> Result<(), &'static str> {
                paste!{
                    match &self.name {
                        $(x if *x == [<$commandName:snake:upper _FIELD>] => {
                            if match arg.letters.as_ref() {
                                $(stringify!([<$arg:upper>]) => {true},)*
                                $(stringify!([<$arg:lower>]) => {true},)*
                                _ => false,
                            } {
                                self.args.push(arg);
                                Ok(())
                            } else {
                                Err(concat!($(stringify!([<$arg:lower>]), " ", stringify!([<$arg:upper>]), " ", )*))
                            }
                        },)*
                        _ => {
                            unreachable!("a command's name cannot change");
                        }
                    }
                }
            }

            /// Iterate over all fields including the command's name (i.e. G0 for rapid positioning)
            pub fn iter(&self) -> impl Iterator<Item = &Field> {
                std::iter::once(&self.name).chain(self.args.iter())
            }

            /// Consumes the command to produce tokens suitable for output
            pub fn into_token_vec(mut self) -> Vec<Token<'a>> {
                std::iter::once(self.name).chain(self.args.drain(..)).map(|f| f.into()).collect()
            }

            /// Iterate over the fields after the command's name
            pub fn iter_args(&self) -> impl Iterator<Item = &Field> {
                self.iter().skip(1)
            }

            pub fn iter_mut_args(&mut self) -> impl Iterator<Item = &mut Field<'a>> {
                self.args.iter_mut()
            }

            pub fn get(&'_ self, letters: &str) -> Option<&'_ Field> {
                let letters = letters.to_ascii_uppercase();
                self.iter_args().find(|arg| arg.letters == letters)
            }

            pub fn set(&mut self, letters: &str, value: Value<'a>) {
                let letters = letters.to_ascii_uppercase();
                for i in 0..self.args.len() {
                    if self.args[i].letters == letters {
                        self.args[i].value = value;
                        break;
                    }
                }
            }
        }
    };
}

impl_commands!(
    /// Moves the head at the fastest possible speed to the desired speed
    /// Never enter a cut with rapid positioning
    /// Some older machines may "dog leg" rapid positioning, moving one axis at a time
    RapidPositioning {
        "G", 0, {
            X,
            Y,
            Z,
            E,
            F,
            H,
            R,
            S,
            A,
            B,
            C
        }
    },
    /// Typically used for "cutting" motion
    LinearInterpolation {
        "G", 1, {
            X,
            Y,
            Z,
            E,
            F,
            H,
            R,
            S,
            A,
            B,
            C
        }
    },
    /// This will keep the axes unmoving for the period of time in seconds specified by the P number
    Dwell {
        "G", 4, {
            /// Time in seconds
            P
        }
    },
    /// Use inches for length units
    UnitsInches {
        "G", 20, {}
    },
    /// Use millimeters for length units
    UnitsMillimeters {
        "G", 21, {}
    },
    /// In absolute distance mode, axis numbers usually represent positions in terms of the currently active coordinate system.
    AbsoluteDistanceMode {
        "G", 90, {}
    },
    /// In relative distance mode, axis numbers usually represent increments from the current values of the numbers
    RelativeDistanceMode {
        "G", 91, {}
    },
    FeedRateUnitsPerMinute {
        "G", 94, {}
    },
    /// Start spinning the spindle clockwise with speed `p`
    StartSpindleClockwise {
        "M", 3, {
            /// Speed
            P
        }
    },
    /// Start spinning the spindle counterclockwise with speed `p`
    StartSpindleCounterclockwise {
        "M", 4, {
            /// Speed
            P
        }
    },
    /// Stop spinning the spindle
    StopSpindle {
        "M", 5, {}
    },
    /// Signals the end of a program
    ProgramEnd {
        "M", 2, {}
    },
);