Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add some examples #48

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions JavaExamples.java
Original file line number Diff line number Diff line change
@@ -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<String> s) {
Set<String> new_s = s; // Flow sensitive will refine this to @Immutable
@Mutable Set<String> new_s1 = s; // ERROR, type incompatible
new_s.add("x"); // ERROR
}

// Mutating immut set, `new_s` is immut
void foo1(@Mutable Set<String> s) {
@Immutable Set<String> new_s = new @Immutable HashSet<>(s);
Set<String> 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<String> s) {
@Mutable Set<String> new_s = new HashSet<>(s);
new_s.add("x"); // OK
}

void foo3(List<@Immutable List<String>> s, int l) {
List<String> v = s.get(l);
@Mutable List<String> 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<String> family;

Person(String n, @Immutable List<String> 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<String> getFamily() {
return family; // ERROR, type incompatible
}
}

// Class and its mut members
class MutPerson {
String name; // String is default @Immutable in PICO
@Mutable List<String> family;

MutPerson(String n, List<String> f) {
this.name = n; // OK
this.family = f; // OK
this.family.add("Mom"); // OK
}

void setName(String n) {
this.name = n; // OK
}

List<String> getFamily() {
return family; // OK
}
}

class ImmutSet<T> {
void foo1 (ImmutSet<MutList<T>> s) { // ERROR
}
void foo2(MutList<ImmutSet<T>> s) { // OK
}
}

@Mutable class MutList<@Mutable T> {}
Loading