Writing your own transformation

This tutorial explains how to write your own transformation. If you are just interested in how to add your transformation as a quickfix to a JT analysis, have a look at this page.

A strength of JTransformer is that it capable of doing analysis on the source code and transformations. In this section, we are writing a transformation that could be applied to code found by the System.out.println detector from the "Write your own analysis"-Example.

Conditional Tranformations (CTs)

If you want to learn what Conditional Transformations are and how you can use them (run a ct, run a sequence of cts, examine the results of a ct …) please have a look at this page: Conditional Tranformations. If you need more examples for transformations you can have a look at the Tutorial Project 1).

The transformation for our System.out.println detector has to replace the call to System.out.println by a call to a logging method. How the logging method can be detected has to be defined in the condition part of the ct.

 1: :- multifile(user:ct/3).     % Don't forget the declaration!
 3: user:ct( replaceSysoutWithLogging(CallId),              % HEAD
 4:     (                                                   % CONDITION
 5:       sysout_analysis:sysout_call(CallId,CallParent, Enclosing, FieldAccess, StaticTypeRef, Argument),
 6:                                                         % Call the analysis predicate and bind all IDs
 7:       get_term(FieldAccess, FieldAccessTerm),           % get the terms which should be deleted
 8:       get_term(StaticTypeRef, StaticTypeRefTerm),
10:       classT(MyLoggerClass, _, 'MyLogger', _, _),       % Get the ID belonging to class 'MyLogger'
11:       methodT(LoggingMethod, MyLoggerClass, println, _, MethodType, _, _, _),
12:                                                         % ... and the ID for the logging method
14:       new_id(NewTypeRef)                                % NewTypeRef is a yet unused ID
15:     ),
16:     (                                                                     % TRANSFORMATION:
17:       delete(FieldAccessTerm),                          % delete the field access
18:       delete(StaticTypeRefTerm),                        % delete the static type reference
20:       replace(callT(CallId, CallParent, Enclosing, NewTypeRef, [Argument], LoggingMethod, [], MethodType))
21:                                                         % replace the existing callT fact with the new one (call the logging method instead of System.out.println)
23:       add(staticTypeRefT(NewTypeRef, CallId, Enclosing, MyLoggerClass)),
24:                                                         % add the static type reference to the class "MyLogger"
25:     )
26: ).
1) New → Example → JTransformer Example Projects → JTransformer Tutorial - Prolog Files → refactorings
Last modified: 2017/08/29 12:22