ecore_rs 0.1.0

A parser for the Eclipse Modeling Framework Ecore format.
Documentation
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
prelude! {
    ctx::*,
    regex::Regex,
}

pub mod helpers {
    use super::*;

    pub fn bool(s: impl AsRef<str>) -> Res<bool> {
        match s.as_ref() {
            "true" | "True" => Ok(true),
            "false" | "False" => Ok(false),
            s => bail!("expected boolean, got `{}`", s),
        }
    }
}

pub struct Parser<'input> {
    txt: &'input str,
    cursor: usize,
}

/// # Parsing entry point
impl<'input> Parser<'input> {
    pub fn parse(txt: &'input str, ctx: &mut Ctx) -> Res<()> {
        let mut slf = Self::new(txt);
        match slf.top(ctx) {
            Ok(res) => Ok(res),
            Err(mut err) => {
                if !slf.at_eoi() {
                    err = err.context(|| {
                        let mut blah = "current parser state:".to_string();
                        for line in slf.tail().lines().take(2) {
                            blah.push_str("\n| `");
                            blah.push_str(line);
                            blah.push('`');
                        }
                        blah
                    })
                }
                return Err(err.with_context("parsing failed"));
            }
        }
    }

    fn top(&mut self, ctx: &mut Ctx) -> Res<()> {
        // ignore xml header
        let _ = self.until_char('<', true);
        let _ = self.until_char('>', true);

        let mut path = ctx.enter_root_pack()?;
        self.at_path(&mut path)
    }
}

/// ## Constructors
impl<'input> Parser<'input> {
    pub fn new(txt: &'input str) -> Self {
        Self { txt, cursor: 0 }
    }
}

/// ## Basic parsing-related features
impl<'input> Parser<'input> {
    pub fn at_eoi(&self) -> bool {
        self.cursor >= self.txt.len()
    }

    pub fn fail_on_eoi(&self) -> Res<()> {
        if self.at_eoi() {
            bail!("reached end of input unexpectedly")
        }
        Ok(())
    }

    pub fn handle_redef<From, Into>(
        &self,
        desc: impl Display,
        name: impl Display,
        from: Option<&From>,
        into: Into,
    ) -> Res<()>
    where
        From: Display,
        Into: Display,
    {
        if let Some(from) = from {
            log::warn!(
                "XML-level {} redefinition for `{}` from `{}` to `{}`",
                desc,
                name,
                from,
                into
            )
        }
        Ok(())
    }

    pub fn tail(&self) -> &'input str {
        &self.txt[self.cursor..]
    }

    pub fn debug_show_tail_n(&self, n: usize, pref: impl AsRef<str>) {
        let pref = pref.as_ref();
        for line in self.tail().lines().take(n) {
            log::debug!("{}`{}`", pref, line)
        }
    }
}

/// ## Basic parsers
impl<'input> Parser<'input> {
    pub fn ws(&mut self) {
        for c in self.tail().chars() {
            if c.is_whitespace() {
                self.cursor += 1;
            } else {
                break;
            }
        }
    }

    pub fn raw_tag(&mut self, tag: impl AsRef<str>) -> Res<()> {
        let tag = tag.as_ref();
        let okay = self.try_raw_tag(tag);
        if !okay {
            log::error!("|==[raw_tag] failure");
            log::error!("| parser tail (next two lines):");
            for line in self.tail().lines().take(2) {
                log::error!("| `{}`", line)
            }
            log::error!("|==|");
            bail!("expected tag `{}`", tag)
        }
        Ok(())
    }
    pub fn try_raw_tag(&mut self, tag: impl AsRef<str>) -> bool {
        let tag = tag.as_ref();
        let tail = self.tail();
        if tag.len() < self.tail().len() {
            if tail.starts_with(tag) {
                self.cursor += tag.len();
                return true;
            }
        }
        false
    }

    pub fn tag(&mut self, tag: impl AsRef<str>) -> Res<()> {
        let tag = tag.as_ref();
        if !self.try_tag(tag) {
            log::error!("|==[tag] failure");
            log::error!("| parser tail:");
            for line in self.tail().lines().take(2) {
                log::error!("| `{}`", line)
            }
            log::error!("|==|");
            bail!("expected tag `{}`", tag)
        }
        Ok(())
    }
    pub fn try_tag(&mut self, tag: impl AsRef<str>) -> bool {
        let mem = self.cursor;
        let success = self.try_raw_tag(tag);
        if success {
            if let Some(c) = self.tail().chars().next() {
                if c.is_ascii_alphanumeric() {
                    self.cursor = mem;
                    return false;
                }
            }
        }
        success
    }

    pub fn regex(&mut self, re: Regex) -> &'input str {
        self.try_regex(re).unwrap()
    }
    pub fn try_regex(&mut self, re: Regex) -> Option<&'input str> {
        if let Some(m4tch) = re.find(self.tail()) {
            debug_assert_eq!(m4tch.start(), 0);
            let res = m4tch.as_str();
            self.cursor += res.len();
            Some(res)
        } else {
            None
        }
    }

    pub fn ident(&mut self) -> Res<&'input str> {
        if let Some(id) = self.try_ident() {
            Ok(id)
        } else {
            bail!("expected identifier")
        }
    }
    pub fn try_ident(&mut self) -> Option<&'input str> {
        self.try_regex(Regex::new(r#"^[a-zA-Z_][a-zA-Z_\-0-9]*"#).unwrap())
    }

    pub fn colon_ident(&mut self) -> &'input str {
        self.try_colon_ident().unwrap()
    }
    pub fn try_colon_ident(&mut self) -> Option<&'input str> {
        self.try_regex(Regex::new(r#"^[a-zA-Z_][:a-zA-Z_\-0-9]*"#).unwrap())
    }

    pub fn until_char(&mut self, c: char, inclusive: bool) -> &'input str {
        self.until_char_is(|char| char == c, inclusive)
    }
    pub fn until_char_is(
        &mut self,
        stop_at: impl Fn(char) -> bool,
        inclusive: bool,
    ) -> &'input str {
        let start = self.cursor;
        for char in self.tail().chars() {
            if stop_at(char) {
                if inclusive {
                    self.cursor += 1;
                }
                break;
            } else {
                self.cursor += 1;
            }
        }
        &self.txt[start..self.cursor]
    }

    pub fn dquote_str(&mut self) -> Res<&'input str> {
        // log::trace!(
        //     "[dquote_str] tail: `{}`",
        //     self.tail().lines().next().unwrap()
        // );
        self.raw_tag("\"")?;
        let inner = self.until_char('"', false);
        self.raw_tag("\"")?;
        Ok(inner)
    }
}

/// ## Low-level XML parsers
impl<'input> Parser<'input> {
    /// Parses an XML attribute of the form `<ident>\s*=\s*<double-quoted-string>`.
    pub fn xml_ident_attribute(&mut self) -> Res<(&'input str, &'input str)> {
        let ident = self.ident()?;
        self.ws();
        self.raw_tag("=")?;
        let val = self
            .dquote_str()
            .context(|| format!("parsing a value for xml attribute `{}`", ident))?;
        Ok((ident, val))
    }

    /// Parses an XML attribute of the form `<ident>\s*=\s*<double-quoted-string>`.
    pub fn xml_colon_ident_attribute(
        &mut self,
    ) -> Res<(SmallVec<[&'input str; 4]>, &'input str, &'input str)> {
        let mut pref = smallvec![];
        let mut ident = self.ident()?;
        'until_equal_sign: loop {
            self.ws();
            if self.try_raw_tag("=") {
                break 'until_equal_sign;
            }
            self.raw_tag(":")?;
            pref.push(ident);
            ident = self.ident()?
        }
        self.ws();
        let val = self
            .dquote_str()
            .context(|| format!("parsing a value for xml attribute `{}`", ident))?;
        Ok((pref, ident, val))
    }

    /// Parses an XML attribute of the form `<ident>\s*=\s*<double-quoted-string>`.
    pub fn named_xml_attribute(&mut self, name: impl AsRef<str>) -> Res<&'input str> {
        let name = name.as_ref();
        self.tag(name)?;
        self.ws();
        self.raw_tag("=")?;
        let val = self
            .dquote_str()
            .context(|| format!("parsing a value for xml attribute `{}`", name))?;
        Ok(val)
    }
}

/// Helper macro to streamline tedious parsing stuff.
macro_rules! parse {
    (
        $slf:ident . attributes for $desc:literal until($stop:expr) $(
            $name:ident = $( [$($key_pref:ident),* $(,)?] )? $key:ident
                $(.map |$val:ident| $map:expr,)?
                $(.ok_or_else $err:expr,)?
        )+
    ) => {
        $( let mut $name = None; )*

        'work: loop {
            if $stop {
                break 'work;
            }

            let (key_pref, key, val) = $slf.xml_colon_ident_attribute()?;
            $slf.ws();
            match (&*key_pref, key) {
                $(
                    (
                        [
                            $($(stringify!($key_pref),)*)?
                        ],
                        stringify!($key)
                    ) => {
                        $slf.handle_redef(
                            concat!($desc, " attribute"),
                            stringify!($name),
                            $name.as_ref(),
                            val
                        )?;
                        $(
                            let val = {
                                let $val = val;
                                $map
                            };
                        )?
                        $name = Some(val);
                    }
                )+
                _ => {
                    let mut key = key.to_string();
                    for pref in key_pref.iter().rev() {
                        key = format!("{pref}:{key}");
                    }
                    let mut help = format!("expected one of");
                    $(
                        help.push_str(
                            concat!(
                                " `",
                                $($(stringify!($key_pref), ":",)*)?
                                stringify!($key)
                                , "`"
                            )
                        );
                    )*
                    return Err(
                        error!(@unexpected(concat!($desc, " attribute")) key)
                            .with_context(help)
                    );
                }
            }
        }

        $(
            let $name = $name
                $( .ok_or_else(|| $err)? )?
            ;
        )*

    }
}

/// ## Package parsing
impl<'input> Parser<'input> {
    pub fn at_path(&mut self, ctx: &mut PathCtx) -> Res<()> {
        'walk: loop {
            self.ws();
            if self.try_tag("<ecore:EPackage") {
                self.ws();
                self.enter_package(ctx)?;
                continue 'walk;
            } else if self.try_tag("<eClassifiers") {
                self.class(ctx)?;
                continue 'walk;
            }

            if self.at_eoi() {
                break 'walk Ok(());
            }
            // not a package, not a class, not done, only legal thing is package closer goes up the
            // current package
            self.package_closer(ctx)?;
            self.ws();
        }
    }

    pub fn enter_package(&mut self, ctx: &mut PathCtx) -> Res<()> {
        parse! {
            self.attributes for "package" until( self.try_raw_tag(">") )
                name = name
                    .map |s| s.to_string(),
                    .ok_or_else error!(@unexpected("package") "with no name"),
                _version = [xmi] version
                _xmi = [xmlns] xmi
                _xsi = [xmlns] xsi
                _type = [xmlns] ecore
        }
        ctx.add_and_enter_sub_pack_mut(name)?;
        Ok(())
    }

    pub fn package_closer(&mut self, ctx: &mut PathCtx) -> Res<()> {
        if self.try_raw_tag("</ecore:EPackage>") {
            ctx.enter_sup_pack()?;
            Ok(())
        } else {
            log::error!("|==[package_closer] failure");
            log::error!("| tail:");
            for line in self.tail().lines().take(2) {
                log::error!("| `{line}`")
            }
            log::error!("|==|");
            bail!("expected package, type, or package closer")
        }
    }
}

/// ## Class parsing
impl<'input> Parser<'input> {
    pub fn class(&mut self, ctx: &mut PathCtx) -> Res<()> {
        let (mut typ, mut name, mut inst_name, mut is_abstract, mut is_interface, mut sup_typs) =
            (None, None, None, None, None, None);
        // operations XML tags can be closed directly with `/>`, or have parameters and end with
        // `</eOperations>`; this flag indicates the former
        let mut early_done = false;

        'attributes: loop {
            self.ws();
            if self.try_raw_tag(">") {
                break 'attributes;
            } else if self.try_raw_tag("/>") {
                early_done = true;
                break 'attributes;
            }

            let (key_pref, key, val) = self.xml_colon_ident_attribute()?;

            match (&*key_pref, key) {
                ([], "name") => {
                    self.handle_redef("class attribute", "name", name.as_ref(), val)?;
                    name = Some(val)
                }
                ([], "instanceTypeName") => {
                    self.handle_redef(
                        "class attribute",
                        "instanceTypeName",
                        inst_name.as_ref(),
                        val,
                    )?;
                    inst_name = Some(val)
                }
                ([], "interface") => {
                    // TODO: factor bool/int/... value parsing outta here
                    let is_int = match val {
                        "true" => true,
                        "false" => false,
                        _ => {
                            return Err(error!(@unexpected("boolean value") val).with_context(
                                format!("failed to parse value of class attribute `{key}`"),
                            ))
                        }
                    };
                    self.handle_redef("class attribute", "interface", is_interface.as_ref(), key)?;
                    is_interface = Some(is_int)
                }
                ([], "abstract") => {
                    // TODO: factor bool/int/... value parsing outta here
                    let is_abs = match val {
                        "true" => true,
                        "false" => false,
                        _ => {
                            return Err(error!(@unexpected("boolean value") val).with_context(
                                format!("failed to parse value of class attribute `{key}`"),
                            ))
                        }
                    };
                    self.handle_redef("class attribute", "abstract", is_abstract.as_ref(), key)?;
                    is_abstract = Some(is_abs)
                }
                ([], "eSuperTypes") => {
                    if let Some(sup_typs) = sup_typs.as_ref() {
                        log::warn!(
                            "XML-level class attribute redefinition for `eSuperTypes` from `{}` to `{}`",
                            sup_typs,
                            val,
                        );
                    }
                    sup_typs = Some(val);
                }
                (["xsi"], "type") => {
                    if let Some(typ) = typ.as_ref() {
                        log::warn!(
                            "XML-level class attribute redefinition for `xsi:type` from `{}` to `{}`",
                            typ,
                            val,
                        );
                    }
                    typ = Some(val);
                }
                _ => {
                    let mut att = key.to_string();
                    for pref in key_pref.iter().rev() {
                        att = format!("{pref}:{att}");
                    }
                    bail!(@unexpected("`eClassifiers` attribute") att)
                }
            }
        }

        let name = name.ok_or_else(|| error!(@unexpected("`eClassifier`") "with no name"))?;
        let typ =
            typ.ok_or_else(|| error!("`eClassifier` named `{}` does not specify its type", name))?;

        #[allow(unused_mut)]
        let mut class_ctx = ctx.enter_class(typ, name, inst_name, is_abstract, is_interface)?;

        if !early_done {
            // log::debug!("parsing content of class `{}`", class_ctx.current().name());
            self.class_content(&mut class_ctx)
                .context(|| format!("failed to parse class `{}`", class_ctx.current().name()))?;
        }

        if let Some(sup_typs) = sup_typs {
            for sup_typ in sup_typs.split(" ").filter_map(|bit| {
                let bit = bit.trim();
                if bit.is_empty() {
                    None
                } else {
                    Some(bit)
                }
            }) {
                let sup_idx = class_ctx.resolve_etype(sup_typ)?;
                class_ctx.add_sup_class(sup_idx);
            }
        }

        class_ctx.finalize();

        Ok(())
    }

    pub fn class_content(&mut self, ctx: &mut ClassCtx) -> Res<()> {
        'content: loop {
            self.ws();

            if self.try_raw_tag("</eClassifiers>") {
                // log::debug!("parsing class end for `{}`", ctx.current().name());
                break 'content;
            }

            if self.try_tag("<eAnnotations") {
                self.ws();
                let annot = self
                    .annotation()
                    .with_context("failed to parse class annotation")?;
                ctx.add_annotation(annot);
                continue 'content;
            } else if self.try_tag("<eOperations") {
                self.ws();
                let op = self
                    .class_operation(ctx)
                    .with_context("failed to parse class operation")?;
                ctx.add_operation(op);
            } else if self.try_tag("<eLiterals") {
                self.ws();
                let lit = self
                    .class_literal()
                    .with_context("failed to parse class literal")?;
                ctx.add_literal(lit);
            } else if self.try_tag("<eStructuralFeatures") {
                self.ws();
                let structural = self
                    .class_structural(ctx)
                    .with_context("failed to parse structural features")?;
                // log::info!("done parsing structural");
                ctx.add_structural(structural);
            } else {
                bail!("unexpected class content")
            }
        }
        Ok(())
    }

    /// Parses everything **after** a `<eAnnotations` until a `</eAnnotations>`.
    ///
    /// Expects no leading whitespaces, as all parsers do except for the top-level one.
    pub fn annotation(&mut self) -> Res<repr::Annot> {
        let source = self.named_xml_attribute("source")?;
        self.ws();
        self.tag(">")?;
        let mut annot = repr::Annot::with_capacity(source, 3);

        // log::debug!("|==| post source:");
        // self.debug_show_tail_n(2, "| ");

        // parse `<details
        'details: loop {
            self.ws();

            // done with this annotation?
            if self.try_tag("</eAnnotations>") {
                break 'details;
            }

            // parse `<details key="..." value="..."/>`
            {
                self.tag("<details")?;
                self.ws();

                let (att1, val1) = self.xml_ident_attribute()?;
                match att1 {
                    "key" => {
                        self.ws();
                        let (att2, val2) = self.xml_ident_attribute()?;
                        match att2 {
                            "value" => annot.insert(val1, val2)?,
                            _ => bail!("expected `value` attribute, found `{}`", att2),
                        }
                    }
                    _ => bail!("expected `key` attribute, found `{}`", att1),
                }

                self.ws();
                self.tag("/>")?
            }
        }

        annot.shrink_to_fit();
        Ok(annot)
    }

    pub fn class_literal(&mut self) -> Res<repr::ELit> {
        let (mut name, mut value): (Option<&str>, Option<&str>) = (None, None);

        'inner: loop {
            if self.try_raw_tag("/>") {
                break 'inner;
            }
            let (key, val) = self.xml_ident_attribute()?;
            match key {
                "name" => {
                    self.handle_redef("class literal", "name", name.as_ref(), val)?;
                    name = Some(val);
                }
                "value" => {
                    self.handle_redef("class literal", "value", value.as_ref(), val)?;
                    value = Some(val);
                }
                _ => bail!(@unexpected("class literal attribute") key),
            }
            self.ws();
        }

        if let Some(name) = name {
            Ok(repr::ELit::new(name, value))
        } else {
            bail!(@unexpected("class literal") "with no name")
        }
    }

    pub fn class_parameter(&mut self, ctx: &mut ClassCtx) -> Res<repr::Param> {
        let (mut name, mut lbound, mut ubound, mut typ) = (None, None, None, None);
        '_attributes: while !self.try_raw_tag("/>") {
            let (key, val) = self.xml_ident_attribute()?;
            match key {
                "name" => {
                    self.handle_redef("parameter name", "name", name.as_ref(), val)?;
                    name = Some(val);
                }
                "lowerBound" => {
                    self.handle_redef("parameter lower bound", "lowerBound", lbound.as_ref(), val)?;
                    lbound = Some(val);
                }
                "upperBound" => {
                    self.handle_redef("parameter upper bound", "upperBound", ubound.as_ref(), val)?;
                    ubound = Some(val);
                }
                "eType" => {
                    self.handle_redef("parameter type", "eType", typ.as_ref(), val)?;
                    typ = Some(val);
                }
                _ => {
                    bail!(@unexpected("parameter attribute key") key)
                }
            }
            self.ws();
        }

        let name = name.ok_or_else(|| error!(@unexpected("class parameter") "with no name"))?;
        let typ = {
            let etyp = typ.ok_or_else(
                || error!(@unexpected(format!("class parameter `{name}`")) "with no type"),
            )?;
            ctx.resolve_etype(etyp)?
        };
        let bounds = repr::Bounds::from_str(lbound, ubound)
            .context(|| format!("illegal bounds for parameter `{name}`"))?;

        Ok(repr::Param::new(name, bounds, typ))
    }

    pub fn class_operation(&mut self, ctx: &mut ClassCtx) -> Res<repr::Operation> {
        let (mut name, mut typ) = (None, None);
        // operations XML tags can be closed directly with `/>`, or have parameters and end with
        // `</eOperations>`; this flag indicates the former
        let mut early_done = false;

        'attributes: loop {
            let (key, val) = self.xml_ident_attribute()?;
            match key {
                "name" => {
                    self.handle_redef("operation name", "name", name.as_ref(), val)?;
                    name = Some(val);
                }
                "eType" => {
                    self.handle_redef("operation type", "eType", typ.as_ref(), val)?;
                    typ = Some(val);
                }
                _ => bail!(@unexpected("operation attribute") key),
            }

            self.ws();

            if self.try_raw_tag("/>") {
                early_done = true;
                break 'attributes;
            } else if self.try_raw_tag(">") {
                break 'attributes;
            }
        }

        let name = name.ok_or_else(|| error!(@unexpected("`eOperation`") "with no name"))?;

        let typ = if let Some(typ) = typ {
            Some(ctx.resolve_etype(typ)?)
        } else {
            None
        };

        let mut operation = repr::Operation::new(name, typ);

        if !early_done {
            self.ws();

            while !self.try_raw_tag("</eOperations>") {
                self.tag("<eParameters")?;
                self.ws();
                let param = self.class_parameter(ctx)?;
                operation.add_parameter(param);
                self.ws();
            }
        }

        Ok(operation)
    }

    pub fn class_structural(&mut self, ctx: &mut ClassCtx) -> Res<repr::Structural> {
        let (
            mut typ,
            mut name,
            mut lbound,
            mut ubound,
            mut etype,
            mut opposite,
            mut containment,
            mut is_id,
        ) = (None, None, None, None, None, None, None, None);

        'attributes: loop {
            let (pref, key, val) = self.xml_colon_ident_attribute()?;
            match (&*pref, key) {
                ([], "name") => {
                    self.handle_redef("class", "name", name.as_ref(), val)?;
                    name = Some(val);
                }
                (["xsi"], "type") => {
                    self.handle_redef("class", "xsi:type", typ.as_ref(), val)?;
                    typ = Some(val);
                }
                ([], "lowerBound") => {
                    self.handle_redef("class", "lowerBound", lbound.as_ref(), val)?;
                    lbound = Some(val);
                }
                ([], "upperBound") => {
                    self.handle_redef("class", "upperBound", ubound.as_ref(), val)?;
                    ubound = Some(val);
                }
                ([], "eType") => {
                    self.handle_redef("class", "eType", etype.as_ref(), val)?;
                    etype = Some(val);
                }
                ([], "eOpposite") => {
                    self.handle_redef("class", "eOpposite", opposite.as_ref(), val)?;
                    opposite = Some(val);
                }
                ([], "containment") => {
                    self.handle_redef("class", "containment", containment.as_ref(), val)?;
                    containment = Some(val);
                }
                ([], "iD") => {
                    self.handle_redef("class", "iD", is_id.as_ref(), val)?;
                    is_id = Some(val);
                }
                _ => bail!(@unexpected("structural feature attribute") key),
            }

            self.ws();

            if self.try_raw_tag("/>") {
                break 'attributes;
            }
        }

        let name =
            name.ok_or_else(|| error!("illegal structural feature, `name` attribut is missing"))?;
        let typ = repr::structural::Typ::from_xsi_type(typ.as_ref().ok_or_else(|| {
            error!(
                "missing attribute `xsi:type` in structural feature `{}`",
                name
            )
        })?)?;
        let etype = if let Some(etype) = etype {
            ctx.resolve_etype(etype)?
        } else {
            bail!("missing attribute `eType` in structural feature `{}`", name);
        };

        let bounds = typ.parse_bounds(lbound, ubound).context(|| {
            format!(
                "failed to parse `lowerBound`/`upperBound` of  structural feature `{}`",
                name,
            )
        })?;

        let mut structural = repr::Structural::new(name, typ, etype, bounds);

        if let Some(containment) = containment {
            structural.set_containment(helpers::bool(containment)?);
        }
        if let Some(is_id) = is_id {
            structural.set_is_id(helpers::bool(is_id)?);
        }

        if opposite.is_some() {
            log::warn!("`eOpposite` attributes are currently not supported, ignoring")
        }

        Ok(structural)
    }
}