diff --git a/JavaExamples.java b/JavaExamples.java new file mode 100644 index 0000000..845ded3 --- /dev/null +++ b/JavaExamples.java @@ -0,0 +1,93 @@ +/// Java Examples +import java.util.*; +import qual.Immutable; +import qual.Mutable; + +public class JavaExamples { + // Mutating immut set, `s` is immut + void foo(@Immutable Set s) { + Set new_s = s; // Flow sensitive will refine this to @Immutable + @Mutable Set new_s1 = s; // ERROR, type incompatible + new_s.add("x"); // ERROR + } + + // Mutating immut set, `new_s` is immut + void foo1(@Mutable Set s) { + @Immutable Set new_s = new @Immutable HashSet<>(s); + Set new_s1 = s; // Flow sensitive will refine this to @Mutable + new_s.add("x"); // ERROR + new_s1.add("x"); //OK + } + + // Mutating mut set + void foo2(Set s) { + @Mutable Set new_s = new HashSet<>(s); + new_s.add("x"); // OK + } + + void foo3(List<@Immutable List> s, int l) { + List v = s.get(l); + @Mutable List v2 = s.get(l); // ERROR + v.add("x"); // ERROR + } + + void foo4(Person p) { + p.name = "Jenny"; // Ok, this should be forbid by compiler by adding final before String + p.family.add("Jenny"); // ERROR, can not mutate immut list + } + + void foo5(MutPerson p) { + p.name = "Jenny"; // OK + p.family.add("Jenny"); // OK + p.getFamily().add("Jenny"); // OK + } +} + +// Class and its immut members +class Person { + String name; // String is default @Immutable, use final to prevent reassignment + @Immutable List family; + + Person(String n, @Immutable List f) { + this.name = n; // OK + this.family = f; // OK + this.family.add("Mom"); // ERROR + } + + void setName(String n) { + this.name = n; // Ok, this should be forbid by compiler by adding final before String + } + + @Mutable List getFamily() { + return family; // ERROR, type incompatible + } +} + +// Class and its mut members +class MutPerson { + String name; // String is default @Immutable in PICO + @Mutable List family; + + MutPerson(String n, List f) { + this.name = n; // OK + this.family = f; // OK + this.family.add("Mom"); // OK + } + + void setName(String n) { + this.name = n; // OK + } + + List getFamily() { + return family; // OK + } +} + +class ImmutSet { + void foo1 (ImmutSet> s) { // ERROR + } + void foo2(MutList> s) { // OK + } +} + +@Mutable class MutList<@Mutable T> {}