- Timestamp:
- Nov 24, 2017, 2:28:57 PM (7 years ago)
- Branches:
- ADT, aaron-thesis, arm-eh, ast-experimental, cleanup-dtors, deferred_resn, demangler, enum, forall-pointer-decay, jacob/cs343-translation, jenkins-sandbox, master, new-ast, new-ast-unique-expr, new-env, no_list, persistent-indexer, pthread-emulation, qualifiedEnum, resolv-new, with_gc
- Children:
- 3de176d
- Parents:
- 178e4ec
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
src/tests/polymorphism.c
r178e4ec r3787dc1 14 14 // 15 15 16 #include <assert.h> 17 #include <inttypes.h> 18 16 19 forall(otype T) 17 20 T f(T x, T y) { … … 24 27 } 25 28 29 forall( otype T, otype U ) 30 size_t struct_size( T i, U j ) { 31 struct S { T i; U j; }; 32 return sizeof(S); 33 } 34 35 forall( otype T, otype U ) 36 size_t union_size( T i, U j ) { 37 union B { T i; U j; }; 38 return sizeof(B); 39 } 40 41 // perform some simple operations on aggregates of T and U 42 forall( otype T | { void print(T); int ?==?(T, T); }, otype U | { void print(U); U ?=?(U&, zero_t); } ) 43 U foo(T i, U j) { 44 struct S { T i; U j; }; 45 union B { T i; U j; }; 46 47 S s; 48 s.i = i; 49 assert(s.i == i); 50 51 B b; 52 b.j = 0; 53 b.i = s.i; 54 return b.j; 55 } 56 26 57 int main() { 27 // ensure that x is not changed by the invocation of a polymorphic function 28 int x = 123; 29 int y = 456; 30 int z = f(x, y); 31 printf("%d %d %d\n", x, y, z); 58 { 59 // ensure that x is not changed by the invocation of a polymorphic function 60 int x = 123; 61 int y = 456; 62 int z = f(x, y); 63 printf("%d %d %d\n", x, y, z); 64 } 32 65 33 // explicitly specialize function 34 int (*f)(int) = ident; 35 ((int(*)(int))ident); 36 printf("%d %d\n", f(5), ((int(*)(int))ident)(5)); 66 { 67 // explicitly specialize function 68 int (*f)(int) = ident; 69 ((int(*)(int))ident); 70 printf("%d %d\n", f(5), ((int(*)(int))ident)(5)); 71 } 72 73 { 74 // test aggregates with polymorphic members 75 typedef uint32_t x_type; 76 typedef uint64_t y_type; 77 78 x_type x = 3; 79 y_type y = 3; 80 81 struct S { 82 x_type f1; 83 y_type f2; 84 }; 85 union U { 86 x_type f1; 87 y_type f2; 88 }; 89 // ensure that the size of aggregates with polymorphic members 90 // matches the size of the aggregates in a monomorphic context 91 assert( struct_size(x, y) == sizeof(S) ); 92 assert( union_size(x, y) == sizeof(U) ); 93 94 y_type ?=?(y_type & this, zero_t) { 95 this = (int)0; 96 return this; 97 } 98 99 void print(x_type x) { 100 printf("%"PRIu32"\n", x); 101 } 102 103 void print(y_type y) { 104 printf("%"PRIu64"\n", y); 105 } 106 107 y_type ret = foo(x, y); 108 109 // duplicate logic from inside of foo to ensure the same results 110 U u; 111 u.f2 = 0; 112 u.f1 = x; 113 assert(ret == u.f2); 114 } 37 115 } 38 116
Note: See TracChangeset
for help on using the changeset viewer.