Skip to main content

reform/
id.rs

1use num_traits::One;
2use num_traits::Zero;
3use number::Number;
4use std::fmt;
5use std::mem;
6use structure::{
7    BorrowedVarInfo, Element, FunctionAttributes, IdentityStatement, IdentityStatementMode,
8    ReplaceResult, StatementResult, VarName,
9};
10use tools::{is_number_in_range, SliceRef};
11
12pub const MAXMATCH: usize = 1_000_000; // maximum number of matches
13
14#[derive(Debug, Clone, Eq, PartialEq)]
15pub enum MatchOpt<'a> {
16    Single(&'a Element),
17    SingleOwned(Element),
18    Multiple(&'a [Element]),
19}
20
21#[derive(Debug, Clone, Eq, PartialEq)]
22pub enum MatchOptOwned {
23    Single(Element, bool), // bool is the changed flag
24    Multiple(Vec<Element>),
25}
26
27impl<'a> MatchOpt<'a> {
28    fn to_owned(&self) -> MatchOptOwned {
29        match *self {
30            MatchOpt::Single(x) => MatchOptOwned::Single(x.clone(), true),
31            MatchOpt::SingleOwned(ref x) => MatchOptOwned::Single(x.clone(), true),
32            MatchOpt::Multiple(x) => {
33                MatchOptOwned::Multiple(x.iter().map(|y| (*y).clone()).collect())
34            }
35        }
36    }
37}
38
39impl MatchOptOwned {
40    pub fn into_single(self) -> (Element, bool) {
41        match self {
42            MatchOptOwned::Single(x, c) => (x, c),
43            _ => panic!("Trying to get single element from a multiple"),
44        }
45    }
46}
47
48impl<'a> fmt::Display for MatchOpt<'a> {
49    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50        match *self {
51            MatchOpt::Single(x) => write!(f, "{}", x),
52            MatchOpt::SingleOwned(ref x) => write!(f, "{}", x),
53            MatchOpt::Multiple(x) => {
54                if let Some(u) = x.first() {
55                    write!(f, "{}", u)?
56                }
57                for u in x.iter().skip(1) {
58                    write!(f, ",{}", u)?;
59                }
60                write!(f, "")
61            }
62        }
63    }
64}
65
66// map of variables names to a function argument slice
67pub type MatchObject<'a> = Vec<(&'a VarName, MatchOpt<'a>)>;
68
69// push something to the match object, keeping track of the old length
70fn push_match<'a>(m: &mut MatchObject<'a>, k: &'a VarName, v: &'a Element) -> Option<usize> {
71    for &(rk, ref rv) in m.iter() {
72        if *rk == *k {
73            match *rv {
74                MatchOpt::Single(ref vv) if *v == **vv => return Some(m.len()),
75                MatchOpt::SingleOwned(ref vv) if v == vv => return Some(m.len()),
76                _ => return None,
77            }
78        }
79    }
80
81    m.push((k, MatchOpt::Single(v)));
82    Some(m.len() - 1)
83}
84
85// push something to the match object, keeping track of the old length
86fn push_match_owned<'a>(m: &mut MatchObject<'a>, k: &'a VarName, v: Element) -> Option<usize> {
87    for &(rk, ref rv) in m.iter() {
88        if *rk == *k {
89            match *rv {
90                MatchOpt::Single(ref vv) if v == **vv => return Some(m.len()),
91                MatchOpt::SingleOwned(ref vv) if v == *vv => return Some(m.len()),
92                _ => return None,
93            }
94        }
95    }
96
97    m.push((k, MatchOpt::SingleOwned(v)));
98    Some(m.len() - 1)
99}
100
101// push something to the match object, keeping track of the old length
102fn push_match_slice<'a>(
103    m: &mut MatchObject<'a>,
104    k: &'a VarName,
105    v: &'a [Element],
106) -> Option<usize> {
107    for &(rk, ref rv) in m.iter() {
108        if *rk == *k {
109            match *rv {
110                MatchOpt::Multiple(vv) if *v == *vv => return Some(m.len()),
111                _ => return None,
112            }
113        }
114    }
115
116    m.push((k, MatchOpt::Multiple(v)));
117    Some(m.len() - 1)
118}
119
120fn find_match<'a>(m: &'a MatchObject<'a>, k: &'a VarName) -> Option<&'a MatchOpt<'a>> {
121    for &(ref rk, ref rv) in m {
122        if **rk == *k {
123            return Some(rv);
124        }
125    }
126    None
127}
128
129// apply a mapping of wildcards to a function argument
130impl Element {
131    pub fn apply_map<'a>(&self, m: &MatchObject<'a>) -> MatchOptOwned {
132        match *self {
133            Element::VariableArgument(ref name) | Element::Wildcard(ref name, ..) => {
134                find_match(m, name)
135                    .expect("Unknown wildcard in rhs")
136                    .to_owned()
137            }
138            Element::FnWildcard(ref name, ref b) => {
139                let (ref restrictions, ref old_args) = **b;
140
141                if restrictions.len() > 0 {
142                    panic!("No restrictions allowed in the rhs");
143                }
144
145                let newname = match find_match(m, name)
146                    .expect("Unknown wildcard function in rhs")
147                    .to_owned()
148                    .into_single()
149                    .0
150                {
151                    Element::Var(n, _) => n,
152                    _ => unreachable!(),
153                };
154
155                let mut changed = false;
156                let mut args = Vec::with_capacity(old_args.len());
157                for a in old_args {
158                    match a.apply_map(m) {
159                        MatchOptOwned::Single(x, c) => {
160                            changed |= c;
161                            args.push(x)
162                        }
163                        MatchOptOwned::Multiple(x) => {
164                            changed = true;
165                            args.extend(x)
166                        }
167                    }
168                }
169
170                MatchOptOwned::Single(Element::Fn(changed, newname, args), changed)
171            }
172            Element::Pow(_, ref be) => {
173                let (ref b, ref e) = **be;
174                let mut changed = false;
175                let (bb, c) = b.apply_map(m).into_single();
176                changed |= c;
177                let (pp, c) = e.apply_map(m).into_single();
178                changed |= c;
179                MatchOptOwned::Single(Element::Pow(changed, Box::new((bb, pp))), changed)
180            }
181            Element::Comparison(_, ref be, ref cond) => {
182                let (ref b, ref e) = **be;
183                let mut changed = false;
184                let (bb, c) = b.apply_map(m).into_single();
185                changed |= c;
186                let (pp, c) = e.apply_map(m).into_single();
187                changed |= c;
188                MatchOptOwned::Single(
189                    Element::Comparison(changed, Box::new((bb, pp)), cond.clone()),
190                    changed,
191                )
192            }
193            Element::Fn(_, name, ref old_args) => {
194                let mut changed = false;
195                let mut args = Vec::with_capacity(old_args.len());
196                for a in old_args {
197                    match a.apply_map(m) {
198                        MatchOptOwned::Single(x, c) => {
199                            changed |= c;
200                            args.push(x)
201                        }
202                        MatchOptOwned::Multiple(x) => {
203                            changed = true;
204                            args.extend(x)
205                        }
206                    }
207                }
208
209                MatchOptOwned::Single(Element::Fn(changed, name, args), changed)
210            }
211            Element::Term(_, ref f) => {
212                let mut changed = false;
213                let mut args = Vec::with_capacity(f.len());
214                for x in f.iter() {
215                    let (xx, c) = x.apply_map(m).into_single();
216                    changed |= c;
217                    args.push(xx);
218                }
219                MatchOptOwned::Single(Element::Term(changed, args), changed)
220            }
221            Element::SubExpr(_, ref f) => {
222                let mut changed = false;
223                let mut args = Vec::with_capacity(f.len());
224                for x in f.iter() {
225                    let (xx, c) = x.apply_map(m).into_single();
226                    changed |= c;
227                    args.push(xx);
228                }
229                MatchOptOwned::Single(Element::SubExpr(changed, args), changed)
230            }
231            Element::Dollar(ref name, ref inds) => {
232                let mut changed = false;
233                let mut newinds = Vec::with_capacity(inds.len());
234                for a in inds.iter() {
235                    match a.apply_map(m) {
236                        MatchOptOwned::Single(x, c) => {
237                            changed |= c;
238                            newinds.push(x)
239                        }
240                        MatchOptOwned::Multiple(x) => {
241                            changed = true;
242                            newinds.extend(x)
243                        }
244                    }
245                }
246
247                MatchOptOwned::Single(Element::Dollar(name.clone(), newinds), changed)
248            }
249            _ => MatchOptOwned::Single(self.clone(), false), // no match, so no change
250        }
251    }
252}
253
254#[derive(Debug)]
255pub enum ElementIterSingle<'a> {
256    FnIter(FuncIterator<'a>), // match function
257    FnWildcardIter(&'a VarName, Element, usize, FuncIterator<'a>),
258    SymFnWildcardIter(&'a VarName, Element, usize, SubSequenceIter<'a>),
259    PermIter(SubSequenceIter<'a>), // go through all permutations to find a match
260    Once,                          // matching without wildcard, ie number vs number
261    OnceMatch(&'a VarName, &'a Element), // simple match of variable
262    VarPowerMatch(
263        VarName,
264        &'a Number,
265        &'a Element,
266        &'a Element,
267        &'a BorrowedVarInfo<'a>,
268    ), // match a variable x^n to x?^y?
269    SeqIt(Vec<&'a Element>, SequenceIter<'a>), // target and iterator
270    None(bool),                    // should we pop?
271}
272
273#[derive(Debug)]
274pub enum ElementIter<'a> {
275    SliceIter(&'a VarName, usize, usize, &'a [Element]), // slice
276    SingleArg(&'a [Element], ElementIterSingle<'a>),     // iters consuming a single argument
277    Once,                                                // match without any changes
278    None,                                                // no match
279}
280
281impl<'a> ElementIterSingle<'a> {
282    fn next(&mut self, m: &mut MatchObject<'a>) -> Option<usize> {
283        match *self {
284            ElementIterSingle::None(should_pop) => {
285                if should_pop {
286                    m.pop();
287                }
288                None
289            }
290            ElementIterSingle::Once => match mem::replace(self, ElementIterSingle::None(false)) {
291                ElementIterSingle::Once => Some(m.len()),
292                _ => unreachable!(),
293            },
294            ElementIterSingle::OnceMatch(_, _) => {
295                match mem::replace(self, ElementIterSingle::None(false)) {
296                    ElementIterSingle::OnceMatch(name, target) => {
297                        mem::replace(self, ElementIterSingle::None(true));
298                        push_match(m, name, target)
299                    }
300                    _ => unreachable!(),
301                }
302            }
303            ElementIterSingle::VarPowerMatch(..) => {
304                match mem::replace(self, ElementIterSingle::None(false)) {
305                    ElementIterSingle::VarPowerMatch(b1, p1, b2, p2, var_info) => {
306                        let oldlen = m.len();
307                        let mut newlen = oldlen;
308
309                        // match the base
310                        let r = Element::Var(b1, Number::one());
311
312                        match b2 {
313                            Element::Wildcard(vn, rest) => {
314                                let mut found = false;
315                                for restriction in rest {
316                                    match restriction {
317                                        _ if restriction == &r => {
318                                            match push_match_owned(m, vn, r.clone()) {
319                                                Some(x) => {
320                                                    found = true;
321                                                    newlen = x;
322                                                    break;
323                                                }
324                                                None => return None,
325                                            }
326                                        }
327                                        _ => {}
328                                    }
329                                }
330
331                                if rest.len() == 0 {
332                                    match push_match_owned(m, vn, r.clone()) {
333                                        Some(x) => {
334                                            newlen = x;
335                                        }
336                                        None => return None,
337                                    }
338                                } else {
339                                    if !found {
340                                        return None;
341                                    }
342                                }
343                            }
344                            Element::Var(i, v) => {
345                                if *i != b1 || !v.is_one() {
346                                    return None;
347                                }
348                            }
349                            Element::Dollar(..) => {
350                                if var_info.local_info.get_dollar(b2) != Some(&r) {
351                                    return None;
352                                }
353                            }
354                            _ => return None,
355                        }
356
357                        let r1 = Element::Num(false, p1.clone());
358                        // match the power
359                        match p2 {
360                            Element::Wildcard(vn, rest) => {
361                                for restriction in rest {
362                                    match restriction {
363                                        &Element::NumberRange(ref num1, ref rel) => {
364                                            // see if the number is in the range
365                                            if is_number_in_range(p1, num1, rel) {
366                                                match push_match_owned(m, vn, r1) {
367                                                    Some(x) => {
368                                                        return Some(x);
369                                                    }
370                                                    None => {
371                                                        m.truncate(oldlen);
372                                                        return None;
373                                                    }
374                                                }
375                                            }
376                                        }
377                                        _ if restriction == &r1 => {
378                                            match push_match_owned(m, vn, r1) {
379                                                Some(x) => {
380                                                    return Some(x);
381                                                }
382                                                None => {
383                                                    m.truncate(oldlen);
384                                                    return None;
385                                                }
386                                            }
387                                        }
388                                        _ => {}
389                                    }
390                                }
391
392                                if rest.len() == 0 {
393                                    match push_match_owned(m, vn, r1) {
394                                        Some(y) => Some(y),
395                                        None => {
396                                            m.truncate(oldlen);
397                                            None
398                                        }
399                                    }
400                                } else {
401                                    None
402                                }
403                            }
404                            Element::Dollar(..) => {
405                                if var_info.local_info.get_dollar(p2) != Some(&r1) {
406                                    return None;
407                                }
408                                Some(newlen)
409                            }
410                            Element::Num(_, i) => {
411                                if i != p1 {
412                                    m.truncate(oldlen);
413                                    None
414                                } else {
415                                    Some(newlen)
416                                }
417                            }
418                            _ => {
419                                m.truncate(oldlen);
420                                None
421                            }
422                        }
423                    }
424                    _ => unreachable!(),
425                }
426            }
427            ElementIterSingle::FnIter(ref mut f) => f.next(m),
428            ElementIterSingle::FnWildcardIter(ref name, ref target, ref mut old_len, ref mut f) => {
429                if *old_len == MAXMATCH {
430                    match push_match_owned(m, name, target.clone()) {
431                        Some(x) => {
432                            *old_len = x;
433                        }
434                        None => {
435                            return None;
436                        }
437                    }
438                }
439
440                match f.next(m) {
441                    None => {
442                        // pop the function name match
443                        m.truncate(*old_len);
444                        None
445                    }
446                    x => x,
447                }
448            }
449            ElementIterSingle::SymFnWildcardIter(
450                ref name,
451                ref target,
452                ref mut old_len,
453                ref mut f,
454            ) => {
455                if *old_len == MAXMATCH {
456                    match push_match_owned(m, name, target.clone()) {
457                        Some(x) => {
458                            *old_len = x;
459                        }
460                        None => {
461                            return None;
462                        }
463                    }
464                }
465
466                match f.next(m).map(|(_, s)| s) {
467                    None => {
468                        // pop the function name match
469                        m.truncate(*old_len);
470                        None
471                    }
472                    x => x,
473                }
474            }
475            ElementIterSingle::PermIter(ref mut f) => f.next(m).map(|(_, s)| s),
476            ElementIterSingle::SeqIt(ref target, ref mut seqit) => seqit.next(target, m),
477        }
478    }
479}
480
481impl<'a> ElementIter<'a> {
482    fn next(&mut self, m: &mut MatchObject<'a>) -> Option<(&'a [Element], usize)> {
483        match *self {
484            ElementIter::None => None,
485            ElementIter::Once => {
486                let mut to_swap = ElementIter::None;
487                mem::swap(self, &mut to_swap); //f switch self to none
488                match to_swap {
489                    ElementIter::Once => Some((&[], 0)), // return empty slice
490                    _ => panic!(),                       // never reached
491                }
492            }
493            ElementIter::SliceIter(name, ref mut curlength, upper_bound, target) => {
494                // if the slice is already found, we can immediately compare
495                if *curlength > upper_bound {
496                    return None;
497                }
498
499                if let Some(&MatchOpt::Multiple(v)) = find_match(m, name) {
500                    *curlength = upper_bound + 1; // make sure next call gives None
501                    if v.len() > target.len() {
502                        return None;
503                    }
504                    //let rr = target[..v.len()].iter().map(|x| x).collect::<Vec<_>>(); // FIXME: is this wrong?
505                    if *v == target[..v.len()] {
506                        return Some((&target[v.len()..], m.len()));
507                    } else {
508                        return None;
509                    }
510                }
511
512                'findcandidate: while *curlength <= target.len() {
513                    let (f, l) = target.split_at(*curlength);
514                    *curlength += 1;
515
516                    //let rr = f.iter().map(|x| x).collect();
517                    match push_match_slice(m, name, f) {
518                        Some(x) => return Some((l, x)),
519                        _ => continue 'findcandidate,
520                    }
521                }
522                None
523            }
524            ElementIter::SingleArg(rest, ref mut f) => f.next(m).map(move |x| (rest, x)),
525        }
526    }
527}
528
529impl Element {
530    // create an iterator over a pattern
531    fn to_iter<'a>(
532        &'a self,
533        target: &'a [Element],
534        slice_min_bound: usize,
535        slice_max_bound: usize,
536        var_info: &'a BorrowedVarInfo<'a>,
537        level: usize,
538    ) -> ElementIter<'a> {
539        // go through all possible options (slice sizes) for the variable argument
540        if let Element::VariableArgument(ref name) = *self {
541            return ElementIter::SliceIter(name, slice_min_bound, slice_max_bound, target);
542        }
543
544        // is the slice non-zero length?
545        match target.first() {
546            Some(x) => {
547                ElementIter::SingleArg(&target[1..], self.to_iter_single(x, var_info, level))
548            }
549            None => ElementIter::None,
550        }
551    }
552
553    // create an iterator over a pattern
554    fn to_iter_single<'a>(
555        &'a self,
556        target: &'a Element,
557        var_info: &'a BorrowedVarInfo<'a>,
558        level: usize,
559    ) -> ElementIterSingle<'a> {
560        match (target, self) {
561            (&Element::Var(ref i1, ref e1), &Element::Pow(_, ref be2)) => {
562                // match x^x1? to x^expr
563                let (ref b2, ref e2) = **be2;
564
565                ElementIterSingle::VarPowerMatch(*i1, e1, b2, e2, var_info)
566            }
567            (&Element::Pow(_, ref be1), &Element::Pow(_, ref be2)) => {
568                let (ref b1, ref e1) = **be1;
569                let (ref b2, ref e2) = **be2;
570
571                // match an expression to its multiple on the ground level
572                if level == 0 {
573                    if let Element::Num(false, Number::SmallInt(n1)) = e1 {
574                        if let Element::Num(false, Number::SmallInt(n2)) = e2 {
575                            if n2 < n1 {
576                                return b1.to_iter_single(b2, var_info, level + 1);
577                            }
578                        }
579                    }
580                }
581
582                ElementIterSingle::SeqIt(
583                    vec![b1, e1],
584                    SequenceIter::new(&SliceRef::OwnedSlice(vec![b2, e2]), b1, var_info, level + 1),
585                )
586            }
587            (&Element::Dollar(ref name, ref inds), &Element::Dollar(ref name1, ref inds1)) => {
588                // match $a[x?] to $a[1]
589                ElementIterSingle::FnIter(FuncIterator::from_element(
590                    name1,
591                    inds1,
592                    name,
593                    inds,
594                    var_info,
595                    level + 1,
596                ))
597            }
598            (i1, d @ &Element::Dollar(..)) => {
599                if var_info.local_info.get_dollar(d) == Some(i1) {
600                    ElementIterSingle::Once
601                } else {
602                    ElementIterSingle::None(false)
603                }
604            }
605            (Element::Pow(_, ref be1), x) => {
606                // match x to x^num on the ground level
607                let (ref b2, ref e2) = **be1;
608
609                if level == 0 && x == b2 {
610                    if let Element::Num(_, Number::SmallInt(n)) = e2 {
611                        if *n > 0 {
612                            return ElementIterSingle::Once;
613                        }
614                    }
615                }
616
617                ElementIterSingle::None(false)
618            }
619            (&Element::Var(ref i1, ref e1), &Element::Var(ref i2, ref e2))
620                if i1 == i2 && (e1 == e2 || (level == 0 && e1 >= e2 && e2 > &Number::zero())) =>
621            {
622                ElementIterSingle::Once
623            }
624            (&Element::Num(_, ref n1), &Element::Num(_, ref n2)) if n1 == n2 => {
625                ElementIterSingle::Once
626            }
627            (&Element::Num(_, ref n), &Element::Wildcard(ref i2, ref rest)) => {
628                if rest.is_empty() {
629                    return ElementIterSingle::OnceMatch(i2, target);
630                }
631
632                for restriction in rest {
633                    match restriction {
634                        &Element::NumberRange(ref num1, ref rel) => {
635                            // see if the number is in the range
636                            if is_number_in_range(n, num1, rel) {
637                                return ElementIterSingle::OnceMatch(i2, target);
638                            }
639                        }
640                        _ if restriction == target => {
641                            return ElementIterSingle::OnceMatch(i2, target)
642                        }
643                        _ => {}
644                    }
645                }
646
647                ElementIterSingle::None(false)
648            }
649            (_, &Element::Wildcard(ref i2, ref rest)) => {
650                if rest.is_empty() || rest.contains(target) {
651                    ElementIterSingle::OnceMatch(i2, target)
652                } else {
653                    ElementIterSingle::None(false)
654                }
655            }
656            (&Element::Fn(_, ref name1, ref args1), &Element::Fn(_, ref name2, ref args2)) => {
657                // check if we have a symmetric function
658                if name1 == name2 && args1.len() == args2.len() {
659                    if let Some(attribs) = var_info.global_info.func_attribs.get(name1) {
660                        // check if the pattern contains no wildcard
661                        if attribs.contains(&FunctionAttributes::Symmetric) {
662                            if !args2.iter().any(|x| {
663                                if let Element::VariableArgument(_) = *x {
664                                    true
665                                } else {
666                                    false
667                                }
668                            }) {
669                                return ElementIterSingle::PermIter(SubSequenceIter::new(
670                                    args2,
671                                    args1,
672                                    var_info,
673                                    level + 1,
674                                ));
675                            } else {
676                                println!("Warning: used ?a in symmetric function pattern match. Ignoring symmetric property.");
677                            }
678                        }
679                    }
680                }
681
682                ElementIterSingle::FnIter(FuncIterator::from_element(
683                    name2, args2, name1, args1, var_info, level,
684                ))
685            }
686            (&Element::Fn(_, ref name1, ref args1), &Element::FnWildcard(ref name2, ref b)) => {
687                let (restrictions, args2) = &**b;
688
689                if restrictions.len() > 0
690                    && !restrictions.contains(&Element::Var(*name1, Number::one()))
691                {
692                    ElementIterSingle::None(false)
693                } else {
694                    if args1.len() == args2.len() {
695                        if let Some(attribs) = var_info.global_info.func_attribs.get(name1) {
696                            // check if the pattern contains no wildcard
697                            if attribs.contains(&FunctionAttributes::Symmetric) {
698                                if !args2.iter().any(|x| {
699                                    if let Element::VariableArgument(_) = *x {
700                                        true
701                                    } else {
702                                        false
703                                    }
704                                }) {
705                                    return ElementIterSingle::SymFnWildcardIter(
706                                        name2,
707                                        Element::Var(*name1, Number::one()),
708                                        MAXMATCH,
709                                        SubSequenceIter::new(args2, args1, var_info, level + 1),
710                                    );
711                                } else {
712                                    println!("Warning: used ?a in symmetric function pattern match. Ignoring symmetric property.");
713                                }
714                            }
715                        }
716                    }
717
718                    ElementIterSingle::FnWildcardIter(
719                        name2,
720                        Element::Var(*name1, Number::one()),
721                        MAXMATCH,
722                        FuncIterator::from_element(name1, args2, name1, args1, var_info, level),
723                    )
724                }
725            }
726            (&Element::Term(_, ref f1), &Element::Term(_, ref f2))
727            | (&Element::SubExpr(_, ref f1), &Element::SubExpr(_, ref f2)) => {
728                if f1.len() == f2.len() {
729                    // TODO: increase the level by 1 in case of a subexpr?
730                    ElementIterSingle::PermIter(SubSequenceIter::new(f2, f1, var_info, level))
731                } else {
732                    ElementIterSingle::None(false)
733                }
734            }
735            _ => ElementIterSingle::None(false),
736        }
737    }
738}
739
740// iterator over a pattern of a function
741#[derive(Debug)]
742pub struct FuncIterator<'a> {
743    args: &'a Vec<Element>,
744    iterators: Vec<ElementIter<'a>>,
745    matches: Vec<(&'a [Element], usize)>, // keep track of stack depth
746    var_info: &'a BorrowedVarInfo<'a>,
747    level: usize,
748}
749
750impl<'a> FuncIterator<'a> {
751    fn from_element(
752        name: &'a VarName,
753        args: &'a Vec<Element>,
754        target_name: &'a VarName,
755        target_args: &'a Vec<Element>,
756        var_info: &'a BorrowedVarInfo<'a>,
757        level: usize,
758    ) -> FuncIterator<'a> {
759        if name != target_name {
760            return FuncIterator {
761                args: args,
762                iterators: vec![],
763                matches: vec![],
764                var_info,
765                level,
766            };
767        }
768
769        // shortcut if the number of arguments is wrong
770        let varargcount = args
771            .iter()
772            .filter(|x| match **x {
773                Element::VariableArgument { .. } => true,
774                _ => false,
775            }).count();
776        if args.len() - varargcount > target_args.len() {
777            return FuncIterator {
778                args: args,
779                iterators: vec![],
780                matches: vec![],
781                var_info,
782                level,
783            };
784        };
785        if varargcount == 0 && args.len() != target_args.len() {
786            return FuncIterator {
787                args: args,
788                iterators: vec![],
789                matches: vec![],
790                var_info,
791                level,
792            };
793        };
794
795        if varargcount == 0 && target_args.len() == 0 {
796            // we match two functions without arguments
797            // return an iterator that yields a success once
798            return FuncIterator {
799                args: args,
800                iterators: vec![ElementIter::Once],
801                matches: vec![(&[], MAXMATCH)],
802                var_info,
803                level,
804            };
805        }
806
807        let mut iterator = (0..args.len())
808            .map(|_| ElementIter::None)
809            .collect::<Vec<_>>(); // create placeholder iterators
810                                  // compute limits for wildcards
811        if let Element::VariableArgument(_) = args[0] {
812            let mut minbound = target_args.len();
813            let mut maxbound = target_args.len();
814
815            for a in &args[1..] {
816                if let Element::VariableArgument(_) = *a {
817                    minbound = 0;
818                } else {
819                    if minbound > 0 {
820                        minbound -= 1;
821                    }
822                    maxbound -= 1;
823                }
824            }
825
826            iterator[0] = args[0].to_iter(&target_args, minbound, maxbound, var_info, level + 1); // initialize the first iterator
827        } else {
828            iterator[0] = args[0].to_iter(&target_args, 0, 0, var_info, level + 1); // initialize the first iterator
829        }
830
831        let matches = vec![(&target_args[..], MAXMATCH); args.len()]; // placeholder matches
832
833        FuncIterator {
834            args: args,
835            iterators: iterator,
836            matches: matches,
837            var_info,
838            level,
839        }
840    }
841
842    fn next(&mut self, m: &mut MatchObject<'a>) -> Option<usize> {
843        if self.iterators.len() == 0 {
844            return None;
845        }
846
847        // find the first iterator from the back that is not None
848        let mut i = self.iterators.len() - 1;
849        'next: loop {
850            //println!("matching {:?} {:?}", self.args, m);
851            // FIXME: not correct. the iters should pop the stack on a next match
852            m.truncate(self.matches[i].1); // pop the matches from the stack
853
854            if let Some(x) = self.iterators[i].next(m) {
855                self.matches[i] = x;
856
857                // now update all elements after
858                let mut j = i + 1;
859                while j < self.iterators.len() {
860                    // create a new iterator at j based on the previous match dictionary and slice
861                    let slicem = self.matches[j - 1].0;
862                    if let Element::VariableArgument(_) = self.args[j] {
863                        let mut minbound = slicem.len();
864                        let mut maxbound = slicem.len();
865
866                        for a in &self.args[j + 1..] {
867                            if let Element::VariableArgument(_) = *a {
868                                minbound = 0;
869                            } else {
870                                if minbound > 0 {
871                                    minbound -= 1;
872                                }
873                                maxbound -= 1;
874                            }
875                        }
876
877                        self.iterators[j] = self.args[j].to_iter(
878                            slicem,
879                            minbound,
880                            maxbound,
881                            self.var_info,
882                            self.level + 1,
883                        );
884                    } else {
885                        self.iterators[j] = self.args[j].to_iter(
886                            self.matches[j - 1].0,
887                            0,
888                            0,
889                            self.var_info,
890                            self.level + 1,
891                        );
892                    }
893
894                    match self.iterators[j].next(m) {
895                        Some(y) => {
896                            self.matches[j] = y;
897                        }
898                        None => {
899                            i = j - 1;
900                            continue 'next;
901                        } // try the next match at j-1
902                    }
903
904                    j += 1;
905                }
906
907                let leftover = self.matches.last().unwrap().0;
908                // FIXME: we dont // we need the index from the first: before the iterator started
909                let index = self.matches.last().unwrap().1;
910                if leftover.len() == 0 {
911                    //println!("yielding new match {:?} {}", m, index);
912                    return Some(index); // should be the same as the length of m
913                } else {
914                    // not all arguments consumed, try the next one at the back
915                    i = self.iterators.len() - 1;
916                    continue 'next;
917                }
918            }
919
920            //println!("truncating {:?} to {} {} {:?}", m, self.matches[i].1, i, self.matches.iter().map(|x| x.1).collect::<Vec<_>>());
921
922            if i == 0 {
923                m.truncate(self.matches[0].1); // delete the first match
924                break; // we are done
925            }
926            i -= 1;
927        }
928
929        None
930    }
931}
932
933/// Iterator over a sequence of pattern matches.
934#[derive(Debug)]
935pub struct SequenceIter<'a> {
936    pattern: SliceRef<'a, Element>, // input term
937    iterators: Vec<ElementIterSingle<'a>>,
938    matches: Vec<usize>, // keep track of stack depth
939    var_info: &'a BorrowedVarInfo<'a>,
940    level: usize,
941}
942
943impl<'a> SequenceIter<'a> {
944    fn new(
945        pattern: &SliceRef<'a, Element>,
946        first: &'a Element,
947        var_info: &'a BorrowedVarInfo<'a>,
948        level: usize,
949    ) -> SequenceIter<'a> {
950        let mut its = (0..pattern.len())
951            .map(|_| ElementIterSingle::None(false))
952            .collect::<Vec<_>>();
953        its[0] = pattern.index(0).to_iter_single(first, var_info, level);
954        SequenceIter {
955            pattern: pattern.clone(),
956            iterators: its,
957            matches: vec![MAXMATCH; pattern.len()],
958            var_info,
959            level,
960        }
961    }
962
963    fn next(&mut self, target: &[&'a Element], m: &mut MatchObject<'a>) -> Option<usize> {
964        if self.iterators.is_empty() {
965            return None;
966        }
967
968        // find the first iterator from the back that is not None
969        let mut i = self.iterators.len() - 1;
970        'next: loop {
971            m.truncate(self.matches[i]); // pop the matches from the stack
972
973            if let Some(x) = self.iterators[i].next(m) {
974                self.matches[i] = x;
975
976                // now update all elements after
977                let mut j = i + 1;
978                while j < self.iterators.len() {
979                    // create a new iterator at j based on the previous match dictionary and slice
980                    self.iterators[j] =
981                        self.pattern
982                            .index(j)
983                            .to_iter_single(target[j], self.var_info, self.level);
984
985                    match self.iterators[j].next(m) {
986                        Some(y) => {
987                            self.matches[j] = y;
988                        }
989                        None => {
990                            i = j - 1;
991                            continue 'next;
992                        } // try the next match at j-1
993                    }
994
995                    j += 1;
996                }
997                return Some(*self.matches.last().unwrap());
998            }
999
1000            if i == 0 {
1001                m.truncate(self.matches[0]); // delete the first match
1002                break; // we are done
1003            }
1004            i -= 1;
1005        }
1006
1007        None
1008    }
1009}
1010
1011/// An iterator that matches a pattern of multiple factors to
1012/// a subset of a term.
1013/// For example:
1014/// `IN = f(1,2,3)*g(1,2,3)*g(4,5,6);
1015/// {
1016///     id all f(?a,n?,?b)*g(?c,n?,?d) = f(n?)*g(n?);
1017/// }
1018///`
1019/// uses this iterator to match the `g` to one of the `g`s in the input.
1020#[derive(Debug)]
1021pub struct SubSequenceIter<'a> {
1022    pattern: &'a [Element], // input term
1023    target: &'a [Element],
1024    iterators: Vec<ElementIterSingle<'a>>,
1025    indices: Vec<usize>,
1026    initialized: bool,
1027    matches: Vec<usize>, // keep track of stack depth
1028    var_info: &'a BorrowedVarInfo<'a>,
1029    level: usize,
1030}
1031
1032impl<'a> SubSequenceIter<'a> {
1033    fn new(
1034        pattern: &'a [Element],
1035        target: &'a [Element],
1036        var_info: &'a BorrowedVarInfo<'a>,
1037        level: usize,
1038    ) -> SubSequenceIter<'a> {
1039        SubSequenceIter {
1040            pattern: pattern,
1041            iterators: (0..pattern.len())
1042                .map(|_| ElementIterSingle::None(false))
1043                .collect(),
1044            matches: vec![MAXMATCH; pattern.len()],
1045            indices: vec![0; pattern.len()],
1046            target,
1047            var_info,
1048            level,
1049            initialized: false,
1050        }
1051    }
1052
1053    fn next(&mut self, m: &mut MatchObject<'a>) -> Option<(&Vec<usize>, usize)> {
1054        if self.pattern.len() > self.target.len() {
1055            return None;
1056        }
1057
1058        let mut i = if self.initialized {
1059            // find the first iterator from the back that is not None
1060            self.iterators.len() - 1
1061        } else {
1062            // build the first iterator from the start
1063            self.indices = (0..self.pattern.len())
1064                .map(|_| self.target.len() + 1)
1065                .collect(); // start with unique indices
1066            0
1067        };
1068        self.initialized = true;
1069
1070        loop {
1071            m.truncate(self.matches[i]); // pop the matches from the stack
1072
1073            if let Some(x) = self.iterators[i].next(m) {
1074                self.matches[i] = x;
1075
1076                // we have found a match!
1077                if i + 1 == self.pattern.len() {
1078                    return Some((&self.indices, self.matches[i]));
1079                }
1080                i += 1;
1081            } else {
1082                // find a new empty position
1083                if self.indices[i] == self.target.len() + 1 {
1084                    self.indices[i] = 0; // initialize
1085
1086                    // for non-commutative functions, we make sure the index in the
1087                    // target is higher than that of its left neighbour
1088                    if i > 0 {
1089                        if let Element::Fn(_, ref name, _) = self.pattern[i] {
1090                            if let Element::Fn(_, ref name1, _) = self.pattern[i - 1] {
1091                                if name == name1 {
1092                                    if let Some(attribs) =
1093                                        self.var_info.global_info.func_attribs.get(name)
1094                                    {
1095                                        if attribs.contains(&FunctionAttributes::NonCommutative) {
1096                                            self.indices[i] = self.indices[i - 1] + 1;
1097                                        }
1098                                    }
1099                                }
1100                            }
1101                        }
1102                    }
1103                } else {
1104                    self.indices[i] += 1;
1105                }
1106                while self.indices[..i].iter().any(|x| self.indices[i] == *x)
1107                    && self.indices[i] < self.target.len()
1108                {
1109                    self.indices[i] += 1;
1110                }
1111
1112                if self.indices[i] == self.target.len() {
1113                    // out of tries, fall back one level
1114                    if i == 0 {
1115                        // we are out of matches
1116                        return None;
1117                    }
1118
1119                    self.indices[i] = self.target.len() + 1; // reset the index
1120                    i -= 1;
1121                } else {
1122                    self.iterators[i] = self.pattern[i].to_iter_single(
1123                        &self.target[self.indices[i]],
1124                        self.var_info,
1125                        self.level,
1126                    );
1127                }
1128            }
1129        }
1130    }
1131}
1132
1133#[derive(Debug)]
1134pub enum MatchKind<'a> {
1135    Single(ElementIterSingle<'a>),
1136    SinglePat(
1137        &'a Element,
1138        ElementIterSingle<'a>,
1139        &'a [Element],
1140        usize,
1141        &'a BorrowedVarInfo<'a>,
1142    ),
1143    Many(SubSequenceIter<'a>),
1144    None,
1145}
1146
1147impl<'a> MatchKind<'a> {
1148    pub fn from_element(
1149        pattern: &'a Element,
1150        target: &'a Element,
1151        var_info: &'a BorrowedVarInfo<'a>,
1152    ) -> MatchKind<'a> {
1153        match (pattern, target) {
1154            (&Element::Term(_, ref x), &Element::Term(_, ref y)) => {
1155                MatchKind::Many(SubSequenceIter::new(x, y, var_info, 0))
1156            }
1157            (a, &Element::Term(_, ref y)) => {
1158                MatchKind::SinglePat(a, ElementIterSingle::None(false), y, 0, var_info)
1159            }
1160            (a, b) => MatchKind::Single(a.to_iter_single(b, var_info, 0)),
1161        }
1162    }
1163
1164    pub fn next(&mut self, m: &mut MatchObject<'a>, indices: &mut Vec<usize>) -> bool {
1165        match *self {
1166            MatchKind::Single(ref mut x) => {
1167                indices.clear();
1168                x.next(m).is_some()
1169            }
1170            MatchKind::Many(ref mut x) => match x.next(m) {
1171                Some((ind, _)) => {
1172                    indices.clone_from(ind);
1173                    true
1174                }
1175                None => false,
1176            },
1177            MatchKind::SinglePat(pat, ref mut it, target, ref mut index, var_info) => loop {
1178                if it.next(m).is_some() {
1179                    indices.clear();
1180                    indices.push(*index - 1);
1181                    return true;
1182                }
1183
1184                if *index == target.len() {
1185                    return false;
1186                }
1187                *it = pat.to_iter_single(&target[*index], var_info, 0);
1188                *index += 1;
1189            },
1190            MatchKind::None => false,
1191        }
1192    }
1193}
1194
1195#[derive(Debug)]
1196pub struct MatchIterator<'a> {
1197    mode: IdentityStatementMode,
1198    lhs: &'a Element,
1199    rhs: &'a Element,
1200    target: &'a Element,
1201    m: MatchObject<'a>,
1202    used_indices: Vec<usize>,
1203    result: Element,
1204    it: MatchKind<'a>,
1205    rhsp: usize, // current rhs index,
1206    hasmatch: bool,
1207    var_info: &'a BorrowedVarInfo<'a>,
1208}
1209
1210// iterate over the output terms of a match
1211impl<'a> MatchIterator<'a> {
1212    /// Find out how often the pattern fits in the
1213    /// target term.
1214    fn find_multiplicity(&self, lhs: &Element, rhs: &Element) -> usize {
1215        match (lhs, rhs) {
1216            (Element::Term(_, ref pts), Element::Term(_, ref tts)) => {
1217                let mut max_mul = 0;
1218                for (i, k) in pts.iter().enumerate() {
1219                    let mul = self.find_multiplicity(k, &tts[self.used_indices[i]]);
1220                    if mul < max_mul || max_mul == 0 {
1221                        max_mul = mul;
1222
1223                        if mul == 1 {
1224                            return 1;
1225                        }
1226                    }
1227                }
1228                max_mul
1229            }
1230            (_, Element::Term(_, ref tts)) => {
1231                self.find_multiplicity(lhs, &tts[self.used_indices[0]])
1232            }
1233            (Element::Pow(_, be), Element::Pow(_, be1)) => {
1234                if let Element::Num(_, Number::SmallInt(p)) = be.1 {
1235                    if let Element::Num(_, Number::SmallInt(p1)) = be1.1 {
1236                        if p > 0 && p1 > 0 {
1237                            return (p1 / p) as usize;
1238                        }
1239                    }
1240                }
1241                1
1242            }
1243            (_, Element::Pow(_, be)) => {
1244                if let Element::Num(_, Number::SmallInt(p)) = be.1 {
1245                    if p > 0 {
1246                        return p as usize;
1247                    }
1248                }
1249                1
1250            }
1251            (Element::Var(_, pow), Element::Var(_, pow1)) => {
1252                if let Number::SmallInt(p) = pow {
1253                    if let Number::SmallInt(p1) = pow1 {
1254                        if *p > 0 && *p1 > 0 {
1255                            return (p1 / p) as usize;
1256                        }
1257                    }
1258                }
1259                1
1260            }
1261            (Element::Wildcard(_, _), Element::Var(_, pow)) => {
1262                if let Number::SmallInt(p) = pow {
1263                    if *p > 0 {
1264                        return *p as usize;
1265                    }
1266                }
1267                1
1268            }
1269            _ => 1,
1270        }
1271    }
1272
1273    fn construct_rest_term(
1274        &self,
1275        lhs: &Element,
1276        rhs: &Element,
1277        accum: &mut Vec<Element>,
1278        multiplicity: usize,
1279    ) {
1280        match (lhs, rhs) {
1281            (Element::Term(_, ref pts), Element::Term(_, ref tts)) => {
1282                for (i, k) in tts.iter().enumerate() {
1283                    // add factors that were not matched or whatever remains of a match
1284                    if self.used_indices.len() < tts.len() && !self.used_indices.contains(&i) {
1285                        accum.push(k.clone())
1286                    } else {
1287                        self.construct_rest_term(
1288                            &pts[self.used_indices.iter().position(|x| *x == i).unwrap()],
1289                            k,
1290                            accum,
1291                            multiplicity,
1292                        )
1293                    }
1294                }
1295            }
1296            (_, Element::Term(_, ref tts)) => {
1297                for (i, k) in tts.iter().enumerate() {
1298                    if i == self.used_indices[0] {
1299                        self.construct_rest_term(lhs, k, accum, multiplicity);
1300                    } else {
1301                        accum.push(k.clone());
1302                    }
1303                }
1304            }
1305            (Element::Pow(_, be), Element::Pow(dirty, be1)) => {
1306                if let Element::Num(_, ref p) = be.1 {
1307                    if let Element::Num(_, ref p1) = be1.1 {
1308                        let newpow =
1309                            p1.clone() - Number::SmallInt(multiplicity as isize) * p.clone();
1310                        if !newpow.is_zero() {
1311                            accum.push(Element::Pow(
1312                                *dirty,
1313                                Box::new((be1.0.clone(), Element::Num(false, newpow))),
1314                            ));
1315                        }
1316                    } else {
1317                        unreachable!()
1318                    }
1319                } else {
1320                    unreachable!()
1321                }
1322            }
1323            (_, Element::Pow(dirty, be)) => {
1324                if let Element::Num(_, ref p) = be.1 {
1325                    let newpow = p.clone() - Number::SmallInt(multiplicity as isize);
1326                    if !newpow.is_zero() {
1327                        accum.push(Element::Pow(
1328                            *dirty,
1329                            Box::new((be.0.clone(), Element::Num(false, newpow))),
1330                        ));
1331                    }
1332                } else {
1333                    unreachable!()
1334                }
1335            }
1336            (Element::Var(_, pow), Element::Var(x1, pow1)) => {
1337                let newpow = pow1.clone() - Number::SmallInt(multiplicity as isize) * pow.clone();
1338                if !newpow.is_zero() {
1339                    accum.push(Element::Var(*x1, newpow));
1340                }
1341            }
1342            (Element::Wildcard(_, _), Element::Var(x1, pow1)) => {
1343                let newpow = pow1.clone() - Number::SmallInt(multiplicity as isize);
1344                if !newpow.is_zero() {
1345                    accum.push(Element::Var(*x1, newpow));
1346                }
1347            }
1348            _ => {} // factor needs to be removed completely
1349        }
1350    }
1351
1352    /// Construct the part of the input that remains in the output.
1353    /// This takes multiplicity of the pattern into account.
1354    fn construct_remaining(&self, target: &Element) -> (usize, Element) {
1355        // determine the maximimum multiplicity
1356        let multiplicity = if self.mode != IdentityStatementMode::Once {
1357            self.find_multiplicity(&self.lhs, target)
1358        } else {
1359            1
1360        };
1361
1362        // construct the rest terms
1363        let mut e = vec![];
1364        self.construct_rest_term(&self.lhs, target, &mut e, multiplicity);
1365
1366        if e.is_empty() {
1367            (multiplicity, Element::Num(false, Number::one()))
1368        } else {
1369            (multiplicity, Element::Term(true, e))
1370        }
1371    }
1372
1373    pub fn next(&mut self) -> StatementResult<Element> {
1374        if self.rhsp == 0 {
1375            if self.it.next(&mut self.m, &mut self.used_indices) {
1376                if self.mode != IdentityStatementMode::All {
1377                    self.it = MatchKind::None;
1378                }
1379
1380                let (mult, mut rem) = self.construct_remaining(self.target);
1381
1382                self.result = if mult == 1 {
1383                    self.rhs.apply_map(&self.m).into_single().0
1384                } else {
1385                    self.rhs
1386                        .apply_map(&self.m)
1387                        .into_single()
1388                        .0
1389                        .pow(Element::Num(false, Number::SmallInt(mult as isize)))
1390                };
1391
1392                // in many-mode we keep on matching on the terms that remain
1393                // TODO: support many-all mode
1394                if self.mode == IdentityStatementMode::Many {
1395                    self.used_indices.clear();
1396
1397                    let mut r;
1398                    loop {
1399                        {
1400                            let mut m2 = vec![]; // needs to be local to prevent borrow issues
1401                            if !MatchKind::from_element(self.lhs, &rem, self.var_info)
1402                                .next(&mut m2, &mut self.used_indices)
1403                            {
1404                                break;
1405                            }
1406
1407                            let (mult, rem1) = self.construct_remaining(&rem);
1408
1409                            self.result.append_factors_mut_move(if mult == 1 {
1410                                self.rhs.apply_map(&m2).into_single().0
1411                            } else {
1412                                self.rhs
1413                                    .apply_map(&m2)
1414                                    .into_single()
1415                                    .0
1416                                    .pow(Element::Num(false, Number::SmallInt(mult as isize)))
1417                            });
1418
1419                            r = rem1;
1420                        }
1421                        rem = r;
1422                    }
1423                }
1424
1425                self.result.append_factors_mut_move(rem);
1426            } else {
1427                if self.hasmatch {
1428                    return StatementResult::Done;
1429                } else {
1430                    return StatementResult::NoChange;
1431                }
1432            }
1433        }
1434
1435        self.hasmatch = true;
1436
1437        let mut e = match &mut self.result {
1438            Element::SubExpr(_, ref mut x) => {
1439                if x.len() == 1 {
1440                    self.rhsp = 0;
1441                } else {
1442                    self.rhsp = x.len();
1443                }
1444                x.pop().unwrap()
1445            }
1446            x => mem::replace(x, Element::default()),
1447        };
1448
1449        // FIXME: in the current setup, the dollar variable list
1450        // handed to the id routines are empty. We have to
1451        // replace dollar variables that are suddenly replacable
1452        // due to index changes elsewhere now
1453        if e.contains_dollar() {
1454            e.normalize_inplace(self.var_info.global_info);
1455            if e.replace_dollar(&self.var_info.local_info.variables)
1456                .contains(ReplaceResult::Replaced)
1457            {
1458                e.normalize_inplace(self.var_info.global_info);
1459            }
1460        } else {
1461            e.normalize_inplace(self.var_info.global_info);
1462        }
1463
1464        StatementResult::Executed(e)
1465    }
1466}
1467
1468impl IdentityStatement {
1469    pub fn to_iter<'a>(
1470        &'a self,
1471        input: &'a Element,
1472        var_info: &'a BorrowedVarInfo<'a>,
1473    ) -> MatchIterator<'a> {
1474        MatchIterator {
1475            hasmatch: false,
1476            target: input,
1477            m: vec![],
1478            used_indices: vec![],
1479            mode: self.mode,
1480            result: Element::default(),
1481            lhs: &self.lhs,
1482            rhs: &self.rhs,
1483            rhsp: 0,
1484            it: MatchKind::from_element(&self.lhs, input, &var_info),
1485            var_info,
1486        }
1487    }
1488}