-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathexpression.py
1473 lines (1123 loc) · 40.9 KB
/
expression.py
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2023 IBM Corp.
# SPDX-License-Identifier: Apache-2.0
from abc import abstractmethod
from . import error, util
from .object import Object
__all__ = [
'Abstraction',
'Application',
'AtomicTerm',
'BoundVariable',
'CompoundTerm',
'Constant',
'Expression',
'Term',
'Type',
'TypeApplication',
'TypeConstructor',
'TypeVariable',
'Variable',
]
class Expression(Object):
"""Abstract base class for expressions.
An :class:`Expression` can be either a :class:`Type` or a :class:`Term`.
Parameters:
args: Arguments
kwargs: Annotations.
Returns:
:class:`Expression`.
"""
__slots__ = (
'_cached_unfolded_args',
'_cached_type_constructors',
'_cached_type_variables',
)
def __neg__(self): # FIXME: generalize
return self.Not(self)
def __invert__(self): # FIXME: generalize
return self.Not(self)
def __and__(self, other): # FIXME: generalize
return self.And(self, other)
def __rand__(self, other): # FIXME: generalize
return self.And(other, self)
def __or__(self, other): # FIXME: generalize
return self.Or(self, other)
def __ror__(self, other): # FIXME: generalize
return self.Or(other, self)
def _build_unfolded_args_cache(self):
"""Gets the expression arguments unfolded."""
return tuple(self._get_unfolded_args_iterator())
def _get_unfolded_args_iterator(self): # defaults to args
return iter(self.args)
def has_type_constructors(self):
"""Tests whether some type constructor occurs in expression.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return bool(self.type_constructors)
def _build_type_constructors_cache(self):
"""Gets the set of type constructors occurring in expression."""
return frozenset(self._get_type_constructors_iterator())
@abstractmethod
def _get_type_constructors_iterator(self):
raise NotImplementedError
def has_type_variables(self):
"""Tests whether some type variable occurs in expression.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return bool(self.type_variables)
def _build_type_variables_cache(self):
"""Gets the set of type variables occurring in expression."""
return frozenset(self._get_type_variables_iterator())
@abstractmethod
def _get_type_variables_iterator(self):
raise NotImplementedError
def instantiate(self, theta):
"""Applies type-variable instantiation `theta` to expression.
Parameters:
theta: Dictionary mapping type variables to types.
Returns:
The resulting :class:`Expression`.
.. code-block:: python
:caption: Example:
a, b = TypeVariables('a', 'b')
f = Constant('f', FunctionType(a, b))
x = Variable('x', a)
print(f(x))
# (f : a → b) (x : a)
print(f(x).instantiate({a: BaseType('nat'), b: BoolType()}))
# (f : nat → bool) (x : nat)
"""
return self._instantiate(theta)[0] if theta else self
@abstractmethod
def _instantiate(self, theta):
raise NotImplementedError
class TypeConstructor(Expression):
"""Type constructor.
Type constructors are the building blocks of type expressions.
Parameters:
arg1: Id.
arg2: Arity.
arg3: Associativity (``'left'`` or ``'right'``).
kwargs: Annotations.
Returns:
A new :class:`TypeConstructor`.
"""
_associativity_values = {'left', 'right'}
def __init__( # (id, arity, associativity)
self, arg1, arg2, arg3=None, **kwargs):
super().__init__(arg1, arg2, arg3, **kwargs)
def _preprocess_arg(self, arg, i):
if i != 3: # skip possible None
arg = super()._preprocess_arg(arg, i)
if i == 1:
return self._preprocess_arg_id(self, arg, i)
elif i == 2:
return abs(error.check_arg_class(
arg, int, self.__class__.__name__, None, i))
elif i == 3:
return error.check_optional_arg_enum(
arg, self._associativity_values, None,
self.__class__.__name__, None, i)
else:
error.should_not_get_here()
def __call__(self, *args, **kwargs):
if self.associativity is None or len(args) <= self.arity:
return TypeApplication(self, *args, **kwargs)
elif self.associativity == 'left':
return util.foldl1(
lambda x, y: TypeApplication(self, x, y),
args).with_annotations(**kwargs)
elif self.associativity == 'right':
return util.foldr1(
lambda x, y: TypeApplication(self, x, y),
args).with_annotations(**kwargs)
else:
error.should_not_get_here()
@property
def id(self):
"""Type constructor id."""
return self.get_id()
def get_id(self):
"""Gets type constructor id.
Returns:
Type constructor id.
"""
return self[0]
@property
def arity(self):
"""Type constructor arity."""
return self.get_arity()
def get_arity(self):
"""Gets type constructor arity.
Returns:
Type constructor arity.
"""
return self[1]
@property
def associativity(self):
"""Type constructor associativity."""
return self.get_associativity()
def get_associativity(self):
"""Gets type constructor associativity.
Returns:
Type constructor associativity.
"""
return self[2]
def _get_type_constructors_iterator(self): # Expression
return iter([self])
def _get_type_variables_iterator(self): # Expression
return iter(())
def _instantiate(self, theta): # Expression
return self, False
class Type(Expression):
"""Abstract base class for types.
A type is an expression representing a structured collection of values.
It can be either a :class:`TypeVariable` or a :class:`TypeApplication`.
"""
@staticmethod
def _preprocess_arg_type(self, arg, i):
if isinstance(arg, type):
try:
return self._thy().lookup_python_type_alias(arg)
except LookupError as err:
return error.arg_error(
arg, err, self.__class__.__name__, None, i)
else:
return Type.check(arg, self.__class__.__name__, None, i)
def match(self, other, theta=None):
"""Finds an instantiation that makes type match `other`.
Parameters:
other: :class:`Type`.
theta: Dictionary mapping variables to types.
Returns:
A type-variable instantiation (theta) if successful;
``None`` otherwise.
.. code-block:: python
:caption: Example:
a, b = TypeVariables('a', 'b')
t1 = FunctionType(a, b)
t2 = FunctionType(bool, bool, bool)
print(t1.match(t2))
# {(a : *): (bool : *), (b : *): (bool → bool : *)}
"""
other = Type.check(other, 'match', 'other', 1)
return self._match(other, theta or dict())
def matches(self, other):
"""Tests whether type can instantiated to match `other`.
Parameters:
other: :class:`Type`.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return self.match(other) is not None
@abstractmethod
def _match(self, other, theta):
raise NotImplementedError
class TypeVariable(Type):
"""Type variable.
A type variable is an expression representing an arbitrary type.
Parameters:
arg1: Id.
kwargs: Annotations.
Returns:
A new :class:`TypeVariable`.
.. code-block:: python
:caption: Example:
a = TypeVariable('a')
print(a)
# a : *
See also:
:func:`TypeVariables`.
"""
def __init__( # (id,)
self, arg1, **kwargs):
super().__init__(arg1, **kwargs)
def _preprocess_arg(self, arg, i):
arg = super()._preprocess_arg(arg, i)
if i == 1:
return self._preprocess_arg_id(self, arg, i)
else:
error.should_not_get_here()
@property
def id(self):
"""Type variable id."""
return self.get_id()
def get_id(self):
"""Gets type variable id.
Returns:
Type variable id.
"""
return self[0]
def _get_type_constructors_iterator(self): # Expression
return iter(())
def _get_type_variables_iterator(self): # Expression
return iter([self])
def _instantiate(self, theta): # Expression
if self in theta:
return theta[self], True
else:
return self, False
def _match(self, other, theta): # Type
if self in theta:
return theta if theta[self] == other else None
else:
theta[self] = other
return theta
class TypeApplication(Type):
"""Type application.
A type application is an expression representing the type obtained by
the application of a type constructor to other types.
Parameters:
arg1: :class:`TypeConstructor`.
args: :class:`Type`'s.
kwargs: Annotations.
Returns:
A new :class:`TypeApplication`.
.. code-block:: python
:caption: Example:
c0 = TypeConstructor('c0', 0)
print(c0()) # Equivalent to: TypeApplication(c0)
# c0 : *
c1 = TypeConstructor('c1', 1)
print(c1(c0())) # Equivalent to: TypeApplication(c1, c0())
# c1 c0 : *
"""
@classmethod
def _unfold(cls, arg):
tcons = arg.head
if tcons.arity == 2:
l, r = arg.tail
if tcons.associativity == 'left':
return tcons, *util.unfoldl(lambda x: x.tail if (
x.is_type_application()
and x.head == tcons) else None, arg)
elif tcons.associativity == 'right':
return tcons, *util.unfoldr(lambda x: x.tail if (
x.is_type_application()
and x.head == tcons) else None, arg)
return super()._unfold(arg)
def __init__( # (tcons, type, ..., type)
self, arg1, *args, **kwargs):
super().__init__(arg1, *args, **kwargs)
def _preprocess_args(self, args):
args = super()._preprocess_args(args)
tcons, exp, got = args[0], args[0].arity, len(args) - 1
if exp != got:
qtd = 'few' if got < exp else 'many'
error.arg_error(
tcons,
f'too {qtd} arguments: expected {exp}, got {got}',
self.__class__.__name__, None, 1)
return args
def _preprocess_arg(self, arg, i):
arg = super()._preprocess_arg(arg, i)
if i == 1:
return self._preprocess_arg_type_constructor(self, arg, i)
else:
return self._preprocess_arg_type(self, arg, i)
@property
def head(self):
"""Type application head.
.. code-block:: python
:caption: Example:
c0 = TypeConstructor('c0', 0)
c1 = TypeConstructor('c1', 1)
c2 = TypeConstructor('c2', 2)
print(c2(c1(c0()), c0()).head)
# c2
"""
return self.get_head()
def get_head(self):
"""Gets type application head.
Returns:
Type application head.
"""
return self[0]
@property
def tail(self):
"""Type application tail.
.. code-block:: python
:caption: Example:
c0 = TypeConstructor('c0', 0)
c1 = TypeConstructor('c1', 1)
c2 = TypeConstructor('c2', 2)
print(c2(c1(c0()), c0()).head)
# (c1 c0 : *, c0 : *)
"""
return self.get_tail()
def get_tail(self):
"""Gets type application tail.
Returns:
Type application tail.
"""
return self[1:]
def _get_unfolded_args_iterator(self): # Expression
return iter(self._unfold_type_application())
def _get_type_constructors_iterator(self): # Expression
return util.chain(
[self.head],
*map(lambda x: x.get_type_constructors(), self.tail))
def _get_type_variables_iterator(self): # Expression
return util.chain(
*map(lambda x: x.get_type_variables(), self.tail))
def _instantiate(self, theta): # Expression
args, status = [self.head], False
for x in self.tail:
y, s = x._instantiate(theta)
args.append(y)
status |= s
return self.with_args(*args), status
def _match(self, other, theta): # Type
if not other.is_type_application():
return None
h1, *t1 = self._unpack_type_application()
h2, *t2 = other._unpack_type_application()
if h1 != h2 or len(t1) != len(t2):
return None
for a, b in zip(t1, t2):
theta = a.match(b, theta)
if theta is None:
return None
return theta
class Term(Expression):
"""Abstract base class for terms.
A term is an expression representing a value of a type.
It can be either a :class:`Variable`, :class:`Constant`,
:class:`Application`, or :class:`Abstraction`.
"""
__slots__ = (
'_cached_type',
'_cached_constants',
'_cached_variables',
'_cached_bound_variables',
'_cached_free_variables',
'_cached_nameless_variables',
)
@staticmethod
def _preprocess_arg_term(self, arg, i):
if not Term.test(arg):
try:
spec = self._thy().lookup_python_type_alias_spec(type(arg))
if hasattr(spec, 'cast'):
arg = spec.cast(arg)
except LookupError:
pass
return Term.check(arg, self.__class__.__name__, None, i)
def __call__(self, *args, **kwargs):
if (not args and self.is_atomic_term()
and not self.type.is_function_type()):
return self.with_annotations(**kwargs)
else:
return Application(self, *args, **kwargs)
def __rshift__(self, other):
return Abstraction(self, other)
def __rrshift__(self, other):
return Abstraction(*other, self)
def __lshift__(self, other):
return other >> self
def _build_type_cache(self):
"""Gets the term type."""
return self._get_type()
@abstractmethod
def _get_type(self):
raise NotImplementedError
def has_constants(self):
"""Tests whether some constant occurs in term.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return bool(self.constants)
def _build_constants_cache(self):
"""Gets the set of constants occurring in term."""
return frozenset(self._get_constants_iterator())
@abstractmethod
def _get_constants_iterator(self):
raise NotImplementedError
def has_occurrence_of(self, x):
"""Tests whether variable `x` occurs (bound or free) in term.
Parameters:
x: :class:`Variable`.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return x in self.variables
def has_variables(self):
"""Tests whether some variable occurs in term.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return bool(self.variables)
def _build_variables_cache(self):
"""Gets the set of variables occurring in term."""
return frozenset(self._get_variables_iterator())
@abstractmethod
def _get_variables_iterator(self):
raise NotImplementedError
def has_bound_occurrence_of(self, x):
"""Tests whether variable `x` occurs bound in term.
Parameters:
x: :class:`Variable`.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return x in self.bound_variables
def has_bound_variables(self):
"""Tests whether some bound variable occurs in term.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return bool(self.bound_variables)
def _build_bound_variables_cache(self):
"""Gets the set of bound variables occurring in term."""
return frozenset(self._get_bound_variables_iterator())
@abstractmethod
def _get_bound_variables_iterator(self):
raise NotImplementedError
def has_free_occurrence_of(self, x):
"""Tests whether variable `x` occurs free in term.
Parameters:
x: :class:`Variable`.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return x in self.free_variables
def has_free_variables(self):
"""Tests whether some free variable occurs in term.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return bool(self.free_variables)
def _build_free_variables_cache(self):
"""Gets the set of free variables occurring in term."""
return frozenset(self._get_free_variables_iterator())
@abstractmethod
def _get_free_variables_iterator(self):
raise NotImplementedError
def has_nameless_occurrence_of(self, x):
"""Tests whether nameless variable `x` occurs in term.
Parameters:
x: :class:`BoundVariable`.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return x in self.nameless_variables
def has_nameless_variables(self):
"""Tests whether some nameless variable occurs in term.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return bool(self.nameless_variables)
def _build_nameless_variables_cache(self):
"""Gets the set of nameless variables occurring in term."""
return frozenset(self._get_nameless_variables_iterator())
@abstractmethod
def _get_nameless_variables_iterator(self):
raise NotImplementedError
def open(self, x):
"""Replaces free variable `x` by bound variable in term.
(Internal: Not intended for direct use.)
Parameters:
x: :class:`Variable`.
Returns:
A new :class:`Term`.
.. code-block:: python
:caption: Example:
x, y = Variables('x', 'y', BoolType())
t = Abstraction(x, y)(y)
print(t.open(y))
# (𝜆 (x : bool) ⇒ (1 : bool)) (0 : bool)
See also:
:class:`BoundVariable`, :func:`Term.close`.
"""
return self._open(x, 0)
@abstractmethod
def _open(self, x, i):
raise NotImplementedError
def close(self, term):
"""Replaces bound variable by `term` in term.
(Internal: Not intended for direct use.)
Parameter:
term: :class:`Term`.
Returns:
A new :class:`Term`.
.. code-block:: python
:caption: Example:
x, y, z = Variables('x', 'y', 'z', BoolType())
t = Abstraction(x, y)(y)
t1 = t.open(y)
print(t1)
# (𝜆 (x : bool) ⇒ (1 : bool)) (0 : bool)
t2 = t1.close(z)
print(t2)
# (𝜆 (x : bool) ⇒ (z : bool)) (z : bool)
See also:
:class:`BoundVariable`, :func:`Term.open`.
"""
return self._close(term, 0)
@abstractmethod
def _close(self, term, i):
raise NotImplementedError
def substitute(self, theta):
"""Applies free-variable substitution `theta` to term.
Parameters:
theta: Dictionary mapping variables to terms.
Returns:
The resulting :class:`Term`.
Raises:
ValueError: `theta` is invalid.
.. code-block:: python
:caption: Example:
a = TypeVariable('a')
x, y, z = Variables('x', 'y', 'z', a)
f = Constant('f', FunctionType(a, a, a))
t = Abstraction(x, f(x, y))
print(t.substitute({y: z}))
# 𝜆 x ⇒ f x z
t = Abstraction(x, f(x, y))
print(t.substitute({y: x}))
# 𝜆 x0 ⇒ f x0 x
"""
for v, t in theta.items():
if not Variable.test(v) or not Term.test(t) or v.type != t.type:
return error.arg_error(
theta, 'invalid theta', 'substitute', 'theta', 1)
return self._substitute(theta)[0] if theta else self
@abstractmethod
def _substitute(self, theta):
raise NotImplementedError
class AtomicTerm(Term):
"""Abstract base class for atomic terms."""
@abstractmethod
def __init__( # (id, type)
self, arg1, type=None, **kwargs):
super().__init__(arg1, type, **kwargs)
def _preprocess_arg(self, arg, i):
if i == 1:
return self._preprocess_arg_id(self, arg, i)
elif i == 2:
return self._preprocess_arg_type(self, arg, i)
else:
error.should_not_get_here()
def __matmul__(self, kwargs):
if isinstance(kwargs, dict):
return super().__matmul__(kwargs)
else:
return self.with_type(
self._preprocess_arg_type(self, kwargs, 2))
@property
def id(self):
"""Atomic term id."""
return self.get_id()
def get_id(self):
"""Get atomic term id.
Returns:
Atomic term id.
"""
return self[0]
def _get_type_constructors_iterator(self): # Expression
return self.type.get_type_constructors()
def _get_type_variables_iterator(self): # Expression
return self.type.get_type_variables()
def _instantiate(self, theta): # Expression
type, status = self.type._instantiate(theta)
if status:
return self.with_type(type), True
else:
return self, False
def _get_type(self): # Term
return self[1]
def with_type(self, type):
"""Copies atomic term overwriting its type.
Parameters:
type: :class:`Type`.
Returns:
The resulting :class:`AtomicTerm`.
.. code-block:: python
:caption: Equivalent to:
term.copy(term.id, type)
"""
return self.with_args(self.id, type)
class Variable(AtomicTerm):
"""Variable.
A variable is an atomic expression representing an arbitrary
value of a type.
Parameters:
arg1: Id.
type: :class:`Type`.
kwargs: Annotations.
Returns:
A new :class:`Variable`.
See also:
:func:`Variables`.
"""
def __init__( # (id, type)
self, arg1, type=None, **kwargs):
super().__init__(arg1, type=type, **kwargs)
def _get_constants_iterator(self): # Term
return iter(())
def _get_variables_iterator(self): # Term
return iter([self])
def _get_bound_variables_iterator(self): # Term
return iter(())
def _get_free_variables_iterator(self): # Term
return iter([self])
def _get_nameless_variables_iterator(self): # Term
return iter(())
def _open(self, x, i): # Term
if self.id == x.id and self.type == x.type:
return BoundVariable(i, self.type)
else:
return self
def _close(self, term, i): # Term
return self
def _substitute(self, theta): # Term
if self in theta:
return theta[self], True
else:
return self, False
def occurs_in(self, it):
"""Tests whether variable occurs in some term in `it`.
Parameters:
it: Iterable.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return util.any_map(lambda x: x.has_occurrence_of(self), iter(it))
def occurs_bound_in(self, it):
"""Tests whether variable occurs bound in some term in `it`.
Parameters:
it: Iterable.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return util.any_map(
lambda x: x.has_bound_occurrence_of(self), iter(it))
def occurs_free_in(self, it):
"""Tests whether variable occurs free in some term in `it`.
Parameters:
it: Iterable.
Returns:
``True`` if successful; ``False`` otherwise.
"""
return util.any_map(
lambda x: x.has_free_occurrence_of(self), iter(it))
def get_variant(self, avoid_test):
"""Gets a variant that passes `avoid_test`.
`avoid_test` is a function that takes a variable and returns
``True`` if it is unacceptable, or ``False`` if it is acceptable.
If variable passes `avoid_test`, returns variable itself.
Otherwise, generates and returns a similarly named variant that
passes `avoid_test`.
Parameter:
avoid_test: Function.
Returns:
Variable itself or a new similarly named variant.
.. code-block:: python
:caption: Example:
x = Variable('x', BoolType())
print(x.get_variant(lambda v: v == x))
# x : bool
print(x.get_variant(lambda v: v.id in {'x', 'x0', 'x1'}))
# x2 : bool
"""
x = self
while avoid_test(x):
x = x.with_args(util.get_variant(x.id), x.type)
return x
def get_variant_not_in(self, avoid):
"""Gets a variant that does not occur in `avoid`.
If variable does not occur in `avoid`, returns variable itself.
Otherwise, generates and returns a similarly named variant that does
not occur in `avoid`.
Parameters:
avoid: Iterable.
Returns:
Variable itself or a similarly named variant.
See also:
:func:`Variable.get_variable`.
"""
return self.get_variant(lambda x: x.occurs_in(avoid))
def get_variant_not_bound_in(self, avoid):
"""Gets a variant that does not occur bound in `avoid`.
If variable does not occur bound in `avoid`, returns variable
itself. Otherwise, generates and returns a similarly named variant
that does not occur bound in `avoid`.
Parameters:
avoid: Iterable.
Returns:
Variable itself or a similarly named variant.
See also:
:func:`Variable.get_variable`.
"""
return self.get_variant(lambda x: x.occurs_bound_in(avoid))
def get_variant_not_free_in(self, avoid):
"""Gets a variant that does not occur free in `avoid`.
If variable does not occur free in `avoid`, returns variable itself.
Otherwise, generates and returns a similarly named variant that does