-
Notifications
You must be signed in to change notification settings - Fork 56
/
operators.py
1098 lines (920 loc) · 32.4 KB
/
operators.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
#------------------------------------------------------------------------------------------#
# This file is part of Pyccel which is released under MIT License. See the LICENSE file or #
# go to https://github.com/pyccel/pyccel/blob/master/LICENSE for full license details. #
#------------------------------------------------------------------------------------------#
# TODO [EB 12.03.21]: Remove pylint command with PR #797
# pylint: disable=W0201
"""
Module handling all python builtin operators
These operators all have a precision as detailed here:
https://docs.python.org/3/reference/expressions.html#operator-precedence
They also have specific rules to determine the dtype, precision, rank, shape
"""
from ..errors.errors import Errors, PyccelSemanticError
from .basic import PyccelAstNode
from .datatypes import (NativeBool, NativeInteger, NativeReal,
NativeComplex, NativeString, default_precision,
NativeNumeric)
from .literals import Literal, LiteralInteger, LiteralFloat, LiteralComplex, Nil
from .literals import convert_to_literal
errors = Errors()
__all__ = (
'PyccelOperator',
'PyccelPow',
'PyccelAdd',
'PyccelMinus',
'PyccelMul',
'PyccelDiv',
'PyccelMod',
'PyccelFloorDiv',
'PyccelEq',
'PyccelNe',
'PyccelLt',
'PyccelLe',
'PyccelGt',
'PyccelGe',
'PyccelAnd',
'PyccelOr',
'PyccelNot',
'PyccelAssociativeParenthesis',
'PyccelUnary',
'PyccelUnarySub',
'Relational',
'PyccelIs',
'PyccelIsNot',
'IfTernaryOperator'
)
#==============================================================================
def broadcast(shape_1, shape_2):
""" This function broadcast two shapes using numpy broadcasting rules """
from pyccel.ast.sympy_helper import pyccel_to_sympy
a = len(shape_1)
b = len(shape_2)
if a>b:
new_shape_2 = (LiteralInteger(1),)*(a-b) + tuple(shape_2)
new_shape_1 = shape_1
elif b>a:
new_shape_1 = (LiteralInteger(1),)*(b-a) + tuple(shape_1)
new_shape_2 = shape_2
else:
new_shape_2 = shape_2
new_shape_1 = shape_1
new_shape = []
for e1,e2 in zip(new_shape_1, new_shape_2):
used_names = set()
symbol_map = {}
sy_e1 = pyccel_to_sympy(e1, symbol_map, used_names)
sy_e2 = pyccel_to_sympy(e2, symbol_map, used_names)
if sy_e1 == sy_e2:
new_shape.append(e1)
elif sy_e1 == 1:
new_shape.append(e2)
elif sy_e2 == 1:
new_shape.append(e1)
elif sy_e1.is_constant() and not sy_e2.is_constant():
new_shape.append(e1)
elif sy_e2.is_constant() and not sy_e1.is_constant():
new_shape.append(e2)
elif not sy_e2.is_constant() and not sy_e1.is_constant()\
and not (sy_e1 - sy_e2).is_constant():
new_shape.append(e1)
else:
shape1_code = '({})'.format(' '.join([str(s)+',' for s in shape_1]))
shape2_code = '({})'.format(' '.join([str(s)+',' for s in shape_2]))
msg = 'operands could not be broadcast together with shapes {} {}'
msg = msg.format(shape1_code, shape2_code)
raise PyccelSemanticError(msg)
return tuple(new_shape)
#==============================================================================
class PyccelOperator(PyccelAstNode):
"""
Abstract superclass for all builtin operators.
The __init__ function is common
but the functions called by __init__ are specialised
Parameters
----------
args: tuple
The arguments passed to the operator
"""
__slots__ = ('_args', )
_attribute_nodes = ('_args',)
def __init__(self, *args):
self._args = tuple(self._handle_precedence(args))
if self.stage == 'syntactic':
super().__init__()
return
self._set_dtype()
self._set_shape_rank()
# rank is None for lambda functions
self._set_order()
super().__init__()
def _set_dtype(self):
self._dtype, self._precision = self._calculate_dtype(*self._args) # pylint: disable=no-member
def _set_shape_rank(self):
self._shape, self._rank = self._calculate_shape_rank(*self._args) # pylint: disable=no-member
@property
def precedence(self):
""" The precedence of the operator as defined here:
https://docs.python.org/3/reference/expressions.html#operator-precedence
"""
return self._precedence
def _handle_precedence(self, args):
"""
Insert parentheses where necessary by examining the precedence of the operator
e.g:
PyccelMul(a,PyccelAdd(b,c))
means:
a*(b+c)
so this input will give:
PyccelMul(a, PyccelAssociativeParenthesis(PyccelAdd(b,c)))
Parentheses are also added were they are required for clarity
Parameters
----------
args: tuple
The arguments passed to the operator
Results
-------
args: tuple
The arguments with the parentheses inserted
"""
precedence = [getattr(a, 'precedence', 17) for a in args]
if min(precedence) <= self._precedence:
new_args = []
for i, (a,p) in enumerate(zip(args, precedence)):
if (p < self._precedence or (p == self._precedence and i != 0)):
new_args.append(PyccelAssociativeParenthesis(a))
else:
new_args.append(a)
args = tuple(new_args)
return args
def __str__(self):
return repr(self)
def _set_order(self):
""" Sets the shape and rank
This is chosen to match the arguments if they are in agreement.
Otherwise it defaults to 'C'
"""
if self._rank is not None and self._rank > 1:
orders = [a.order for a in self._args if a.order is not None]
my_order = orders[0]
if all(o == my_order for o in orders):
self._order = my_order
else:
self._order = 'C'
else:
self._order = None
@property
def args(self):
""" Arguments of the operator
"""
return self._args
#==============================================================================
class PyccelUnaryOperator(PyccelOperator):
""" Abstract superclass representing a python
operator with only one argument
Parameters
----------
arg: PyccelAstNode
The argument passed to the operator
"""
__slots__ = ('_dtype', '_precision','_shape','_rank','_order')
def __init__(self, arg):
super().__init__(arg)
@staticmethod
def _calculate_dtype(*args):
""" Sets the dtype and precision
They are chosen to match the argument
"""
a = args[0]
dtype = a.dtype
precision = a.precision
return dtype, precision
@staticmethod
def _calculate_shape_rank(*args):
""" Sets the shape and rank
They are chosen to match the argument
"""
a = args[0]
rank = a.rank
shape = a.shape
return shape, rank
#==============================================================================
class PyccelUnary(PyccelUnaryOperator):
"""
Class representing a call to the python positive operator.
I.e:
+a
is equivalent to:
PyccelUnary(a)
Parameters
----------
arg: PyccelAstNode
The argument passed to the operator
"""
__slots__ = ()
_precedence = 14
def _handle_precedence(self, args):
args = PyccelUnaryOperator._handle_precedence(self, args)
args = tuple(PyccelAssociativeParenthesis(a) if isinstance(a, PyccelUnary) else a for a in args)
return args
def __repr__(self):
return '+{}'.format(repr(self.args[0]))
#==============================================================================
class PyccelUnarySub(PyccelUnary):
"""
Class representing a call to the python negative operator.
I.e:
-a
is equivalent to:
PyccelUnarySub(a)
Parameters
----------
arg: PyccelAstNode
The argument passed to the operator
"""
__slots__ = ()
def __repr__(self):
return '-{}'.format(repr(self.args[0]))
#==============================================================================
class PyccelNot(PyccelUnaryOperator):
"""
Class representing a call to the python not operator.
I.e:
not a
is equivalent to:
PyccelNot(a)
Parameters
----------
arg: PyccelAstNode
The argument passed to the operator
"""
__slots__ = ()
_precedence = 6
@staticmethod
def _calculate_dtype(*args):
""" Sets the dtype and precision
They are chosen to match the argument unless the class has
a _dtype or _precision member
"""
dtype = NativeBool()
precision = default_precision['bool']
return dtype, precision
@staticmethod
def _calculate_shape_rank(*args):
""" Sets the shape and rank
They are chosen to match the argument unless the class has
a _shape or _rank member
"""
rank = 0
shape = ()
return shape, rank
def __repr__(self):
return 'not {}'.format(repr(self.args[0]))
#==============================================================================
class PyccelAssociativeParenthesis(PyccelUnaryOperator):
"""
Class representing parentheses
Parameters
----------
arg: PyccelAstNode
The argument in the PyccelAssociativeParenthesis
"""
__slots__ = () # ok
_precedence = 18
def _handle_precedence(self, args):
return args
def __repr__(self):
return '({})'.format(repr(self.args[0]))
#==============================================================================
class PyccelBinaryOperator(PyccelOperator):
""" Abstract superclass representing a python
operator with two arguments
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ('_dtype','_precision','_shape','_rank','_order')
def __init__(self, arg1, arg2, simplify = False):
super().__init__(arg1, arg2)
@classmethod
def _calculate_dtype(cls, *args):
""" Sets the dtype and precision
If one argument is a string then all arguments must be strings
If the arguments are numeric then the dtype and precision
match the broadest type and the largest precision
e.g.
1 + 2j -> PyccelAdd(LiteralInteger, LiteralComplex) -> complex
"""
integers = [a for a in args if a.dtype in (NativeInteger(),NativeBool())]
reals = [a for a in args if a.dtype is NativeReal()]
complexes = [a for a in args if a.dtype is NativeComplex()]
strs = [a for a in args if a.dtype is NativeString()]
if strs:
return cls._handle_str_type(strs)
assert len(integers + reals + complexes) == 0
elif complexes:
return cls._handle_complex_type(complexes)
elif reals:
return cls._handle_real_type(reals)
elif integers:
return cls._handle_integer_type(integers)
else:
raise TypeError('cannot determine the type of {}'.format(args))
@staticmethod
def _handle_str_type(strs):
"""
Set dtype and precision when both arguments are strings
"""
raise TypeError("unsupported operand type(s) for /: 'str' and 'str'")
@staticmethod
def _handle_complex_type(complexes):
"""
Set dtype and precision when the result is complex
"""
dtype = NativeComplex()
precision = max(a.precision for a in complexes)
return dtype, precision
@staticmethod
def _handle_real_type(reals):
"""
Set dtype and precision when the result is real
"""
dtype = NativeReal()
precision = max(a.precision for a in reals)
return dtype, precision
@staticmethod
def _handle_integer_type(integers):
"""
Set dtype and precision when the result is integer
"""
dtype = NativeInteger()
precision = max(a.precision for a in integers)
return dtype, precision
@staticmethod
def _calculate_shape_rank(*args):
""" Sets the shape and rank
Strings must be scalars.
For numeric types the rank and shape is determined according
to numpy broadcasting rules where possible
"""
strs = [a for a in args if a.dtype is NativeString()]
if strs:
other = [a for a in args if a.dtype in (NativeInteger(), NativeBool(), NativeReal(), NativeComplex())]
assert len(other) == 0
rank = 0
shape = ()
else:
ranks = [a.rank for a in args]
shapes = [a.shape for a in args]
if None in ranks:
rank = None
shape = None
elif all(sh is not None for tup in shapes for sh in tup):
s = broadcast(args[0].shape, args[1].shape)
shape = s
rank = len(s)
else:
rank = max(a.rank for a in args)
shape = [None]*rank
return shape, rank
#==============================================================================
class PyccelArithmeticOperator(PyccelBinaryOperator):
""" Abstract superclass representing a python
arithmetic operator
This class is necessary to handle specific precedence
rules for arithmetic operators
I.e. to handle the error:
Extension: Unary operator following arithmetic operator (use parentheses)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
def _handle_precedence(self, args):
args = PyccelBinaryOperator._handle_precedence(self, args)
args = tuple(PyccelAssociativeParenthesis(a) if isinstance(a, PyccelUnary) else a for a in args)
return args
#==============================================================================
class PyccelPow(PyccelArithmeticOperator):
"""
Class representing a call to the python exponent operator.
I.e:
a ** b
is equivalent to:
PyccelPow(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
_precedence = 15
def __repr__(self):
return '{} ** {}'.format(self.args[0], self.args[1])
#==============================================================================
class PyccelAdd(PyccelArithmeticOperator):
"""
Class representing a call to the python addition operator.
I.e:
a + b
is equivalent to:
PyccelAdd(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
_precedence = 12
def __new__(cls, arg1, arg2, simplify = False):
if simplify:
if isinstance(arg2, PyccelUnarySub):
return PyccelMinus(arg1, arg2.args[0], simplify = True)
dtype, precision = cls._calculate_dtype(arg1, arg2)
if isinstance(arg1, Literal) and isinstance(arg2, Literal):
return convert_to_literal(arg1.python_value + arg2.python_value,
dtype, precision)
if dtype == arg2.dtype and precision == arg2.precision and \
isinstance(arg1, Literal) and arg1.python_value == 0:
return arg2
if dtype == arg1.dtype and precision == arg1.precision and \
isinstance(arg2, Literal) and arg2.python_value == 0:
return arg1
if isinstance(arg1, (LiteralInteger, LiteralFloat)) and \
isinstance(arg2, LiteralComplex) and \
arg2.real == LiteralFloat(0):
return LiteralComplex(arg1, arg2.imag)
elif isinstance(arg2, (LiteralInteger, LiteralFloat)) and \
isinstance(arg1, LiteralComplex) and \
arg1.real == LiteralFloat(0):
return LiteralComplex(arg2, arg1.imag)
else:
return super().__new__(cls)
@staticmethod
def _handle_str_type(strs):
dtype = NativeString()
precision = None
return dtype, precision
def __repr__(self):
return '{} + {}'.format(self.args[0], self.args[1])
#==============================================================================
class PyccelMul(PyccelArithmeticOperator):
"""
Class representing a call to the python multiplication operator.
I.e:
a * b
is equivalent to:
PyccelMul(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
_precedence = 13
def __new__(cls, arg1, arg2, simplify = False):
if simplify:
if (arg1 == 1):
return arg2
if (arg2 == 1):
return arg1
if (arg1 == 0 or arg2 == 0):
dtype, precision = cls._calculate_dtype(arg1, arg2)
return convert_to_literal(0, dtype, precision)
if (isinstance(arg1, PyccelUnarySub) and arg1.args[0] == 1):
return PyccelUnarySub(arg2)
if (isinstance(arg2, PyccelUnarySub) and arg2.args[0] == 1):
return PyccelUnarySub(arg1)
if isinstance(arg1, Literal) and isinstance(arg2, Literal):
dtype, precision = cls._calculate_dtype(arg1, arg2)
return convert_to_literal(arg1.python_value * arg2.python_value,
dtype, precision)
return super().__new__(cls)
def __repr__(self):
return '{} * {}'.format(self.args[0], self.args[1])
#==============================================================================
class PyccelMinus(PyccelArithmeticOperator):
"""
Class representing a call to the python subtraction operator.
I.e:
a - b
is equivalent to:
PyccelMinus(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
_precedence = 12
def __new__(cls, arg1, arg2, simplify = False):
if simplify:
if isinstance(arg2, PyccelUnarySub):
return PyccelAdd(arg1, arg2.args[0], simplify = True)
elif isinstance(arg1, Literal) and isinstance(arg2, Literal):
dtype, precision = cls._calculate_dtype(arg1, arg2)
return convert_to_literal(arg1.python_value - arg2.python_value,
dtype, precision)
if isinstance(arg1, LiteralFloat) and \
isinstance(arg2, LiteralComplex) and \
arg2.real == LiteralFloat(0):
return LiteralComplex(arg1, -arg2.imag.python_value)
elif isinstance(arg2, LiteralFloat) and \
isinstance(arg1, LiteralComplex) and \
arg1.real == LiteralFloat(0):
return LiteralComplex(-arg2.python_value, arg1.imag)
else:
return super().__new__(cls)
def __repr__(self):
return '{} - {}'.format(repr(self.args[0]), repr(self.args[1]))
#==============================================================================
class PyccelDiv(PyccelArithmeticOperator):
"""
Class representing a call to the python division operator.
I.e:
a / b
is equivalent to:
PyccelDiv(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
_precedence = 13
def __new__(cls, arg1, arg2, simplify=False):
if simplify:
if (arg2 == 1):
return arg1
return super().__new__(cls)
@staticmethod
def _handle_integer_type(integers):
dtype = NativeReal()
precision = default_precision['real']
return dtype, precision
def __repr__(self):
return '{} + {}'.format(self.args[0], self.args[1])
def __repr__(self):
return '{} / {}'.format(self.args[0], self.args[1])
#==============================================================================
class PyccelMod(PyccelArithmeticOperator):
"""
Class representing a call to the python modulo operator.
I.e:
a % b
is equivalent to:
PyccelMod(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
_precedence = 13
def __repr__(self):
return '{} % {}'.format(self.args[0], self.args[1])
#==============================================================================
class PyccelFloorDiv(PyccelArithmeticOperator):
"""
Class representing a call to the python integer division operator.
I.e:
a // b
is equivalent to:
PyccelFloorDiv(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
_precedence = 13
def __repr__(self):
return '{} // {}'.format(self.args[0], self.args[1])
#==============================================================================
class PyccelComparisonOperator(PyccelBinaryOperator):
""" Abstract superclass representing a python
comparison operator with two arguments
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
_precedence = 7
@staticmethod
def _calculate_dtype(*args):
dtype = NativeBool()
precision = default_precision['bool']
return dtype, precision
#==============================================================================
class PyccelEq(PyccelComparisonOperator):
"""
Class representing a call to the python equality operator.
I.e:
a == b
is equivalent to:
PyccelEq(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
def __repr__(self):
return '{} == {}'.format(self.args[0], self.args[1])
class PyccelNe(PyccelComparisonOperator):
"""
Class representing a call to the python inequality operator.
I.e:
a != b
is equivalent to:
PyccelEq(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
def __repr__(self):
return '{} != {}'.format(self.args[0], self.args[1])
class PyccelLt(PyccelComparisonOperator):
"""
Class representing a call to the python less than operator.
I.e:
a < b
is equivalent to:
PyccelEq(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
def __repr__(self):
return '{} < {}'.format(self.args[0], self.args[1])
class PyccelLe(PyccelComparisonOperator):
"""
Class representing a call to the python less or equal operator.
I.e:
a <= b
is equivalent to:
PyccelEq(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
def __repr__(self):
return '{} <= {}'.format(self.args[0], self.args[1])
class PyccelGt(PyccelComparisonOperator):
"""
Class representing a call to the python greater than operator.
I.e:
a > b
is equivalent to:
PyccelEq(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
def __repr__(self):
return '{} > {}'.format(self.args[0], self.args[1])
class PyccelGe(PyccelComparisonOperator):
"""
Class representing a call to the python greater or equal operator.
I.e:
a >= b
is equivalent to:
PyccelEq(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
def __repr__(self):
return '{} >= {}'.format(self.args[0], self.args[1])
#==============================================================================
class PyccelBooleanOperator(PyccelOperator):
""" Abstract superclass representing a python
boolean operator with two arguments
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
dtype = NativeBool()
precision = default_precision['bool']
rank = 0
shape = ()
order = None
__slots__ = ()
def _set_order(self):
pass
def _set_dtype(self):
pass
def _set_shape_rank(self):
pass
#==============================================================================
class PyccelAnd(PyccelBooleanOperator):
"""
Class representing a call to the python AND operator.
I.e:
a and b
is equivalent to:
PyccelAnd(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
_precedence = 5
def _handle_precedence(self, args):
args = PyccelBooleanOperator._handle_precedence(self, args)
args = tuple(PyccelAssociativeParenthesis(a) if isinstance(a, PyccelOr) else a for a in args)
return args
def __repr__(self):
return '{} and {}'.format(self.args[0], self.args[1])
#==============================================================================
class PyccelOr(PyccelBooleanOperator):
"""
Class representing a call to the python OR operator.
I.e:
a or b
is equivalent to:
PyccelOr(a, b)
Parameters
----------
arg1: PyccelAstNode
The first argument passed to the operator
arg2: PyccelAstNode
The second argument passed to the operator
"""
__slots__ = ()
_precedence = 4
def _handle_precedence(self, args):
args = PyccelBooleanOperator._handle_precedence(self, args)
args = tuple(PyccelAssociativeParenthesis(a) if isinstance(a, PyccelAnd) else a for a in args)
return args
def __repr__(self):
return '{} or {}'.format(self.args[0], self.args[1])
#==============================================================================
class PyccelIs(PyccelBooleanOperator):
"""Represents a is expression in the code.
Examples
--------
>>> from pyccel.ast.operators import PyccelIs
>>> from pyccel.ast.literals import Nil
>>> from pyccel.ast.internals import PyccelSymbol
>>> x = PyccelSymbol('x')
>>> PyccelIs(x, Nil())
PyccelIs(x, None)
"""
__slots__ = ()
_precedence = 7
def __init__(self, arg1, arg2):
super().__init__(arg1, arg2)
@property
def lhs(self):
""" First operator argument"""
return self._args[0]
@property
def rhs(self):
""" First operator argument"""
return self._args[1]
def __repr__(self):
return '{} is {}'.format(self.args[0], self.args[1])
#==============================================================================
class PyccelIsNot(PyccelIs):
"""Represents a is expression in the code.
Examples
--------
>>> from pyccel.ast.operators import PyccelIsNot
>>> from pyccel.ast.literals import Nil
>>> from pyccel.ast.internals import PyccelSymbol
>>> x = PyccelSymbol('x')
>>> PyccelIsNot(x, Nil())
PyccelIsNot(x, None)
"""