geo_aid_script/
figure.rs

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
//! Geo-AID's figure Intermediate Representation and all definitions related to it.
//! Note that a part of it is also located in `geo-aid-figure`

use std::{fmt::Display, str::FromStr};

use crate::geometry::ValueEnum;
use crate::math::{EntityKind, IndexMap, Reconstruct, ReconstructCtx, Reindex};
use geo_aid_figure::math_string::{
    MathChar, MathIndex, MathSpecial, MathString, ParseErrorKind, SPECIAL_MATH,
};
use geo_aid_figure::{Style, VarIndex};

use crate::span;

use super::math::Entity;
use super::{
    math,
    parser::{FromProperty, Parse, PropertyValue},
    token::{Ident, PointCollectionItem, Span},
    unroll::most_similar,
    Error,
};

/// A drawn point
#[derive(Debug, Clone)]
pub struct PointItem {
    /// Index of the defining expression
    pub id: VarIndex,
    /// Label of this point
    pub label: MathString,
    /// Whether to display a small circle in its place
    pub display_dot: bool,
}

impl Reindex for PointItem {
    fn reindex(&mut self, map: &IndexMap) {
        self.id.reindex(map);
    }
}

impl Reconstruct for PointItem {
    fn reconstruct(self, ctx: &mut ReconstructCtx) -> Self {
        Self {
            id: self.id.reconstruct(ctx),
            ..self
        }
    }
}

impl From<PointItem> for Item {
    fn from(value: PointItem) -> Self {
        Self::Point(value)
    }
}

/// A drawn circle
#[derive(Debug, Clone)]
pub struct CircleItem {
    /// Index of the defining expression
    pub id: VarIndex,
    /// Label of this circle
    pub label: MathString,
    /// How to draw the circle (brush)
    pub style: Style,
}

impl Reindex for CircleItem {
    fn reindex(&mut self, map: &IndexMap) {
        self.id.reindex(map);
    }
}

impl Reconstruct for CircleItem {
    fn reconstruct(self, ctx: &mut ReconstructCtx) -> Self {
        Self {
            id: self.id.reconstruct(ctx),
            ..self
        }
    }
}

impl From<CircleItem> for Item {
    fn from(value: CircleItem) -> Self {
        Self::Circle(value)
    }
}

/// A drawn line
#[derive(Debug, Clone)]
pub struct LineItem {
    /// Index of the defining expression
    pub id: VarIndex,
    /// Label of this line
    pub label: MathString,
    /// How to draw the line (brush)
    pub style: Style,
}

impl Reindex for LineItem {
    fn reindex(&mut self, map: &IndexMap) {
        self.id.reindex(map);
    }
}

impl Reconstruct for LineItem {
    fn reconstruct(self, ctx: &mut ReconstructCtx) -> Self {
        Self {
            id: self.id.reconstruct(ctx),
            ..self
        }
    }
}

impl From<LineItem> for Item {
    fn from(value: LineItem) -> Self {
        Self::Line(value)
    }
}

/// A drawn ray (half-line)
#[derive(Debug, Clone)]
pub struct RayItem {
    /// Index of the expression defining the ray's origin (end point).
    pub p_id: VarIndex,
    /// Index of the expression defining the ray's guiding point
    pub q_id: VarIndex,
    /// The ray's label
    pub label: MathString,
    /// How to draw the ray (brush)
    pub style: Style,
}

impl Reindex for RayItem {
    fn reindex(&mut self, map: &IndexMap) {
        self.p_id.reindex(map);
        self.q_id.reindex(map);
    }
}

impl Reconstruct for RayItem {
    fn reconstruct(self, ctx: &mut ReconstructCtx) -> Self {
        Self {
            p_id: self.p_id.reconstruct(ctx),
            q_id: self.q_id.reconstruct(ctx),
            ..self
        }
    }
}

impl From<RayItem> for Item {
    fn from(value: RayItem) -> Self {
        Self::Ray(value)
    }
}

/// A drawn segment
#[derive(Debug, Clone)]
pub struct SegmentItem {
    /// Index of the expression defining the first endpoint
    pub p_id: VarIndex,
    /// Index of the expression defining the second endpoint
    pub q_id: VarIndex,
    /// The segment's label
    pub label: MathString,
    /// How to draw the segment (brush)
    pub style: Style,
}

impl From<SegmentItem> for Item {
    fn from(value: SegmentItem) -> Self {
        Self::Segment(value)
    }
}

impl Reindex for SegmentItem {
    fn reindex(&mut self, map: &IndexMap) {
        self.p_id.reindex(map);
        self.q_id.reindex(map);
    }
}

impl Reconstruct for SegmentItem {
    fn reconstruct(self, ctx: &mut ReconstructCtx) -> Self {
        Self {
            p_id: self.p_id.reconstruct(ctx),
            q_id: self.q_id.reconstruct(ctx),
            ..self
        }
    }
}

/// A type-erased drawn item of the figure
#[derive(Debug, Clone)]
pub enum Item {
    Point(PointItem),
    Circle(CircleItem),
    Line(LineItem),
    Ray(RayItem),
    Segment(SegmentItem),
}

impl Reindex for Item {
    fn reindex(&mut self, map: &IndexMap) {
        match self {
            Self::Point(v) => v.reindex(map),
            Self::Circle(v) => v.reindex(map),
            Self::Line(v) => v.reindex(map),
            Self::Ray(v) => v.reindex(map),
            Self::Segment(v) => v.reindex(map),
        }
    }
}

impl Reconstruct for Item {
    fn reconstruct(self, ctx: &mut ReconstructCtx) -> Self {
        match self {
            Self::Point(v) => Self::Point(v.reconstruct(ctx)),
            Self::Circle(v) => Self::Circle(v.reconstruct(ctx)),
            Self::Line(v) => Self::Line(v.reconstruct(ctx)),
            Self::Ray(v) => Self::Ray(v.reconstruct(ctx)),
            Self::Segment(v) => Self::Segment(v.reconstruct(ctx)),
        }
    }
}

/// Defines the visual data of the figure.
#[derive(Debug, Default, Clone)]
pub struct Figure {
    /// Entities used by the figure
    pub entities: Vec<EntityKind>,
    /// Variables used by the figure
    pub variables: Vec<math::Expr<()>>,
    /// Drawn items
    pub items: Vec<Item>,
}

/// Generated figure, created by the engine
#[derive(Debug, Clone, Default)]
pub struct Generated {
    /// Entities used by the figure
    pub entities: Vec<Entity<ValueEnum>>,
    /// Variables used by the figure
    pub variables: Vec<math::Expr<ValueEnum>>,
    /// Drawn items with meta
    pub items: Vec<Item>,
}

/// A [`MathString`] with a [`Span`].
#[derive(Debug, Clone)]
pub struct SpannedMathString {
    pub string: MathString,
    pub span: Span,
}

impl SpannedMathString {
    /// Create an empty math string with a span.
    #[must_use]
    pub fn new(span: Span) -> Self {
        Self {
            string: MathString::new(),
            span,
        }
    }

    /// Return `Some` with `self` if the string should be displayed by default.
    /// A string should be displayed by default if it consists of one alphabetical
    /// (either special or literal) and is possibly followed by primes (') and an index
    /// of any length.
    ///
    /// # Panics
    /// Any panic here is a bug.
    #[must_use]
    pub fn displayed_by_default(&self) -> Option<Self> {
        let mut result = MathString::new();

        // The first set of characters must be either a single character or a special code.
        let mut letter = String::new();

        let mut chars = self.string.iter().copied().peekable();

        while let Some(MathChar::Ascii(c)) = chars.peek().copied() {
            chars.next();
            letter.push(c);
        }

        if let Some(special) = MathSpecial::parse(&letter) {
            if special.is_alphabetic() {
                result.push(MathChar::Special(special));
            } else {
                return None;
            }
        } else if letter.len() == 1 {
            result.push(MathChar::Ascii(letter.chars().next().unwrap()));
        } else {
            return None;
        }

        while Some(MathChar::Prime) == chars.peek().copied() {
            chars.next();
            result.push(MathChar::Prime);
        }

        if chars.next() == Some(MathChar::SetIndex(MathIndex::Lower)) {
            result.push(MathChar::SetIndex(MathIndex::Lower));
            for c in chars.by_ref() {
                if c == MathChar::SetIndex(MathIndex::Normal) {
                    break;
                }

                result.push(c);
            }
            result.push(MathChar::SetIndex(MathIndex::Normal));
        }

        if chars.next().is_none() {
            Some(Self {
                string: result,
                span: self.span,
            })
        } else {
            None
        }
    }

    /// Try to parse the given string as a math string.
    ///
    /// # Errors
    /// Returns an error on parsing errors.
    pub fn parse(content: &str, content_span: Span) -> Result<Self, Error> {
        let string = MathString::from_str(content).map_err(|err| {
            let error_span = span!(
                content_span.start.line,
                content_span.start.column + err.span.start,
                content_span.end.line,
                content_span.end.column + err.span.end
            );

            match err.kind {
                ParseErrorKind::SpecialNotRecognised(special) => {
                    let suggested = most_similar(&SPECIAL_MATH, &special);

                    Error::SpecialNotRecognised {
                        error_span,
                        code: special,
                        suggested,
                    }
                }
                ParseErrorKind::NestedIndex => Error::LabelIndexInsideIndex { error_span },
                ParseErrorKind::UnclosedSpecialTag(special) => Error::UnclosedSpecial {
                    error_span,
                    parsed_special: special,
                },
            }
        })?;

        Ok(Self {
            string,
            span: content_span,
        })
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.string.is_empty()
    }

    #[must_use]
    pub fn get_span(&self) -> Span {
        self.span
    }
}

impl FromProperty for SpannedMathString {
    fn from_property(property: PropertyValue) -> Result<Self, Error> {
        match property {
            PropertyValue::Number(n) => Err(Error::StringOrIdentExpected {
                error_span: n.get_span(),
            }),
            PropertyValue::Ident(i) => match i {
                Ident::Collection(mut c) => {
                    if c.len() == 1 {
                        Ok(Self::from(c.collection.swap_remove(0)))
                    } else {
                        Err(Error::InvalidIdentMathString { error_span: c.span })
                    }
                }
                Ident::Named(n) => Self::parse(&n.ident, n.span)?
                    .displayed_by_default()
                    .ok_or(Error::InvalidIdentMathString { error_span: n.span }),
            },
            PropertyValue::String(s) => Self::parse(
                &s.content,
                span!(
                    s.span.start.line,
                    s.span.start.column + 1,
                    s.span.end.line,
                    s.span.end.column - 1
                ),
            ),
            PropertyValue::RawString(s) => Ok(Self {
                string: MathString::raw(&s.lit.content),
                span: s.get_span(),
            }),
        }
    }
}

impl From<PointCollectionItem> for SpannedMathString {
    fn from(value: PointCollectionItem) -> Self {
        let mut string = MathString::new();
        string.push(MathChar::Ascii(value.letter));

        if let Some(index) = value.index {
            string.extend(index.chars().map(MathChar::Ascii));
        }

        string.extend([MathChar::Prime].repeat(value.primes.into()));

        Self {
            string,
            span: value.span,
        }
    }
}

impl Display for SpannedMathString {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.string)
    }
}