01: package spoon.reflect.visitor;
02:
03: import java.util.ArrayList;
04: import java.util.HashMap;
05: import java.util.List;
06: import java.util.Map;
07:
08: import spoon.processing.Environment;
09: import spoon.reflect.cu.CompilationUnit;
10: import spoon.reflect.cu.SourceCodeFragment;
11: import spoon.reflect.declaration.CtSimpleType;
12:
13: /**
14: * This pretty printer is used when Spoon is use with the "fragments" mode. This
15: * pretty printer simply prints out the original source code of the compilation
16: * unit and replaces some fragments of code as defined by the
17: * {@link CompilationUnit#getSourceCodeFraments()} method.
18: */
19:
20: public class FragmentDrivenJavaPrettyPrinter implements PrettyPrinter {
21:
22: private void addjustFragments(List<SourceCodeFragment> fragments) {
23: int i = 0;
24: for (SourceCodeFragment f : fragments) {
25: for (int j = i + 1; j < fragments.size(); j++) {
26: fragments.get(j).position += f.code.length()
27: - f.replacementLength;
28: }
29: i++;
30: }
31: }
32:
33: Map<Integer, Integer> lineNumberMapping = new HashMap<Integer, Integer>();
34:
35: public StringBuffer getResult() {
36: StringBuffer sb = new StringBuffer();
37: sb.append(compilationUnit.getOriginalSourceCode());
38: List<SourceCodeFragment> fragments = new ArrayList<SourceCodeFragment>();
39: if (compilationUnit.getSourceCodeFraments() != null) {
40: for (SourceCodeFragment f : compilationUnit
41: .getSourceCodeFraments()) {
42: fragments.add(new SourceCodeFragment(f.position,
43: f.code, f.replacementLength));
44: }
45: }
46: addjustFragments(fragments);
47: for (SourceCodeFragment f : fragments) {
48: sb.replace(f.position, f.position + f.replacementLength,
49: f.code);
50: // sb.insert(f.position, f.code);
51: }
52: return sb;
53: }
54:
55: public String getPackageDeclaration() {
56: return "";
57: }
58:
59: Environment env;
60:
61: CompilationUnit compilationUnit;
62:
63: /**
64: * Creates a new fragment-driven pretty printer for the given compilation
65: * unit.
66: */
67: public FragmentDrivenJavaPrettyPrinter(Environment env,
68: CompilationUnit compilationUnit) throws Exception {
69: this .env = env;
70: this .compilationUnit = compilationUnit;
71: }
72:
73: public void calculate(CompilationUnit originalCompilationUnit,
74: List<CtSimpleType<?>> types) {
75: // do nothing
76: }
77:
78: public Map<Integer, Integer> getLineNumberMapping() {
79: return lineNumberMapping;
80: }
81:
82: }
|