Class Rewriting<O,A,E>

java.lang.Object
eu.bandm.tools.graph.Rewriting<O,A,E>
Type Parameters:
O - the type of objects to rewrite
A - the type of dynamic arguments of the rewriting process
E - the type of static environments of the rewriting process

public class Rewriting<O,A,E> extends Object
Recursive rewriting of object graphs with sharing and managed cycles.

In the simplest case, each object o is rewritten by recursively rewriting its neighborhood (the other objects in the graph that o has direct references to), and then creating a new object, often a modified copy of o, with the rewritten references. If the object graph is tree-shaped, this is the only case that occurs. For other cases, see below.

The particular rewriting operation to perform is specified by a step function given as a parameter step at the creation time of the Rewriting process object. If the object graph is heterogeneous, the step function is often a reference to a polymorphic method. For object graphs built from classes that have no built-in rewriting operations, an adapter may be required.

Functional Behavior

Rewriting is a functional process. It is recommended

  • that the original objects should not be modified,
  • that the result should not depend on the order of rewriting steps,
  • that there should be no observable side effects, and
  • that no implicit source of information be used.
Three explicit sources of information are available at each step:
  1. The original object to be rewritten,
  2. a dynamic argument that can vary between recursive calls,
  3. a static environment that is fixed for all recursive calls of the process.

If more than one item is required for an argument or environment, use a record type. Conversely, if no argument or environment information is required, use type Void and value null.

Getting Started

For example, consider the task of replacing each array of references in a deeply nested array structure by a list. The following method is a valid implementation of Rewriting.Step that does the job with no argument or environment information:

 static Object array2listDeep(Object original, Void argument,
                              Rewriting<Object, Void, Void>.Context context) {
     if (original instanceof Object[]) {
         final List<Object> result = new ArrayList<>();
         for (Object elem : arr)
             result.add(context.rewrite((Object[])elem, null));
         return result;
     }
     else return original;
 }
 

Equality and Null

The objects that constitute the graph are distinguished exactly. Distinct objects are considered distinct graph vertices, for the purpose of cycle and sharing detection, even if they are equal to each other. By contrast, dynamic arguments have value semantics; they are distinguished only up to Objects.equals.

Whether null references in the object graph are valid is application-specific. All generic operations of the rewriting process tolerate null. The client must implement the given step function accordingly.

Memory Management

A Rewriting object maintains internal data structures throughout its lifetime. It is recommended not to retain such objects for indefinitely later reuse. Rather, a fresh process should be initiated every time an object graph is rewritten, and the controlling Rewriting object be made unreachable immediately afterwards, such that the associated data structures can be garbage-collected.

Internal Sharing

If configured to do so, a rewriting process maintains a cache for objects that have already been rewritten. If the same object is encountered again with the same dynamic argument, the cached result is retrieved, and no new object is created. Whether this effect is desired depends on the application context. The choice is specified by a flag shareResults at creation time of the Rewriting process object.

Cycles

When references in the object graph to be rewritten form cycles, there is no general solution for rewriting purely with bottom-up steps. However, if cycles are used in a disciplined way, there is support for explicit handling.

This support requires that all cycles have distinguished entry points, and that cycles can be formed after object creation by cyclic dependency injection. Then an incomplete object can be created and recorded as the rewriting result for a cycle entry point.

For example, the rewriting step discussed above can be upgraded straightforwardly to cycle handling, because the result lists naturally support deferred initialization of contents:

 static Object array2listDeep(Object original, Void argument,
                              Rewriting<Object, Void, Void>.Context context) {
     if (original instanceof Object[]) {
         final List<Object> result = new ArrayList<>();
         context.pushCycleEntry(original, argument, result);
         for (Object elem : arr)
             result.add(context.rewrite((Object[])elem, null));
         return context.popCycleEntry(original, argument);
     }
     else return original;
 }
 

Cross-Graph Sharing

A rewriting process may rewrite some object to an equivalent one. In that case, it depends on the application context whether the result graph should contain a distinct copy or a reference to the original. This choice is specified by a flag shareOriginals at creation time of the Rewriting process object.

The detection of shareable objects requires cooperation between the rewriting process and the client code. A step function that wishes to exploit cross-graph sharing of an object should invoke the method Rewriting.Context.pushNeighborhood(O) before recursively rewriting its neighborhood, and use method Rewriting.Context.popNeighborhood(Supplier) to obtain the rewriting result. Behavior is unspecified if these methods are not invoked in balanced pairs.

For example, consider the task to replace each string in a deeply nested reference array data structure by sequence of '*' characters that represents its nesting depth. Nested arrays that do not directly or indirectly contain any string can be shared unchanged. The following method is a valid implementation of Rewriting.Step that does the job with an integer argument:

 private static Object string2stars(Object original, Integer argument,
                                    Rewriting<Object, Integer, Void>.Context context) {
     if (original instanceof Object[]) {
         context.pushNeighborhood(original);
         final Object[] arr = (Object[])original;
         final Object[] result = new Object[arr.length];
         for (int i = 0; i < arr.length; i++)
             result[i] = context.rewrite(arr[i], argument + 1);
         return context.popNeighborhood(() -> result);
     }
     else if (original instanceof String)
         return "*".repeat(argument);
     else
         return original;
 }
 
  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    class 
    Context-sensitive callback to the rewriting process.
    static interface 
    Interface for functions that rewrite an object.
  • Constructor Summary

    Constructors
    Constructor
    Description
    Rewriting(Rewriting.Step<O,A,E> step, @Opt E environment, boolean shareOriginals, boolean shareResults)
    Creates a new rewriting process.
  • Method Summary

    Modifier and Type
    Method
    Description
    long
    Returns the number of steps performed so far by this rewriting process.
    rewrite(O original, @Opt A argument)
    Rewrites the graph reachable from a top-level object recursively.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • Rewriting

      public Rewriting(Rewriting.Step<O,A,E> step, @Opt E environment, boolean shareOriginals, boolean shareResults)
      Creates a new rewriting process.
      Parameters:
      step - the function that rewrites a single object
      environment - the static environment of the rewriting process, or null if not applicable
      shareOriginals - whether to share references to original objects if rewritten equivalently
      shareResults - whether to share references in repeated equivalent rewritings
  • Method Details

    • getStepCounter

      public long getStepCounter()
      Returns the number of steps performed so far by this rewriting process.
      Returns:
      the number of steps performed so far by this rewriting process
    • rewrite

      public O rewrite(O original, @Opt A argument)
      Rewrites the graph reachable from a top-level object recursively.
      Parameters:
      original - the original object to rewrite along with all reachable objects
      argument - the dynamic argument to the rewriting, or null if not applicable
      Returns:
      the rewritten top-level object