Rune - Further Object abstraction work
[rune.git] / tests / operator.d
1 #!/usr/local/bin/rune -x
2 #
3 #       Demonstrate a user-defined operator.  We demonstrate two types
4 #       of operators.. one which is pass-by-value, another which is
5 #       pass-by-reference.
6
7 import "sys";
8 import <stdio>;
9
10 alias stdio.File @stdout = stdio.stdout;
11
12 class Test {
13     int a;
14     int b;
15
16     public operator "+++"
17     Test
18     myfunc (Test lhs, Test rhs) {
19         lhs.a = lhs.a + rhs.a;
20         lhs.b = lhs.b - rhs.b;
21         return(lhs);
22     }
23
24     public operator "%%="
25     lvalue void
26     myfunc (lvalue Test lhs, int rhs) {
27         lhs.a = lhs.a + rhs;
28         lhs.b = lhs.b * rhs;
29         return(lhs);
30     }
31 }
32
33 # Rune is allowed to optimize a procedure's return value if the procedure
34 # returns a const (e.g. char * const or const int, NOT const char *)
35 # and the arguments supplied to the procedure are constants or constant
36 # evaluated expressions.  This works recursively and can massively optimize
37 # the code.
38
39 pure int
40 blech(int lhs, int rhs) 
41 {
42     stdout->show("this message should only print twice");
43     return(lhs + rhs);
44 }
45
46 int
47 main(int ac, string_p *av)
48 {
49     Test x;
50     Test y;
51     Test z;
52     int i;
53
54     x.a = 5;
55     x.b = 6;
56     y.a = 7;
57     y.b = 8;
58     z = x +++ y;        # z should be (12, -2)
59     z %%= 23;           # z should be (35, -46)
60     stdout->show("z.a (should be 35) ", z.a, " z.b (should be -46) ", z.b);
61
62     stdout->show("looping ", blech(10000000, 1));
63
64
65     # Rune should be able to optimize out the call to blech()
66     #
67     for (i = 0; i < blech(10000000, 1); ++i)
68         ;
69
70     const char *str;
71     char c;
72
73     str = "abcd" + 4;
74     for (i = 0; i < 4; ++i) {
75         stdout->fputc(*--str);
76     }
77     stdout->fputc('\n');
78
79     return(0);
80 }