Algorithmcore
Rapid type analysis
Build a call graph like class hierarchy analysis, but let a virtual call reach only the classes that some reachable method creates with new.
- Solves
- Call graph construction
- Time
- O(n + S K + K M) worst
- Space
- O(S K + K M) extra
- Where
- K = the number of classes; M = the number of method names; S = the number of call sites; n = the size of the program
- Model
- Word RAM
- Properties
- not context sensitivedeterministicnot flow sensitiveofflineiterative
- Evidence
- Full proofCode in 1 languages
- Origin
- David F. Bacon, Peter F. Sweeney, 1996
Rapid type analysis (RTA) is a solution of call graph construction for object-oriented programs that refines class hierarchy analysis with one global set: the classes that the program creates. A virtual call y.m(z) may reach the method m of a class only if that class is at or below the declared class of y and some reachable method contains new of that class. The graph is built on the fly from main, so a class created only in dead code does not count. RTA costs about the same as CHA, it is sound for type-safe programs without reflection, and its graph is always inside the CHA graph.
In plain words
Class hierarchy analysis assumes that a variable of type Shape can hold any kind of shape. But a program that never writes new Oval() can never hold an Oval. Rapid type analysis keeps a list of the classes that the program creates, and it only follows calls into methods of those classes. It starts at main and keeps a to-do list of methods to read. When a method creates a new class, the analysis goes back to the calls it has already seen and adds the new targets. When it sees a new call, it uses all the classes found so far. When the to-do list is empty, the graph is done.
The problem
The input is a program in the model of class hierarchy analysis: classes with single inheritance and the order , method bodies with x = new C(), x = y, x = y.f, y.f = z and virtual calls x = y.m(z) at sites , a declared class for each variable, the dispatch function and the root main. The program is well typed. The output is the pair of the least triple of methods, classes and edges with these rules:
- ;
- if a method of contains
x = new C(), then ; - if a method of contains the site :
x = y.m(z), and , then and .
| item | value |
|---|---|
| direction | none: flow-insensitive, one answer for the whole program |
| may or must | may |
| domain | triples of reachable methods, created classes and call edges |
| order | inclusion of all three parts (bottom is precise) |
| join | union of all three parts |
| bottom and top | and all methods, all classes, all edges |
| boundary value | |
| initial value | , , |
| transfer | rules 2 and 3; monotone, not distributive, since rule 3 needs a site of and a class of at once |
The algorithm
RTA(P)- 1
R <- {main}; W <- [main]; E <- {}; I <- {}; S <- {} - 2
while W is not empty do - 3
take a method M from W - 4
for each statement x = new C() in M do - 5
if C is not in I then add C to I - 6
for each site s: x = y.m(z) in S with C <= decl(y) do - 7
ADD(s, LOOKUP(C, m)) - 8
for each call site s: x = y.m(z) in M do - 9
add s to S - 10
for each class C in I with C <= decl(y) do - 11
ADD(s, LOOKUP(C, m)) - 12
return (R, E) ADD(s, T)- 13
add (s, T) to E - 14
if T is not in R then add T to R and to W
holds the classes created so far, and holds the call sites seen so far. Lines L4 to L7 handle a class that appears late: every site seen before gets the targets for the new class. Lines L8 to L11 handle a site that appears late: it gets the targets for every class created before. So each pair of a site and a class is examined once, by whichever of the two arrives second. LOOKUP and the subclass test use tables built once, as in class hierarchy analysis.
Example
The program of the call graph construction page:
class Shape { Shape grow() { return this; } }
class Circle : Shape { Shape grow() { return new Square(); } }
class Square : Shape { Shape grow() { return this; } }
class Oval : Circle { }
main() {
Shape a = new Circle();
Shape b = new Square();
Shape c = a.grow(); // site s1
Shape d = b.grow(); // site s2
Shape e = c.grow(); // site s3
}
| step | method taken | what happens | after the step |
|---|---|---|---|
| 1 | main | lines L4 to L7: , no sites seen yet; lines L8 to L11: s1, s2 and s3 each get edges to Circle.grow and Square.grow |
Circle.grow, Square.grow |
| 2 | Square.grow | no new, no sites |
Circle.grow |
| 3 | Circle.grow | new Square(), but Square is already in |
empty |
The result has 3 reachable methods and 6 edges. Class hierarchy analysis gives 4 methods and 9 edges: RTA drops Shape.grow, because no reachable code creates a plain Shape, and it drops the 3 edges to it. The run makes 3 of the 6 edges: s1 to Circle.grow, and s2 and s3 to Square.grow. The edge from s1 to Square.grow is spurious, because RTA does not know that a holds only a Circle. Variable type analysis removes it.
Correctness
Least solution. Each class enters once and each site enters once. The invariant is: for each site in and each class in below its declared class, the edge is in . Line L7 keeps it when a class arrives, and line L11 keeps it when a site arrives. When is empty, holds all sites of and holds all classes created in , so the three rules hold. Every edge that the algorithm adds is forced by the rules, so the result is the least solution.
Soundness. Take a well-typed program without reflection, native code or classes loaded at run time. By induction over the steps of a run: every object is created by a new in a method that the run entered, which is in , so its class is in . At a call y.m(z), the receiver has a class , and type safety gives . So rule 3 puts the call in and the callee in .
Inside CHA. The CHA result with set to all classes satisfies the three rules. The RTA result is the least triple that satisfies them, so it is inside the CHA result. The full proofs are in the proof file.
Proof: Rapid type analysis computes the least closed call graph, it is sound for well-typed programs, and it is inside class hierarchy analysisfull
Setting. The program, , , and well typed are as in the proof of class hierarchy analysis. The program has no reflection, no native code and no classes loaded at run time: every object of a run comes from the execution of a statement x = new C() of the text, and every call of a run is the execution of a call site of the text. A triple of methods, classes and edges is closed if
- ;
- for every method and every statement
x = new C()in , ; - for every method , every site :
x = y.m(z)in and every with , the edge is in and .
is defined in rule 3, because and defines .
Lemma 1 (termination). Each method enters at most once, so the loop of line L2 runs at most times, for the set of methods. Each class enters at most once, and each site enters at most once.
Proof. A method enters only in line L1 or line L14, and line L14 adds it to in the same step, only if it was not in . Methods never leave . A class enters in line L5 only if it is not in . A site enters in line L9 when its method is taken from , which happens once.
Lemma 2 (the invariant). At each test of line L2: (a) ; (b) is the set of classes such that some method of has a statement x = new C(), and is the set of sites of the methods of ; (c) for every site : x = y.m(z) in and every with , and .
Proof. At the start, , and are empty, so (b) and (c) hold, and . Take one pass of the loop, with method . Part (a) holds because line L14 adds a method to and to together. Lines L4 and L5 add the classes created in to , and line L9 adds the sites of to , while leaves in line L3. This gives (b). For (c), take a site in and a class in with , after the pass. There are three cases. If both were there before the pass, (c) held before, and sets only grow. If was in before and entered in this pass, line L6 visited when entered, and line L7 added the edge. If entered in this pass, lines L4 to L7 ran before, so was in when line L10 ran for , and line L11 added the edge. In each case, ADD put the target in (line L14).
Lemma 3 (every fact is forced). Let be any closed triple. At all times, , and .
Proof. At the start, by rule 1, and and are empty. Line L5 adds a class created in a method , which is in by rule 2. Lines L7 and L11 call ADD with a site of a method of , a class with and . By the induction hypothesis the method is in and , so rule 3 gives and .
Theorem 1 (least closed triple). The algorithm stops and returns of the least closed triple, and its is the of that triple.
Proof. It stops by Lemma 1. At the end is empty, so by Lemma 2 rule 2 holds (part (b)) and rule 3 holds (part (c), with the sites of all of ). Rule 1 holds from line L1. So is closed, and by Lemma 3 it is inside every closed triple. The intersection of all closed triples is closed, because each rule instance holds in each of them, so the least closed triple exists, and it is .
Lemma 4 (type safety). In every run of a well-typed program, every variable of declared class and every field of type holds null or an object of a class .
Proof. This is Lemma 4 of the proof of class hierarchy analysis. It does not use any part of the analysis.
Theorem 2 (soundness). In every run, every object has a class in , every method that the run enters is in , and every call from a site to a method has .
Proof. By induction over the steps of the run. The run starts in . A step x = new C() runs in a frame of a method that the run entered, so by the induction hypothesis, and by rule 2. A call at site : x = y.m(z) runs in a frame of a method . Its receiver is an object that an earlier step created, so its class is in , and by Lemma 4. The method that runs is , so rule 3 gives and .
Theorem 3 (inside class hierarchy analysis). Let be the result of class hierarchy analysis. Then and .
Proof. Let be the set of all classes. The triple is closed. Rule 1 holds since . Rule 2 holds since contains every class. For rule 3, take a site of a method of and . Then is in the CHA target set of , so the CHA closure rule puts the edge in and the target in . By Theorem 1 the RTA result is inside every closed triple, so it is inside this one.
Theorem 4 (cost). After a dispatch table of and a subclass test in are built, the algorithm runs in time, where is the size of the program, the number of sites and the number of classes.
Proof. By Lemma 1, each body is read once in lines L4 and L8, which costs in total. Each pair of a site and a class is examined at most once: in line L6 if entered before entered , and in line L10 otherwise. Each class enters once and each site enters once, so no pair is examined twice. Each examination is a subclass test, a table lookup and at most one ADD, all in with hashing or direct indexing for and . So lines L6, L7, L10 and L11 cost in total. The table takes time for method names, filled from the root down as in the proof of class hierarchy analysis, and a bit matrix for the subclass test takes time and space. A hash set of the classes below each class takes for a class tree of height and gives the same test in expected .
Complexity
Proved. Each body is read once, which costs . Each pair of a site and a class is examined once, in line L6 or in line L10, with work, which costs . The dispatch table costs time and space. So the time is , with direct indexing for , and (or hashing, in expectation). The space is for the edges and for the table. This is the same bound as CHA.
Measured, not proved. On 500 random well-typed programs with up to 7 classes (seed 1996), the result equals that of a plain round-robin iteration of the three rules. On 300 random programs with 5 concrete runs each (seed 78), every call that a run makes is in . On 300 random programs (seed 6), the RTA graph is inside the CHA graph, and it is strictly smaller on some of them.
Properties
- Sound under type safety and a closed world. The proof needs every object to come from a
newof the analysed text. - Inside CHA. For every program, and .
- One set for the whole program. All variables share the same set . A class created anywhere in reachable code is a possible receiver of every call whose declared type is above it.
- Not distributive. An edge needs a site and a class, which may come from different paths. So the analysis has a real fixed point, but it is reached in one pass over each method because of lines L6 and L7.
Variants and improvements
- Whole-program instantiation. Count the classes created anywhere in the program text, not only in reachable methods. This needs no on-the-fly graph and gives a graph between RTA and CHA.
- One set per method or per field. Tip and Palsberg give each method, each field or each class its own set of classes and propagate classes along the call edges and field accesses. These variants lie between RTA and variable type analysis.
- Type propagation per variable. Variable type analysis keeps a set of classes for each variable and field.
- Points-to based graphs. A points-to analysis keeps sets of allocation sites instead of classes and builds the call graph at the same time.
- Dead code removal. A method outside cannot run. A linker or a tree shaker can drop it (dead code elimination).
When to use it
Use RTA when you need a sound call graph for a whole program and CHA keeps too many targets, for example when the program uses a large library but creates few of its classes. RTA costs almost the same as CHA and has no per-variable state. It is a good initial graph for variable type analysis or for a points-to analysis. If you analyse a library without its clients, every class that client code may create must be in from the start, and then RTA gains little over CHA.
Pitfalls
- No back-patching of earlier sites. A version without lines L6 and L7 handles only the sites seen after a class is created. If
maincallsa.m()and only then reaches a method that creates a subclassBthat overridesm, the edge toB.mis lost, and the graph is unsound. Lines L6 and L7 must revisit the sites in for each new class. - Objects that no
newcreates. Reflection (Class.newInstance), deserialization,cloneand native code create objects without anewstatement in the text. Their classes never enter in line L5, and the calls on them are missing. Add these classes to by hand or treat the program as outside the soundness claim. - Forgetting the constructor and static calls. In a real language,
new C()also calls the constructor of and its superclasses, and the first use of may run its static initializer. These are direct calls. Add them to and their methods to when line L5 runs, or the methods they call are missed. - Testing the class of the declared type only. Line L10 must test for every created class, not . A variable declared as
Shapecan hold aCircle.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A small object-oriented program model, for the call graph pages.
A program is a dict with these keys:
"classes" dict from each class name to its parent, None for the root.
"methods" dict from each method name m to (decl, ptype, rtype): the
class that introduces m, the declared type of its parameter
p and the declared type of its result.
"fields" dict from each field name f to (decl, ftype): the class that
declares f and the declared type of f.
"bodies" dict from each method id (C, m), the method m as class C
defines it, to (locals, stmts). The root is MAIN, a static
method with no this, p or ret. locals maps each variable to
its declared class. Every other body has the variables
"this" (of type C), "p" and "ret" among its locals.
The statements are tuples:
("new", x, C) x = new C()
("copy", x, y) x = y
("load", x, y, f) x = y.f
("store", y, f, z) y.f = z
("call", s, x, y, m, z) x = y.m(z) at call site s; x or z may be None
A method returns the value of its variable ret. The programs of
random_program are well typed in the sense of Java: a variable or field only
receives objects of its declared class or of a subclass, and a call y.m(z)
has decl(y) <= decl(m), so the dispatch always finds a method.
lookup(prog, C, m) is the method that runs for m on an object of class C.
run(prog, rng) runs the program concretely and returns the call edges and
the methods that the run saw. cha_spec and rta_spec are slow reference
versions of class hierarchy analysis and rapid type analysis: they apply
their rules to every reachable method, round after round, until nothing
changes.
"""
MAIN = ("Main", "main")
def is_sub(prog, c, d):
"""True if class c is d or a subclass of d."""
while c is not None:
if c == d:
return True
c = prog["classes"][c]
return False
def subclasses(prog):
"""A dict from each class d to the set of classes c with c <= d."""
below = {d: set() for d in prog["classes"]}
for c in prog["classes"]:
a = c
while a is not None:
below[a].add(c)
a = prog["classes"][a]
return below
def lookup(prog, c, m):
"""The method id that runs when m is called on an object of class c."""
while c is not None:
if (c, m) in prog["bodies"]:
return (c, m)
c = prog["classes"][c]
raise KeyError(f"no method {m} above the class")
def call_sites(prog, mid):
"""The call statements of the body of mid."""
return [st for st in prog["bodies"][mid][1] if st[0] == "call"]
def all_sites(prog):
"""A dict from each call site to (method id, statement)."""
out = {}
for mid, (_, stmts) in prog["bodies"].items():
for st in stmts:
if st[0] == "call":
out[st[1]] = (mid, st)
return out
def shapes():
"""The example of the call graph pages: Shape, Circle, Square, Oval."""
S = "Shape"
return {
"classes": {S: None, "Circle": S, "Square": S, "Oval": "Circle"},
"methods": {"grow": (S, S, S)},
"fields": {},
"bodies": {
(S, "grow"): ({"this": S, "p": S, "ret": S}, [("copy", "ret", "this")]),
("Circle", "grow"): ({"this": "Circle", "p": S, "ret": S}, [("new", "ret", "Square")]),
("Square", "grow"): ({"this": "Square", "p": S, "ret": S}, [("copy", "ret", "this")]),
MAIN: (
{"a": S, "b": S, "c": S, "d": S, "e": S},
[
("new", "a", "Circle"),
("new", "b", "Square"),
("call", "s1", "c", "a", "grow", None),
("call", "s2", "d", "b", "grow", None),
("call", "s3", "e", "c", "grow", None),
],
),
},
}
def random_program(rng, nclasses=5, nmethods=3, nfields=2, nstmts=6):
"""A random well-typed program. rng is a random.Random."""
names = ["K%d" % i for i in range(nclasses)]
classes = {names[0]: None}
for i in range(1, nclasses):
classes[names[i]] = names[rng.randrange(i)]
prog = {"classes": classes, "methods": {}, "fields": {}, "bodies": {}}
below = subclasses(prog)
for i in range(nmethods):
prog["methods"]["m%d" % i] = (rng.choice(names), rng.choice(names), rng.choice(names))
for i in range(nfields):
prog["fields"]["f%d" % i] = (rng.choice(names), rng.choice(names))
sites = [0]
def body(this, ptype, rtype, count):
local = {"v%d" % i: rng.choice(names) for i in range(3)}
if this is not None:
local.update({"this": this, "p": ptype, "ret": rtype})
allv = list(local)
dest = [v for v in allv if v != "this"]
def sub_vars(t):
return [v for v in allv if is_sub(prog, local[v], t)]
def super_vars(t):
return [v for v in dest if is_sub(prog, t, local[v])]
stmts = []
if this is None: # main starts by making objects for two variables
stmts = [("new", x, rng.choice(sorted(below[local[x]]))) for x in rng.sample(dest, 2)]
while len(stmts) < count:
kind = rng.choices(["new", "copy", "load", "store", "call"], (3, 3, 2, 2, 4))[0]
if kind == "new":
x = rng.choice(dest)
stmts.append(("new", x, rng.choice(sorted(below[local[x]]))))
elif kind == "copy":
x = rng.choice(dest)
ys = sub_vars(local[x])
if ys:
stmts.append(("copy", x, rng.choice(ys)))
elif kind in ("load", "store"):
if not prog["fields"]:
continue
f = rng.choice(sorted(prog["fields"]))
fdecl, ftype = prog["fields"][f]
ys = sub_vars(fdecl)
if not ys:
continue
if kind == "load":
xs = super_vars(ftype)
if xs:
stmts.append(("load", rng.choice(xs), rng.choice(ys), f))
else:
zs = sub_vars(ftype)
if zs:
stmts.append(("store", rng.choice(ys), f, rng.choice(zs)))
else:
m = rng.choice(sorted(prog["methods"]))
mdecl, pt, rt = prog["methods"][m]
ys = sub_vars(mdecl)
if not ys:
continue
zs = sub_vars(pt)
xs = super_vars(rt)
z = rng.choice(zs) if zs and rng.random() < 0.8 else None
x = rng.choice(xs) if xs and rng.random() < 0.8 else None
sites[0] += 1
stmts.append(("call", "s%d" % sites[0], x, rng.choice(ys), m, z))
return local, stmts
for m, (mdecl, pt, rt) in sorted(prog["methods"].items()):
for c in sorted(below[mdecl]):
if c == mdecl or rng.random() < 0.4:
prog["bodies"][(c, m)] = body(c, pt, rt, rng.randint(1, nstmts))
prog["bodies"][MAIN] = body(None, None, None, nstmts + 2)
return prog
class _Stop(Exception):
pass
def run(prog, rng, steps=300, depth=6, skip=0.25):
"""One concrete run from MAIN. Variables start as null. Each statement is
skipped with probability skip, and each body runs once or twice, which
stands for branches and loops. A call on null or a field access on null
is skipped, as if the program caught the exception. Returns (edges,
entered): the pairs (site, method id) that the run executed and the
methods it entered."""
heap = []
edges, entered = set(), {MAIN}
budget = [steps]
def execute(mid, env, level):
stmts = prog["bodies"][mid][1]
for _ in range(rng.randint(1, 2)):
for st in stmts:
budget[0] -= 1
if budget[0] < 0:
raise _Stop
if rng.random() < skip:
continue
kind = st[0]
if kind == "new":
heap.append((st[2], {}))
env[st[1]] = len(heap) - 1
elif kind == "copy":
env[st[1]] = env.get(st[2])
elif kind == "load":
o = env.get(st[2])
if o is None:
continue
env[st[1]] = heap[o][1].get(st[3])
elif kind == "store":
o = env.get(st[1])
if o is None:
continue
heap[o][1][st[2]] = env.get(st[3])
else:
_, s, x, y, m, z = st
o = env.get(y)
if o is None:
continue
target = lookup(prog, heap[o][0], m)
edges.add((s, target))
entered.add(target)
result = None
if level < depth:
callee = {"this": o, "p": env.get(z) if z is not None else None}
execute(target, callee, level + 1)
result = callee.get("ret")
if x is not None:
env[x] = result
try:
execute(MAIN, {}, 0)
except _Stop:
pass
return edges, entered
def _fixpoint(prog, targets):
"""The least (R, E) closed under: MAIN in R, and for each site s of a
method of R and each T in targets(s, R), (s, T) in E and T in R."""
reach, edges = {MAIN}, set()
changed = True
while changed:
changed = False
for mid in sorted(reach):
for st in call_sites(prog, mid):
for t in targets(mid, st, reach):
if (st[1], t) not in edges:
edges.add((st[1], t))
changed = True
if t not in reach:
reach.add(t)
changed = True
return reach, edges
def cha_spec(prog):
"""Class hierarchy analysis by plain iteration."""
def targets(mid, st, reach):
decl = prog["bodies"][mid][0][st[3]]
return {lookup(prog, c, st[4]) for c in prog["classes"] if is_sub(prog, c, decl)}
return _fixpoint(prog, targets)
def rta_spec(prog):
"""Rapid type analysis by plain iteration."""
def targets(mid, st, reach):
made = {s[2] for r in reach for s in prog["bodies"][r][1] if s[0] == "new"}
decl = prog["bodies"][mid][0][st[3]]
return {lookup(prog, c, st[4]) for c in made if is_sub(prog, c, decl)}
return _fixpoint(prog, targets)
def show(prog):
"""The program in a short text form, for messages of failed tests."""
out = []
for c, p in prog["classes"].items():
out.append(f"class {c}" + (f" : {p}" if p else ""))
for m, sig in prog["methods"].items():
out.append(f"method {m} {sig}")
for f, sig in prog["fields"].items():
out.append(f"field {f} {sig}")
for mid, (local, stmts) in prog["bodies"].items():
out.append(f"{mid[0]}.{mid[1]} {local}")
out.extend(f" {st}" for st in stmts)
return "\n".join(out)
rapid_type_analysis.py 55 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rapid-type-analysis/. The authors are listed in prov/D3EG6T.jsonl.
"""Rapid type analysis (RTA): a call graph from the classes that reachable
code creates.
rapid_type_analysis(prog) takes a program of the oomodel form and returns
(R, E): the methods reachable from the root, and the call edges as pairs
(site, method id). A virtual call y.m(z) may call LOOKUP(C, m) for every class
C that is at or below the declared class of y and that a reachable method
creates with new. The graph is built on the fly: a class created late adds
edges to the sites seen before, and a site seen late uses all classes created
before.
Precondition: the program is well typed. Cost: O(K * M) for the dispatch
table, plus O(n + S * K) for a program of size n with S call sites and K
classes.
"""
from oomodel import MAIN, lookup, subclasses
def rapid_type_analysis(prog: dict) -> tuple[set, set]:
below = subclasses(prog)
table = {} # (C, m) -> LOOKUP(C, m), built once
for m, (mdecl, _, _) in prog["methods"].items():
for c in below[mdecl]:
table[(c, m)] = lookup(prog, c, m)
reach, work, edges = {MAIN}, [MAIN], set() # @line L1
made, seen = set(), [] # I and S of the pseudocode
def add(s, t):
edges.add((s, t)) # @line L13
if t not in reach: # @line L14
reach.add(t)
work.append(t)
while work: # @line L2
mid = work.pop() # @line L3
local, stmts = prog["bodies"][mid]
for st in stmts: # @line L4
if st[0] == "new" and st[2] not in made:
c = st[2]
made.add(c) # @line L5
for s, m, d in seen: # @line L6
if c in below[d]:
add(s, table[(c, m)]) # @line L7
for st in stmts: # @line L8
if st[0] == "call":
_, s, _, y, m, _ = st
d = local[y]
seen.append((s, m, d)) # @line L9
for c in made: # @line L10
if c in below[d]:
add(s, table[(c, m)]) # @line L11
return reach, edges # @line L12
test_rapid_type_analysis.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rapid-type-analysis/. The authors are listed in prov/D3EG6T.jsonl.
import random
import oomodel
from oomodel import MAIN
from rapid_type_analysis import rapid_type_analysis
def test_page_example():
reach, edges = rapid_type_analysis(oomodel.shapes())
live = {("Circle", "grow"), ("Square", "grow")}
assert reach == {MAIN} | live
assert edges == {(s, t) for s in ("s1", "s2", "s3") for t in live}
def test_class_created_after_the_site_is_seen():
# main calls a.m() on an A; A.m then creates a B, which overrides m.
prog = {
"classes": {"A": None, "B": "A"},
"methods": {"m": ("A", "A", "A")},
"fields": {},
"bodies": {
("A", "m"): ({"this": "A", "p": "A", "ret": "A"}, [("new", "ret", "B")]),
("B", "m"): ({"this": "B", "p": "A", "ret": "A"}, []),
MAIN: ({"a": "A"}, [("new", "a", "A"), ("call", "s1", "a", "a", "m", None)]),
},
}
reach, edges = rapid_type_analysis(prog)
assert edges == {("s1", ("A", "m")), ("s1", ("B", "m"))}
assert reach == {MAIN, ("A", "m"), ("B", "m")}
def test_creation_in_unreachable_code_does_not_count():
prog = oomodel.shapes()
prog["bodies"][("Oval", "grow")] = ({"this": "Oval", "p": "Shape", "ret": "Shape"}, [])
prog["bodies"][("Shape", "grow")][1].append(("new", "ret", "Oval"))
reach, edges = rapid_type_analysis(prog)
assert ("Oval", "grow") not in reach
assert ("Shape", "grow") not in reach
def test_no_objects_no_edges():
prog = oomodel.shapes()
local, stmts = prog["bodies"][MAIN]
prog["bodies"][MAIN] = (local, [st for st in stmts if st[0] == "call"])
assert rapid_type_analysis(prog) == ({MAIN}, set())
def test_same_as_plain_iteration():
rng = random.Random(1996)
for _ in range(500):
prog = oomodel.random_program(rng, rng.randint(1, 7), rng.randint(1, 4), rng.randint(0, 2), 8)
assert rapid_type_analysis(prog) == oomodel.rta_spec(prog), oomodel.show(prog)
def test_sound_against_concrete_runs():
rng = random.Random(78)
for _ in range(300):
prog = oomodel.random_program(rng, rng.randint(2, 7), rng.randint(1, 4), rng.randint(0, 2), 8)
reach, edges = rapid_type_analysis(prog)
for _ in range(5):
seen_edges, entered = oomodel.run(prog, rng)
assert seen_edges <= edges, oomodel.show(prog)
assert entered <= reach
def test_inside_class_hierarchy_analysis():
rng = random.Random(6)
smaller = 0
for _ in range(300):
prog = oomodel.random_program(rng, rng.randint(2, 7), rng.randint(1, 4), rng.randint(0, 2), 8)
reach, edges = rapid_type_analysis(prog)
cha_reach, cha_edges = oomodel.cha_spec(prog)
assert reach <= cha_reach and edges <= cha_edges
smaller += edges != cha_edges
assert smaller > 0
History
Bacon and Sweeney introduced rapid type analysis in 1996. They compared it with class hierarchy analysis and with name-based resolution on C++ programs, and found that keeping only the created classes resolves many more virtual calls at almost the same cost. Tip and Palsberg (2000) wrote RTA as a set of constraints and refined it with separate sets of classes per method, per field and per class. Grove and Chambers (2001) placed RTA in a framework of call graph algorithms between class hierarchy analysis and full type propagation.
References
- David F. Bacon and Peter F. Sweeney, Fast static analysis of C++ virtual function calls, Proceedings of OOPSLA '96, 324 to 341, 1996, the definition of rapid type analysis and its measured comparison with class hierarchy analysis on C++ programs
- Frank Tip and Jens Palsberg, Scalable propagation-based call graph construction algorithms, Proceedings of OOPSLA 2000, 281 to 293, the constraint form of rapid type analysis, and the refinements that keep one set of classes per method, per field or per class
- David Grove and Craig Chambers, A framework for call graph construction algorithms, ACM Transactions on Programming Languages and Systems 23(6), 685 to 746, 2001, rapid type analysis as a point of the framework between class hierarchy analysis and type propagation
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag D3EG6T Edit this page History Report an error Markdown