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
use super::{
    combinator::*, entity::*, expression::*, identifier::*, stmt::*, subsuper::*, types::*,
};
use crate::ast::*;

/// 296 schema_decl = SCHEMA [schema_id] \[ schema_version_id \] `;` [schema_body] END_SCHEMA `;` .
pub fn schema_decl(input: &str) -> ParseResult<Schema> {
    // FIXME schema_version_id
    let schema_head =
        tuple((tag("SCHEMA "), schema_id, char(';'))).map(|(_start, id, _semicolon)| id);
    tuple((schema_head, schema_body, tag("END_SCHEMA"), char(';')))
        .map(|(name, (interfaces, constants, decls), _end, _semicolon)| {
            let mut entities = Vec::new();
            let mut types = Vec::new();
            let mut functions = Vec::new();
            let mut procedures = Vec::new();
            let mut rules = Vec::new();
            let mut subtype_constraints = Vec::new();

            for decl in decls {
                match decl {
                    Declaration::Entity(e) => entities.push(e),
                    Declaration::Type(ty) => types.push(ty),
                    Declaration::Function(f) => functions.push(f),
                    Declaration::Procedure(p) => procedures.push(p),
                    Declaration::Rule(r) => rules.push(r),
                    Declaration::SubTypeConstraint(sub) => subtype_constraints.push(sub),
                }
            }

            Schema {
                name,
                entities,
                types,
                functions,
                procedures,
                rules,
                constants,
                interfaces,
                subtype_constraints,
            }
        })
        .parse(input)
}

/// 295 schema_body = { [interface_specification] } \[ [constant_decl] \] { [declaration] | [rule_decl] } .
pub fn schema_body(
    input: &str,
) -> ParseResult<(Vec<InterfaceSpec>, Vec<Constant>, Vec<Declaration>)> {
    tuple((
        many0(interface_specification),
        opt(constant_decl).map(|opt| opt.unwrap_or_default()),
        many0(alt((declaration, rule_decl.map(Declaration::Rule)))),
    ))
    .parse(input)
}

/// 199 declaration = [entity_decl] | [function_decl] | [procedure_decl] | [subtype_constraint_decl] | [type_decl] .
pub fn declaration(input: &str) -> ParseResult<Declaration> {
    alt((
        entity_decl.map(Declaration::Entity),
        type_decl.map(Declaration::Type),
        function_decl.map(Declaration::Function),
        procedure_decl.map(Declaration::Procedure),
        subtype_constraint_decl.map(Declaration::SubTypeConstraint),
    ))
    .parse(input)
}

/// 271 procedure_decl = [procedure_head] [algorithm_head] { [stmt] } END_PROCEDURE `;` .
pub fn procedure_decl(input: &str) -> ParseResult<Procedure> {
    tuple((
        procedure_head,
        algorithm_head,
        many0(stmt),
        tag("END_PROCEDURE"),
        char(';'),
    ))
    .map(
        |(
            (name, parameters),
            (declarations, constants, variables),
            statements,
            _end,
            _semicolon,
        )| Procedure {
            name,
            parameters,
            declarations,
            constants,
            variables,
            statements,
        },
    )
    .parse(input)
}

/// 272 procedure_head = PROCEDURE [procedure_id]
///                    \[ `(`
///                      \[ VAR \] [formal_parameter] { `;`
///                      \[ VAR \] [formal_parameter]
///                    }
///                    `)` \] `;` .
pub fn procedure_head(input: &str) -> ParseResult<(String, Vec<FormalParameter>)> {
    let param = tuple((opt(tag("VAR")), formal_parameter)).map(|(var, mut params)| {
        for mut param in &mut params {
            param.is_variable = var.is_some();
        }
        params
    });
    tuple((
        tag("PROCEDURE"),
        procedure_id,
        opt(
            tuple((char('('), semicolon_separated(param), char(')'))).map(
                |(_open, params, _close)| {
                    params.into_iter().flat_map(|ps| ps.into_iter()).collect()
                },
            ),
        )
        .map(|opt| opt.unwrap_or_default()),
        char(';'),
    ))
    .map(|(_procedure, name, parameters, _semicolon)| (name, parameters))
    .parse(input)
}

/// 220 function_decl = [function_head] [algorithm_head] [stmt] { [stmt] } END_FUNCTION `;` .
pub fn function_decl(input: &str) -> ParseResult<Function> {
    tuple((
        function_head,
        algorithm_head,
        many1(stmt),
        tag("END_FUNCTION"),
        char(';'),
    ))
    .map(
        |(
            (name, parameters, return_type),
            (declarations, constants, variables),
            statements,
            _end,
            _semicolon,
        )| Function {
            name,
            parameters,
            declarations,
            constants,
            variables,
            statements,
            return_type,
        },
    )
    .parse(input)
}

/// 221 function_head = FUNCTION [function_id]
///                   \[ `(` [formal_parameter] { `;` [formal_parameter] } `)` \]
///                   `:` [parameter_type] `;` .
pub fn function_head(input: &str) -> ParseResult<(String, Vec<FormalParameter>, Type)> {
    tuple((
        tag("FUNCTION"),
        function_id,
        opt(
            tuple((char('('), semicolon_separated(formal_parameter), char(')'))).map(
                |(_open, params, _close)| {
                    params.into_iter().flat_map(|ps| ps.into_iter()).collect()
                },
            ),
        )
        .map(|opt| opt.unwrap_or_default()),
        char(':'),
        parameter_type,
        char(';'),
    ))
    .map(|(_function, name, parameters, _comma, ty, _semicolon)| (name, parameters, ty))
    .parse(input)
}

/// 218 formal_parameter = [parameter_id] { `,` [parameter_id] } `:` [parameter_type] .
pub fn formal_parameter(input: &str) -> ParseResult<Vec<FormalParameter>> {
    tuple((comma_separated(parameter_id), char(':'), parameter_type))
        .map(|(names, _comma, ty)| {
            names
                .into_iter()
                .map(|name| FormalParameter {
                    name,
                    ty: ty.clone(),
                    is_variable: false,
                })
                .collect()
        })
        .parse(input)
}

/// 195 constant_decl = CONSTANT [constant_body] { [constant_body] } END_CONSTANT `;` .
pub fn constant_decl(input: &str) -> ParseResult<Vec<Constant>> {
    tuple((
        tag("CONSTANT"),
        many1(constant_body),
        tag("END_CONSTANT"),
        char(';'),
    ))
    .map(|(_constant, consts, _end, _semicolon)| consts)
    .parse(input)
}

/// 194 constant_body = [constant_id] `:` [instantiable_type] `:=` [expression] `;` .
pub fn constant_body(input: &str) -> ParseResult<Constant> {
    tuple((
        constant_id,
        char(':'),
        instantiable_type,
        tag(":="),
        expression,
        char(';'),
    ))
    .map(|(name, _colon, ty, _def, expr, _semicolon)| Constant { name, ty, expr })
    .parse(input)
}

/// 291 rule_decl = [rule_head] [algorithm_head] { [stmt] } [where_clause] END_RULE `;` .
pub fn rule_decl(input: &str) -> ParseResult<Rule> {
    tuple((
        rule_head,
        algorithm_head,
        many0(stmt),
        where_clause,
        tag("END_RULE"),
        char(';'),
    ))
    .map(
        |(
            (name, references),
            (declarations, constants, variables),
            statements,
            where_clause,
            _end,
            _semicolon,
        )| Rule {
            name,
            references,
            declarations,
            constants,
            variables,
            statements,
            where_clause,
        },
    )
    .parse(input)
}

/// 292 rule_head = RULE [rule_id] FOR `(` [entity_ref] { `,` [entity_ref] } `)` `;` .
pub fn rule_head(input: &str) -> ParseResult<(String, Vec<String>)> {
    tuple((
        tag("RULE"),
        rule_id,
        tag("FOR"),
        char('('),
        comma_separated(entity_ref),
        char(')'),
        char(';'),
    ))
    .map(|(_rule, name, _for, _open, references, _close, _semicolon)| (name, references))
    .parse(input)
}

/// 173 algorithm_head = { [declaration] } \[ [constant_decl] \] \[ [local_decl] \] .
pub fn algorithm_head(
    input: &str,
) -> ParseResult<(Vec<Declaration>, Vec<Constant>, Vec<LocalVariable>)> {
    tuple((
        many0(declaration),
        opt(constant_decl).map(|opt| opt.unwrap_or_default()),
        opt(local_decl).map(|opt| opt.unwrap_or_default()),
    ))
    .parse(input)
}

/// 252 local_decl = LOCAL [local_variable] { [local_variable] } END_LOCAL `;` .
pub fn local_decl(input: &str) -> ParseResult<Vec<LocalVariable>> {
    tuple((
        tag("LOCAL"),
        many1(local_variable),
        tag("END_LOCAL"),
        char(';'),
    ))
    .map(|(_local, vars, _end, _semicolon)| {
        vars.into_iter().flat_map(|var| var.into_iter()).collect()
    })
    .parse(input)
}

/// 253 local_variable = [variable_id] { `,` [variable_id] } `:` [parameter_type] \[ `:=` [expression] \] `;` .
pub fn local_variable(input: &str) -> ParseResult<Vec<LocalVariable>> {
    tuple((
        comma_separated(variable_id),
        char(':'),
        parameter_type,
        opt(tuple((tag(":="), expression)).map(|(_def, expr)| expr)),
        char(';'),
    ))
    .map(|(names, _comma, ty, expr, _semicolon)| {
        names
            .into_iter()
            .map(|name| LocalVariable {
                name,
                ty: ty.clone(),
                expr: expr.clone(),
            })
            .collect()
    })
    .parse(input)
}

/// 242 interface_specification = [reference_clause] | [use_clause] .
pub fn interface_specification(input: &str) -> ParseResult<InterfaceSpec> {
    alt((reference_clause, use_clause)).parse(input)
}

/// 281 reference_clause = REFERENCE FROM [schema_ref] \[ `(` [resource_or_rename] { `,` [resource_or_rename] } `)` \] `;` .
pub fn reference_clause(input: &str) -> ParseResult<InterfaceSpec> {
    tuple((
        tag("REFERENCE"),
        tag("FROM"),
        schema_ref,
        opt(
            tuple((char('('), comma_separated(resource_or_rename), char(')')))
                .map(|(_open, ty, _close)| ty),
        )
        .map(|opt| opt.unwrap_or_default()),
        char(';'),
    ))
    .map(|(_use, _from, name, resources, _semicolon)| InterfaceSpec::Reference { name, resources })
    .parse(input)
}

/// 288 resource_or_rename = [resource_ref] \[ AS [rename_id] \] .
pub fn resource_or_rename(input: &str) -> ParseResult<(String, Option<String>)> {
    tuple((
        resource_ref,
        opt(tuple((tag("AS"), rename_id)).map(|(_as, rename)| rename)),
    ))
    .parse(input)
}

/// 336 use_clause = USE FROM [schema_ref]
///                \[ `(` [named_type_or_rename] { `,` [named_type_or_rename] } `)`
///                \] `;` .
pub fn use_clause(input: &str) -> ParseResult<InterfaceSpec> {
    tuple((
        tag("USE"),
        tag("FROM"),
        schema_ref,
        opt(
            tuple((char('('), comma_separated(named_type_or_rename), char(')')))
                .map(|(_open, ty, _close)| ty),
        )
        .map(|opt| opt.unwrap_or_default()),
        char(';'),
    ))
    .map(|(_use, _from, name, types, _semicolon)| InterfaceSpec::Use { name, types })
    .parse(input)
}

/// 259 named_type_or_rename = [named_types] \[ AS ( [entity_id] | [type_id] ) \] .
pub fn named_type_or_rename(input: &str) -> ParseResult<(String, Option<String>)> {
    tuple((
        named_types,
        opt(tuple((tag("AS"), alt((entity_id, type_id)))).map(|(_as, id)| id)),
    ))
    .parse(input)
}

#[cfg(test)]
mod tests {
    use super::*;
    use nom::Finish;

    #[test]
    fn schema() {
        let exp_str = r#"
        SCHEMA my_first_schema;
          ENTITY first;
            m_ref : second;
            fattr : STRING;
          END_ENTITY;

          ENTITY second;
            sattr : STRING;
          END_ENTITY;
        END_SCHEMA;
        "#
        .trim();

        let (residual, (schema, _remark)) = super::schema_decl(exp_str).finish().unwrap();
        assert_eq!(schema.name, "my_first_schema");
        assert_eq!(schema.entities.len(), 2);
        assert_eq!(
            schema.entities[0],
            entity_decl(
                r#"
                ENTITY first;
                  m_ref : second;
                  fattr : STRING;
                END_ENTITY;
                "#
                .trim()
            )
            .finish()
            .unwrap()
            .1
             .0
        );
        assert_eq!(
            schema.entities[1],
            entity_decl(
                r#"
                ENTITY second;
                  sattr : STRING;
                END_ENTITY;
                "#
                .trim()
            )
            .finish()
            .unwrap()
            .1
             .0
        );
        assert_eq!(residual, "");
    }

    #[test]
    fn constant() {
        let exp_str = r#"
        CONSTANT
            dummy_gri : geometric_representation_item := representation_item('') || geometric_representation_item();
            dummy_tri : topological_representation_item := representation_item('') || topological_representation_item();
        END_CONSTANT;
        "#
        .trim();
        let (residual, (local, _remark)) = super::constant_decl(exp_str).finish().unwrap();
        dbg!(&local);
        assert_eq!(residual, "");
    }

    #[test]
    fn local1() {
        // From ISO-10303-11 p.72
        let exp_str = r#"
        LOCAL
            r_result : REAL := 0.0;
            i_result : INTEGER;
        END_LOCAL;
        "#
        .trim();
        let (residual, (local, _remark)) = super::local_decl(exp_str).finish().unwrap();
        dbg!(&local);
        assert_eq!(residual, "");
    }

    #[test]
    fn local2() {
        // Part of rule1
        let exp_str = r#"
        LOCAL
            first_oct ,
            seventh_oct : SET OF point := []; -- empty set of point (see 12.9)
        END_LOCAL;
        "#
        .trim();
        let (residual, (local, _remark)) = super::local_decl(exp_str).finish().unwrap();
        dbg!(&local);
        assert_eq!(residual, "");
    }

    #[test]
    fn rule1() {
        // From ISO-10303-11 p.73
        let exp_str = r#"
        RULE point_match FOR (point);
        LOCAL
            first_oct ,
            seventh_oct : SET OF point := []; -- empty set of point (see 12.9), change `POINT` -> `point`
        END_LOCAL;
            first_oct := QUERY(temp <* point | (temp.x > 0) AND
                (temp.y > 0) AND
                (temp.z > 0) );
            seventh_oct := QUERY(temp <* point | (temp.x < 0) AND
                (temp.y < 0) AND
                (temp.z < 0) );
        WHERE
            SIZEOF(first_oct) = SIZEOF(seventh_oct);
        END_RULE;
        "#
        .trim();
        let (residual, (rule, _remark)) = super::rule_decl(exp_str).finish().unwrap();
        dbg!(&rule);
        assert_eq!(residual, "");
    }

    #[test]
    fn rule2() {
        // From ISO-10303-11 p.73
        let exp_str = r#"
        RULE vu FOR (b);
            ENTITY temp;
                a1 : c;
                a2 : d;
            END_ENTITY;
        LOCAL
            s : SET OF temp := [];
        END_LOCAL;
        REPEAT i := 1 TO SIZEOF(b);
            s := s + temp(b[i].a1, b[i].a2);
        END_REPEAT;
        WHERE
            wr1 : VALUE_UNIQUE(s);
        END_RULE;
        "#
        .trim();
        let (residual, (rule, _remark)) = super::rule_decl(exp_str).finish().unwrap();
        dbg!(&rule);
        assert_eq!(residual, "");
    }

    #[test]
    fn formal_parameter1() {
        let (residual, (p, _remark)) = super::formal_parameter("input : AGGREGATE:intype OF REAL")
            .finish()
            .unwrap();
        dbg!(&p);
        assert_eq!(residual, "");
    }

    #[test]
    fn formal_parameter2() {
        let (residual, (p, _remark)) = super::formal_parameter("a,b: GENERIC:intype")
            .finish()
            .unwrap();
        dbg!(&p);
        assert_eq!(residual, "");
    }

    #[test]
    fn function_aggregate() {
        // From ISO-10303-11 p.66-67
        let exp_str = r#"
        FUNCTION scale(input : AGGREGATE:intype OF REAL; scalar: REAL): AGGREGATE:intype OF REAL;
            LOCAL
                result : AGGREGATE:intype OF REAL := input;
            END_LOCAL;
            IF SIZEOF(['BAG','SET'] * TYPEOF(input)) > 0 THEN
                REPEAT i := LOINDEX(input) TO HIINDEX(input);
                    result := result - input[i];              -- remove the original
                    result := result + scalar*input[i];       -- insert the scaled
                END_REPEAT;
            ELSE
                REPEAT i := LOINDEX(input) TO HIINDEX(input);
                    result[i] := scalar*input[i];
                END_REPEAT;
            END_IF;
            RETURN(result);
        END_FUNCTION;
        "#
        .trim();
        let (residual, (rule, _remark)) = super::function_decl(exp_str).finish().unwrap();
        dbg!(&rule);
        assert_eq!(residual, "");
    }

    #[test]
    fn function_generic() {
        // From ISO-10303-11 p.67-68
        let exp_str = r#"
        FUNCTION add(a,b: GENERIC:intype): GENERIC:intype;
            LOCAL
                nr : NUMBER; -- integer or real
                vr : vector;
            END_LOCAL;
            IF ('NUMBER' IN TYPEOF(a)) AND ('NUMBER' IN TYPEOF(b)) THEN
                nr := a+b;
                RETURN(nr);
            ELSE
                IF ('THIS_SCHEMA.VECTOR' IN TYPEOF(a)) AND ('THIS_SCHEMA.VECTOR' IN TYPEOF(b)) THEN
                    vr := vector(a.i + b.i,
                    a.j + b.j,
                    a.k + b.k);
                    RETURN(vr);
                END_IF;
            END_IF;
            RETURN (?); --"add" if we receive input that is invalid, return a no-value
        END_FUNCTION;
        "#
        .trim();
        let (residual, (rule, _remark)) = super::function_decl(exp_str).finish().unwrap();
        dbg!(&rule);
        assert_eq!(residual, "");
    }

    #[test]
    fn function_generic_entity() {
        // From ISO-10303-11 p.68
        let exp_str = r#"
        FUNCTION check_relating (type1 : instance_of_type_1;
                                 type2 : instance_of_type_2;
                                 sample : GENERIC_ENTITY): BOOLEAN;
            RETURN ((type1 IN USEDIN(sample, '')) AND (type2 IN USEDIN(sample, '')));
        END_FUNCTION;
        "#
        .trim();
        let (residual, (rule, _remark)) = super::function_decl(exp_str).finish().unwrap();
        dbg!(&rule);
        assert_eq!(residual, "");
    }

    #[test]
    fn function_ap201_bag_to_set() {
        // From AP201
        let exp_str = r#"
        FUNCTION bag_to_set (the_bag : BAG OF GENERIC : intype) : SET OF GENERIC : intype;
            LOCAL
                the_set: SET OF GENERIC : intype := [];
                i      : INTEGER;
            END_LOCAL;
            IF SIZEOF (the_bag) > 0 THEN
                REPEAT i := 1 TO HIINDEX (the_bag);
                    the_set := the_set + the_bag [i];
                END_REPEAT;
            END_IF;
            RETURN (the_set);
        END_FUNCTION;
        "#
        .trim();
        let (residual, (rule, _remark)) = super::function_decl(exp_str).finish().unwrap();
        dbg!(&rule);
        assert_eq!(residual, "");
    }

    #[test]
    fn function_ap201_valid_calendar_date() {
        // From AP201
        let exp_str = r#"
        FUNCTION valid_calendar_date (date : calendar_date) : LOGICAL;
            IF NOT ({1 <= date.day_component <= 31}) THEN
                RETURN(FALSE);
            END_IF;
            CASE date.month_component OF
                4         : RETURN({ 1<= date.day_component <= 30});
                6         : RETURN({ 1<= date.day_component <= 30});
                9         : RETURN({ 1<= date.day_component <= 30});
                11        : RETURN({ 1<= date.day_component <= 30});
                2         : 
                    BEGIN
                        IF (leap_year(date.year_component)) THEN
                            RETURN({ 1<= date.day_component <= 29});
                        ELSE
                            RETURN({ 1<= date.day_component <= 28});
                        END_IF;
                    END;
                OTHERWISE : RETURN(TRUE);
            END_CASE;
        END_FUNCTION;
        "#
        .trim();
        let (residual, (rule, _remark)) = super::function_decl(exp_str).finish().unwrap();
        dbg!(&rule);
        assert_eq!(residual, "");
    }
}