This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.

View | Details | Raw Unified | Return to bug 138225
Collapse All | Expand All

(-)a/java.hints/src/org/netbeans/modules/java/hints/errors/CreateClassFix.java (-1 / +1 lines)
Lines 345-351 Link Here
345
                }
345
                }
346
            });
346
            });
347
            
347
            
348
            return Utilities.commitAndComputeChangeInfo(targetFile, diff);
348
            return Utilities.commitAndComputeChangeInfo(targetFile, diff, null);
349
        }
349
        }
350
        
350
        
351
        public String toDebugString(CompilationInfo info) {
351
        public String toDebugString(CompilationInfo info) {
(-)a/java.hints/src/org/netbeans/modules/java/hints/errors/CreateFieldFix.java (-1 / +1 lines)
Lines 131-137 Link Here
131
            }
131
            }
132
        });
132
        });
133
        
133
        
134
        return Utilities.commitAndComputeChangeInfo(targetFile, diff);
134
        return Utilities.commitAndComputeChangeInfo(targetFile, diff, null);
135
    }
135
    }
136
    
136
    
137
    String toDebugString(CompilationInfo info) {
137
    String toDebugString(CompilationInfo info) {
(-)a/java.hints/src/org/netbeans/modules/java/hints/errors/CreateMethodFix.java (-2 / +11 lines)
Lines 83-93 Link Here
83
    private String name;
83
    private String name;
84
    private String inFQN;
84
    private String inFQN;
85
    private String methodDisplayName;
85
    private String methodDisplayName;
86
    private CompilationInfo info;
86
    
87
    
87
    public CreateMethodFix(CompilationInfo info, String name, Set<Modifier> modifiers, TypeElement target, TypeMirror returnType, List<? extends TypeMirror> argumentTypes, List<String> argumentNames, FileObject targetFile) {
88
    public CreateMethodFix(CompilationInfo info, String name, Set<Modifier> modifiers, TypeElement target, TypeMirror returnType, List<? extends TypeMirror> argumentTypes, List<String> argumentNames, FileObject targetFile) {
88
        this.name = name;
89
        this.name = name;
89
        this.inFQN = target.getQualifiedName().toString();
90
        this.inFQN = target.getQualifiedName().toString();
90
        this.cpInfo = info.getClasspathInfo();
91
        this.cpInfo = info.getClasspathInfo();
92
        this.info = info;
91
        this.modifiers = modifiers;
93
        this.modifiers = modifiers;
92
        this.targetFile = targetFile;
94
        this.targetFile = targetFile;
93
        this.target = ElementHandle.create(target);
95
        this.target = ElementHandle.create(target);
Lines 140-145 Link Here
140
    public ChangeInfo implement() throws IOException {
142
    public ChangeInfo implement() throws IOException {
141
        //use the original cp-info so it is "sure" that the proposedType can be resolved:
143
        //use the original cp-info so it is "sure" that the proposedType can be resolved:
142
        JavaSource js = JavaSource.create(cpInfo, targetFile);
144
        JavaSource js = JavaSource.create(cpInfo, targetFile);
145
        //XXX tag used for selection
146
        final String methodBodyTag = "mbody"; //NOI18N
143
        
147
        
144
        ModificationResult diff = js.runModificationTask(new Task<WorkingCopy>() {
148
        ModificationResult diff = js.runModificationTask(new Task<WorkingCopy>() {
145
            public void run(final WorkingCopy working) throws IOException {
149
            public void run(final WorkingCopy working) throws IOException {
Lines 180-185 Link Here
180
                }
184
                }
181
                
185
                
182
                BlockTree body = targetType.getKind().isClass() ? createDefaultMethodBody(working, returnType) : null;
186
                BlockTree body = targetType.getKind().isClass() ? createDefaultMethodBody(working, returnType) : null;
187
                
188
                if(body != null && !body.getStatements().isEmpty()) {
189
                    working.tag(body.getStatements().get(0), methodBodyTag);
190
                }
191
                
183
                MethodTree mt = make.Method(make.Modifiers(modifiers), name, returnType != null ? make.Type(returnType) : null, Collections.<TypeParameterTree>emptyList(), argTypes, Collections.<ExpressionTree>emptyList(), body, null);
192
                MethodTree mt = make.Method(make.Modifiers(modifiers), name, returnType != null ? make.Type(returnType) : null, Collections.<TypeParameterTree>emptyList(), argTypes, Collections.<ExpressionTree>emptyList(), body, null);
184
                ClassTree decl = GeneratorUtils.insertClassMember(working, targetTree, mt);
193
                ClassTree decl = GeneratorUtils.insertClassMember(working, targetTree, mt);
185
                
194
                
Lines 187-193 Link Here
187
            }
196
            }
188
        });
197
        });
189
        
198
        
190
        return Utilities.commitAndComputeChangeInfo(targetFile, diff);
199
        return Utilities.commitAndComputeChangeInfo(targetFile, diff, methodBodyTag);
191
    }
200
    }
192
    
201
    
193
    private void addArguments(CompilationInfo info, StringBuilder value) {
202
    private void addArguments(CompilationInfo info, StringBuilder value) {
Lines 244-249 Link Here
244
        }
253
        }
245
        return make.Block(blockStatements, false);
254
        return make.Block(blockStatements, false);
246
    }
255
    }
247
    
256
248
}
257
}
249
258
(-)a/java.hints/src/org/netbeans/modules/java/hints/errors/Utilities.java (-8 / +23 lines)
Lines 48-53 Link Here
48
import com.sun.source.tree.NewClassTree;
48
import com.sun.source.tree.NewClassTree;
49
import com.sun.source.tree.ParameterizedTypeTree;
49
import com.sun.source.tree.ParameterizedTypeTree;
50
import com.sun.source.tree.Scope;
50
import com.sun.source.tree.Scope;
51
import com.sun.source.tree.StatementTree;
51
import com.sun.source.tree.Tree;
52
import com.sun.source.tree.Tree;
52
import com.sun.source.util.TreePath;
53
import com.sun.source.util.TreePath;
53
import java.io.IOException;
54
import java.io.IOException;
Lines 213-222 Link Here
213
        }
214
        }
214
        
215
        
215
    }
216
    }
216
    
217
217
    public static ChangeInfo commitAndComputeChangeInfo(FileObject target, ModificationResult diff) throws IOException {
218
    /**
219
     * Commits changes and provides selection bounds
220
     *
221
     * @param target target FileObject
222
     * @param diff set of changes made by ModificationTask
223
     * @param tag mark used for selection of generated text
224
     * @return set of changes made by hint
225
     * @throws java.io.IOException
226
     */
227
    public static ChangeInfo commitAndComputeChangeInfo(FileObject target, final ModificationResult diff, final Object tag) throws IOException {
218
        List<? extends Difference> differences = diff.getDifferences(target);
228
        List<? extends Difference> differences = diff.getDifferences(target);
219
        ChangeInfo result = null;
229
        ChangeInfo result = null;
230
        
231
        diff.commit();
220
        
232
        
221
        try {
233
        try {
222
            if (differences != null) {
234
            if (differences != null) {
Lines 229-242 Link Here
229
                            doc = start.getCloneableEditorSupport().openDocument();
241
                            doc = start.getCloneableEditorSupport().openDocument();
230
                        }
242
                        }
231
                        
243
                        
232
                        final Position[] pos = new Position[1];
244
                        final Position[] pos = new Position[2];
233
                        final Document fdoc = doc;
245
                        final Document fdoc = doc;
234
                        
246
                        
235
                        doc.render(new Runnable() {
247
                        doc.render(new Runnable() {
236
237
                            public void run() {
248
                            public void run() {
238
                                try {
249
                                try {
239
                                    pos[0] = NbDocument.createPosition(fdoc, start.getOffset(), Position.Bias.Backward);
250
                                    if(diff.getSpan(tag) != null) {
251
                                        pos[0] = fdoc.createPosition(diff.getSpan(tag)[0]);
252
                                        pos[1] = fdoc.createPosition(diff.getSpan(tag)[1]);
253
                                    } else {
254
                                        pos[0] = NbDocument.createPosition(fdoc, start.getOffset(), Position.Bias.Backward);
255
                                        pos[1] = pos[0];
256
                                    }
240
                                } catch (BadLocationException ex) {
257
                                } catch (BadLocationException ex) {
241
                                    Exceptions.printStackTrace(ex);
258
                                    Exceptions.printStackTrace(ex);
242
                                }
259
                                }
Lines 244-250 Link Here
244
                        });
261
                        });
245
                        
262
                        
246
                        if (pos[0] != null) {
263
                        if (pos[0] != null) {
247
                            result = new ChangeInfo(target, pos[0], pos[0]);
264
                            result = new ChangeInfo(target, pos[0], pos[1]);
248
                        }
265
                        }
249
                        
266
                        
250
                        break;
267
                        break;
Lines 254-261 Link Here
254
        } catch (IOException e) {
271
        } catch (IOException e) {
255
            Exceptions.printStackTrace(e);
272
            Exceptions.printStackTrace(e);
256
        }
273
        }
257
        
258
        diff.commit();
259
        
274
        
260
        return result;
275
        return result;
261
    }
276
    }
(-)a/java.source/apichanges.xml (+11 lines)
Lines 105-110 Link Here
105
    <!-- ACTUAL CHANGES BEGIN HERE: -->
105
    <!-- ACTUAL CHANGES BEGIN HERE: -->
106
106
107
    <changes>
107
    <changes>
108
        <change id="TaggingSupport">
109
             <api name="general"/>
110
             <summary>Added ModificationResult.getSpan and WorkingCopy.tag</summary>
111
             <version major="0" minor="37"/>
112
             <date day="25" month="6" year="2008"/>
113
             <author login="msauer"/>
114
             <compatibility addition="yes" binary="compatible" deletion="no" deprecation="no" modification="no" semantic="compatible" source="compatible"/>
115
             <description>
116
                 Added Methods allowing tagging of trees and getting their span inside modified document.
117
             </description>
118
        </change>
108
        <change id="TypeUtilities.substitute">
119
        <change id="TypeUtilities.substitute">
109
             <api name="general"/>
120
             <api name="general"/>
110
             <summary>Added TypeUtilities.substitute</summary>
121
             <summary>Added TypeUtilities.substitute</summary>
(-)a/java.source/nbproject/project.properties (-1 / +1 lines)
Lines 43-49 Link Here
43
javadoc.title=Java Source
43
javadoc.title=Java Source
44
javadoc.arch=${basedir}/arch.xml
44
javadoc.arch=${basedir}/arch.xml
45
javadoc.apichanges=${basedir}/apichanges.xml
45
javadoc.apichanges=${basedir}/apichanges.xml
46
spec.version.base=0.36.0
46
spec.version.base=0.37.0
47
test.qa-functional.cp.extra=${refactoring.java.dir}/modules/ext/javac-api-nb-7.0-b07.jar
47
test.qa-functional.cp.extra=${refactoring.java.dir}/modules/ext/javac-api-nb-7.0-b07.jar
48
test.unit.run.cp.extra=${o.n.core.dir}/core/core.jar:\
48
test.unit.run.cp.extra=${o.n.core.dir}/core/core.jar:\
49
    ${o.n.core.dir}/lib/boot.jar:\
49
    ${o.n.core.dir}/lib/boot.jar:\
(-)a/java.source/src/org/netbeans/api/java/source/JavaSource.java (-3 / +3 lines)
Lines 857-863 Link Here
857
     * @see Task for information about implementation requirements
857
     * @see Task for information about implementation requirements
858
     * @param task The task which.
858
     * @param task The task which.
859
     */    
859
     */    
860
    public ModificationResult runModificationTask(Task<WorkingCopy> task) throws IOException {        
860
    public ModificationResult runModificationTask(Task<WorkingCopy> task) throws IOException {
861
        if (task == null) {
861
        if (task == null) {
862
            throw new IllegalArgumentException ("Task cannot be null");     //NOI18N
862
            throw new IllegalArgumentException ("Task cannot be null");     //NOI18N
863
        }
863
        }
Lines 914-920 Link Here
914
                    assert currentInfo != null;                    
914
                    assert currentInfo != null;                    
915
                    WorkingCopy copy = new WorkingCopy (currentInfo);
915
                    WorkingCopy copy = new WorkingCopy (currentInfo);
916
                    task.run (copy);
916
                    task.run (copy);
917
                    List<Difference> diffs = copy.getChanges();
917
                    List<Difference> diffs = copy.getChanges(result.tag2Span);
918
                    if (diffs != null && diffs.size() > 0)
918
                    if (diffs != null && diffs.size() > 0)
919
                        result.diffs.put(currentInfo.getFileObject(), diffs);
919
                        result.diffs.put(currentInfo.getFileObject(), diffs);
920
                }
920
                }
Lines 965-971 Link Here
965
                        if (!ci.needsRestart) {
965
                        if (!ci.needsRestart) {
966
                            jt = ci.getJavacTask();
966
                            jt = ci.getJavacTask();
967
                            Log.instance(jt.getContext()).nerrors = 0;
967
                            Log.instance(jt.getContext()).nerrors = 0;
968
                            List<Difference> diffs = copy.getChanges();
968
                            List<Difference> diffs = copy.getChanges(result.tag2Span);
969
                            if (diffs != null && diffs.size() > 0)
969
                            if (diffs != null && diffs.size() > 0)
970
                                result.diffs.put(ci.getFileObject(), diffs);
970
                                result.diffs.put(ci.getFileObject(), diffs);
971
                            activeFile = null;
971
                            activeFile = null;
(-)a/java.source/src/org/netbeans/api/java/source/ModificationResult.java (+11 lines)
Lines 71-76 Link Here
71
71
72
    private JavaSource js;
72
    private JavaSource js;
73
    Map<FileObject, List<Difference>> diffs = new HashMap<FileObject, List<Difference>>();
73
    Map<FileObject, List<Difference>> diffs = new HashMap<FileObject, List<Difference>>();
74
    Map<?, int[]> tag2Span = new IdentityHashMap<Object, int[]>();
74
    
75
    
75
    /** Creates a new instance of ModificationResult */
76
    /** Creates a new instance of ModificationResult */
76
    ModificationResult(final JavaSource js) {
77
    ModificationResult(final JavaSource js) {
Lines 332-337 Link Here
332
        
333
        
333
        return writer.toString();
334
        return writer.toString();
334
    }
335
    }
336
337
    /**
338
     * Provides span of tree tagged with {@code tag}
339
     * @param tag
340
     * @return borders in target document
341
     * @since 0.37
342
     */
343
    public int[] getSpan(Object tag) {
344
        return tag2Span.get(tag);
345
    }
335
    
346
    
336
    public static class Difference {
347
    public static class Difference {
337
        Kind kind;
348
        Kind kind;
(-)a/java.source/src/org/netbeans/api/java/source/WorkingCopy.java (-8 / +24 lines)
Lines 57-62 Link Here
57
import java.util.HashMap;
57
import java.util.HashMap;
58
import java.util.HashSet;
58
import java.util.HashSet;
59
import java.util.IdentityHashMap;
59
import java.util.IdentityHashMap;
60
import java.util.LinkedHashSet;
60
import java.util.LinkedList;
61
import java.util.LinkedList;
61
import java.util.List;
62
import java.util.List;
62
import java.util.Map;
63
import java.util.Map;
Lines 94-99 Link Here
94
    private Map<Integer, String> userInfo;
95
    private Map<Integer, String> userInfo;
95
    private boolean afterCommit = false;
96
    private boolean afterCommit = false;
96
    private TreeMaker treeMaker;
97
    private TreeMaker treeMaker;
98
    private Map<Tree, Object> tree2Tag;
97
    
99
    
98
    WorkingCopy(final CompilationInfoImpl impl) {        
100
    WorkingCopy(final CompilationInfoImpl impl) {        
99
        super(impl);
101
        super(impl);
Lines 105-110 Link Here
105
        
107
        
106
        treeMaker = new TreeMaker(this, TreeFactory.instance(getContext()));
108
        treeMaker = new TreeMaker(this, TreeFactory.instance(getContext()));
107
        changes = new IdentityHashMap<Tree, Tree>();
109
        changes = new IdentityHashMap<Tree, Tree>();
110
        tree2Tag = new IdentityHashMap<Tree, Object>();
108
        externalChanges = null;
111
        externalChanges = null;
109
        textualChanges = new HashSet<Diff>();
112
        textualChanges = new HashSet<Diff>();
110
        userInfo = new HashMap<Integer, String>();
113
        userInfo = new HashMap<Integer, String>();
Lines 230-235 Link Here
230
        userInfo.put(start, NbBundle.getMessage(CasualDiff.class,"TXT_RenameInComment")); //NOI18N
233
        userInfo.put(start, NbBundle.getMessage(CasualDiff.class,"TXT_RenameInComment")); //NOI18N
231
    }
234
    }
232
    
235
    
236
    /**
237
     * Tags a tree. Used in {@code ModificationResult} to determine position of tree inside document.
238
     * @param t the tree to be tagged
239
     * @param tag an {@code Object} used as tag
240
     * @since 0.37
241
     */
242
    public synchronized void tag(Tree t, Object tag) {
243
        tree2Tag.put(t, tag);
244
    }
245
    
233
    // Package private methods -------------------------------------------------        
246
    // Package private methods -------------------------------------------------        
234
    
247
    
235
    private static void commit(CompilationUnitTree topLevel, List<Diff> diffs, SourceRewriter out) throws IOException, BadLocationException {
248
    private static void commit(CompilationUnitTree topLevel, List<Diff> diffs, SourceRewriter out) throws IOException, BadLocationException {
Lines 284-291 Link Here
284
            
297
            
285
    private static boolean REWRITE_WHOLE_FILE = Boolean.getBoolean(WorkingCopy.class.getName() + ".rewrite-whole-file");
298
    private static boolean REWRITE_WHOLE_FILE = Boolean.getBoolean(WorkingCopy.class.getName() + ".rewrite-whole-file");
286
    
299
    
287
    private List<Difference> processCurrentCompilationUnit() throws IOException, BadLocationException {
300
    private List<Difference> processCurrentCompilationUnit(Map<?, int[]> tag2Span) throws IOException, BadLocationException {
288
        final Set<TreePath> pathsToRewrite = new HashSet<TreePath>();
301
        final Set<TreePath> pathsToRewrite = new LinkedHashSet<TreePath>();
289
        final Map<TreePath, Map<Tree, Tree>> parent2Rewrites = new IdentityHashMap<TreePath, Map<Tree, Tree>>();
302
        final Map<TreePath, Map<Tree, Tree>> parent2Rewrites = new IdentityHashMap<TreePath, Map<Tree, Tree>>();
290
        boolean fillImports = true;
303
        boolean fillImports = true;
291
        
304
        
Lines 376-384 Link Here
376
                ia.classEntered(ct);
389
                ia.classEntered(ct);
377
            }
390
            }
378
391
379
            translator.attach(getContext(), ia, getCompilationUnit());
392
            translator.attach(getContext(), ia, getCompilationUnit(), tree2Tag);
380
            
393
            
381
            Tree brandNew = translator.translate(path.getLeaf(), parent2Rewrites.get(path));
394
            Tree brandNew = translator.translate(path.getLeaf(), parent2Rewrites.get(path));
395
396
            //tagging debug
397
            //System.err.println("brandNew=" + brandNew);
382
            
398
            
383
            for (ClassTree ct : classes) {
399
            for (ClassTree ct : classes) {
384
                ia.classLeft();
400
                ia.classLeft();
Lines 388-401 Link Here
388
                fillImports = false;
404
                fillImports = false;
389
            }
405
            }
390
406
391
            diffs.addAll(CasualDiff.diff(getContext(), this, path, (JCTree) brandNew, userInfo));
407
            diffs.addAll(CasualDiff.diff(getContext(), this, path, (JCTree) brandNew, userInfo, tree2Tag, tag2Span));
392
        }
408
        }
393
        
409
        
394
        if (fillImports) {
410
        if (fillImports) {
395
            List<? extends ImportTree> nueImports = ia.getImports();
411
            List<? extends ImportTree> nueImports = ia.getImports();
396
            
412
            
397
            if (nueImports != null) { //may happen if no changes, etc.
413
            if (nueImports != null) { //may happen if no changes, etc.
398
                diffs.addAll(CasualDiff.diff(getContext(), this, getCompilationUnit().getImports(), nueImports, userInfo));
414
                diffs.addAll(CasualDiff.diff(getContext(), this, getCompilationUnit().getImports(), nueImports, userInfo, tree2Tag, tag2Span));
399
            }
415
            }
400
        }
416
        }
401
        
417
        
Lines 425-431 Link Here
425
        for (CompilationUnitTree t : externalChanges.values()) {
441
        for (CompilationUnitTree t : externalChanges.values()) {
426
            Translator translator = new Translator();
442
            Translator translator = new Translator();
427
            
443
            
428
            translator.attach(getContext(), new ImportAnalysis2(getContext()), t);
444
            translator.attach(getContext(), new ImportAnalysis2(getContext()), t, tree2Tag);
429
            
445
            
430
            CompilationUnitTree nue = (CompilationUnitTree) translator.translate(t, changes);
446
            CompilationUnitTree nue = (CompilationUnitTree) translator.translate(t, changes);
431
            
447
            
Lines 437-443 Link Here
437
        return result;
453
        return result;
438
    }
454
    }
439
455
440
    List<Difference> getChanges() throws IOException, BadLocationException {
456
    List<Difference> getChanges(Map<?, int[]> tag2Span) throws IOException, BadLocationException {
441
        if (afterCommit)
457
        if (afterCommit)
442
            throw new IllegalStateException("The commit method can be called only once on a WorkingCopy instance");   //NOI18N
458
            throw new IllegalStateException("The commit method can be called only once on a WorkingCopy instance");   //NOI18N
443
        afterCommit = true;
459
        afterCommit = true;
Lines 449-455 Link Here
449
        
465
        
450
        List<Difference> result = new LinkedList<Difference>();
466
        List<Difference> result = new LinkedList<Difference>();
451
        
467
        
452
        result.addAll(processCurrentCompilationUnit());
468
        result.addAll(processCurrentCompilationUnit(tag2Span));
453
        result.addAll(processExternalCUs());
469
        result.addAll(processExternalCUs());
454
        
470
        
455
        return result;
471
        return result;
(-)a/java.source/src/org/netbeans/modules/java/source/pretty/VeryPretty.java (-8 / +48 lines)
Lines 66-71 Link Here
66
66
67
import java.util.ArrayList;
67
import java.util.ArrayList;
68
import java.util.LinkedList;
68
import java.util.LinkedList;
69
import java.util.Map;
69
import org.netbeans.api.java.lexer.JavaTokenId;
70
import org.netbeans.api.java.lexer.JavaTokenId;
70
import org.netbeans.api.java.source.Comment.Style;
71
import org.netbeans.api.java.source.Comment.Style;
71
import org.netbeans.api.java.source.CompilationInfo;
72
import org.netbeans.api.java.source.CompilationInfo;
Lines 105-125 Link Here
105
    private int toOffset = -1;
106
    private int toOffset = -1;
106
    private boolean containsError = false;
107
    private boolean containsError = false;
107
    
108
    
109
    private final Map<Tree, ?> tree2Tag;
110
    private final Map<Object, int[]> tag2Span;
111
    private int initialOffset = 0;
112
    
108
    public VeryPretty(CompilationInfo cInfo) {
113
    public VeryPretty(CompilationInfo cInfo) {
109
        this(cInfo, CodeStyle.getDefault(null));
114
        this(cInfo, CodeStyle.getDefault(null), null, null);
110
    }
115
    }
111
116
112
    public VeryPretty(CompilationInfo cInfo, CodeStyle cs) {
117
    public VeryPretty(CompilationInfo cInfo, CodeStyle cs) {
113
        this(JavaSourceAccessor.getINSTANCE().getJavacTask(cInfo).getContext(), cs);
118
        this(cInfo, cs, null, null);
119
    }
120
    
121
    public VeryPretty(CompilationInfo cInfo, CodeStyle cs, Map<Tree, ?> tree2Tag, Map<?, int[]> tag2Span) {
122
        this(JavaSourceAccessor.getINSTANCE().getJavacTask(cInfo).getContext(), cs, tree2Tag, tag2Span);
114
        this.cInfo = cInfo;
123
        this.cInfo = cInfo;
115
        this.origUnit = (JCCompilationUnit) cInfo.getCompilationUnit();
124
        this.origUnit = (JCCompilationUnit) cInfo.getCompilationUnit();
116
    }
125
    }
117
    
126
    
118
    public VeryPretty(Context context) {
127
    public VeryPretty(CompilationInfo cInfo, CodeStyle cs, Map<Tree, ?> tree2Tag, Map<?, int[]> tag2Span, int initialOffset) {
119
        this(context, CodeStyle.getDefault(null));
128
        this(cInfo, cs, tree2Tag, tag2Span);
129
        this.initialOffset = initialOffset; //provide intial offset of this priter
120
    }
130
    }
121
    
131
    
122
    public VeryPretty(Context context, CodeStyle cs) {
132
    public VeryPretty(Context context) {
133
        this(context, CodeStyle.getDefault(null), null, null);
134
    }
135
    
136
    public VeryPretty(Context context, CodeStyle cs, Map<Tree, ?> tree2Tag, Map<?, int[]> tag2Span) {
123
	names = Name.Table.instance(context);
137
	names = Name.Table.instance(context);
124
	enclClassName = names.empty;
138
	enclClassName = names.empty;
125
        commentHandler = CommentHandlerService.instance(context);
139
        commentHandler = CommentHandlerService.instance(context);
Lines 132-137 Link Here
132
        this.cs = cs;
146
        this.cs = cs;
133
        out = new CharBuffer(cs.getRightMargin(), cs.getTabSize(), cs.expandTabToSpaces());
147
        out = new CharBuffer(cs.getRightMargin(), cs.getTabSize(), cs.expandTabToSpaces());
134
        this.indentSize = cs.getIndentSize();
148
        this.indentSize = cs.getIndentSize();
149
        this.tree2Tag = tree2Tag;
150
        this.tag2Span = (Map<Object, int[]>) tag2Span;//XXX
151
    }
152
153
    public void setInitialOffset(int offset) {
154
        initialOffset = offset < 0 ? 0 : offset;
155
    }
156
    
157
    public int getInitialOffset() {
158
        return initialOffset;
135
    }
159
    }
136
160
137
    @Override
161
    @Override
Lines 189-197 Link Here
189
        blankLines(t, true);
213
        blankLines(t, true);
190
        toLeftMargin();
214
        toLeftMargin();
191
	printPrecedingComments(t, true);
215
	printPrecedingComments(t, true);
192
	t.accept(this);
216
        doAccept(t);
193
        printTrailingComments(t, true);
217
        printTrailingComments(t, true);
194
        blankLines(t, false);
218
        blankLines(t, false);
219
    }
220
    
221
    private void doAccept(JCTree t) {
222
        int start = toString().length();
223
224
        t.accept(this);
225
226
        int end = toString().length();
227
228
        System.err.println("t: " + t);
229
        System.err.println("thr=" + System.identityHashCode(t));
230
        Object tag = tree2Tag != null ? tree2Tag.get(t) : null;
231
232
        if (tag != null) {
233
            tag2Span.put(tag, new int[]{start + initialOffset, end + initialOffset});
234
        }    
195
    }
235
    }
196
    
236
    
197
    public String reformat(JCTree t, int fromOffset, int toOffset, int indent) {
237
    public String reformat(JCTree t, int fromOffset, int toOffset, int indent) {
Lines 1499-1505 Link Here
1499
	} else {
1539
	} else {
1500
	    int prevPrec = this.prec;
1540
	    int prevPrec = this.prec;
1501
	    this.prec = prec;
1541
	    this.prec = prec;
1502
            tree.accept(this);
1542
            doAccept(tree);
1503
	    this.prec = prevPrec;
1543
	    this.prec = prevPrec;
1504
	}
1544
	}
1505
    }
1545
    }
Lines 1871-1877 Link Here
1871
1911
1872
    private void printComment(Comment comment, boolean preceding, boolean printWhitespace) {
1912
    private void printComment(Comment comment, boolean preceding, boolean printWhitespace) {
1873
        if (Comment.Style.WHITESPACE == comment.style()) {
1913
        if (Comment.Style.WHITESPACE == comment.style()) {
1874
            if (printWhitespace) {
1914
            if (false && printWhitespace) {
1875
                char[] data = comment.getText().toCharArray();
1915
                char[] data = comment.getText().toCharArray();
1876
                int n = -1;
1916
                int n = -1;
1877
                for (int i = 0; i < data.length; i++) {
1917
                for (int i = 0; i < data.length; i++) {
(-)a/java.source/src/org/netbeans/modules/java/source/save/CasualDiff.java (-10 / +32 lines)
Lines 47-53 Link Here
47
import org.netbeans.api.java.source.Comment.Style;
47
import org.netbeans.api.java.source.Comment.Style;
48
import org.netbeans.modules.java.source.transform.FieldGroupTree;
48
import org.netbeans.modules.java.source.transform.FieldGroupTree;
49
import static com.sun.source.tree.Tree.*;
49
import static com.sun.source.tree.Tree.*;
50
import org.netbeans.api.java.lexer.JavaTokenId;
51
import org.netbeans.api.lexer.TokenSequence;
50
import org.netbeans.api.lexer.TokenSequence;
52
import org.netbeans.modules.java.source.builder.CommentHandlerService;
51
import org.netbeans.modules.java.source.builder.CommentHandlerService;
53
import org.netbeans.api.java.source.Comment;
52
import org.netbeans.api.java.source.Comment;
Lines 85-103 Link Here
85
    private static final Logger LOG = Logger.getLogger(CasualDiff.class.getName());
84
    private static final Logger LOG = Logger.getLogger(CasualDiff.class.getName());
86
85
87
    private Map<Integer, String> diffInfo = new HashMap<Integer, String>();
86
    private Map<Integer, String> diffInfo = new HashMap<Integer, String>();
87
    private final Map<Tree, ?> tree2Tag;
88
    private final Map<Object, int[]> tag2Span;
88
    
89
    
89
    // used for diffing var def, when parameter is printed, annotation of
90
    // used for diffing var def, when parameter is printed, annotation of
90
    // such variable should not provide new line at the end.
91
    // such variable should not provide new line at the end.
91
    private boolean parameterPrint = false;
92
    private boolean parameterPrint = false;
92
    
93
    
93
    protected CasualDiff(Context context, WorkingCopy workingCopy) {
94
    protected CasualDiff(Context context, WorkingCopy workingCopy, Map<Tree, ?> tree2Tag, Map<?, int[]> tag2Span) {
94
        diffs = new ListBuffer<Diff>();
95
        diffs = new ListBuffer<Diff>();
95
        comments = CommentHandlerService.instance(context);
96
        comments = CommentHandlerService.instance(context);
96
        this.workingCopy = workingCopy;
97
        this.workingCopy = workingCopy;
97
        this.tokenSequence = workingCopy.getTokenHierarchy().tokenSequence(JavaTokenId.language());
98
        this.tokenSequence = workingCopy.getTokenHierarchy().tokenSequence(JavaTokenId.language());
98
        this.origText = workingCopy.getText();
99
        this.origText = workingCopy.getText();
99
        this.context = context;
100
        this.context = context;
100
        printer = new VeryPretty(workingCopy, CodeStyle.getDefault(null));
101
        this.tree2Tag = tree2Tag;
102
        this.tag2Span = (Map<Object, int[]>) tag2Span;//XXX
103
        printer = new VeryPretty(workingCopy, CodeStyle.getDefault(null), tree2Tag, tag2Span);
101
    }
104
    }
102
    
105
    
103
    public com.sun.tools.javac.util.List<Diff> getDiffs() {
106
    public com.sun.tools.javac.util.List<Diff> getDiffs() {
Lines 108-116 Link Here
108
            WorkingCopy copy,
111
            WorkingCopy copy,
109
            TreePath oldTreePath,
112
            TreePath oldTreePath,
110
            JCTree newTree,
113
            JCTree newTree,
111
            Map<Integer, String> userInfo)
114
            Map<Integer, String> userInfo,
115
            Map<Tree, ?> tree2Tag,
116
            Map<?, int[]> tag2Span)
112
    {
117
    {
113
        CasualDiff td = new CasualDiff(context, copy);
118
        CasualDiff td = new CasualDiff(context, copy, tree2Tag, tag2Span);
114
        JCTree oldTree = (JCTree) oldTreePath.getLeaf();
119
        JCTree oldTree = (JCTree) oldTreePath.getLeaf();
115
        td.oldTopLevel =  (JCCompilationUnit) (oldTree.getKind() == Kind.COMPILATION_UNIT ? oldTree : copy.getCompilationUnit());
120
        td.oldTopLevel =  (JCCompilationUnit) (oldTree.getKind() == Kind.COMPILATION_UNIT ? oldTree : copy.getCompilationUnit());
116
        
121
        
Lines 125-130 Link Here
125
        }
130
        }
126
        
131
        
127
        int[] bounds = td.getBounds(oldTree);
132
        int[] bounds = td.getBounds(oldTree);
133
        td.printer.setInitialOffset(bounds[0]);
128
        boolean isCUT = oldTree.getKind() == Kind.COMPILATION_UNIT;
134
        boolean isCUT = oldTree.getKind() == Kind.COMPILATION_UNIT;
129
        int start = isCUT ? 0 : bounds[0];
135
        int start = isCUT ? 0 : bounds[0];
130
        int end   = isCUT ? td.workingCopy.getText().length() : bounds[1];
136
        int end   = isCUT ? td.workingCopy.getText().length() : bounds[1];
Lines 175-183 Link Here
175
            WorkingCopy copy,
181
            WorkingCopy copy,
176
            List<? extends ImportTree> original,
182
            List<? extends ImportTree> original,
177
            List<? extends ImportTree> nue,
183
            List<? extends ImportTree> nue,
178
            Map<Integer, String> userInfo)
184
            Map<Integer, String> userInfo,
185
            Map<Tree, ?> tree2Tag,
186
            Map<?, int[]> tag2Span)
179
    {
187
    {
180
        CasualDiff td = new CasualDiff(context, copy);
188
        CasualDiff td = new CasualDiff(context, copy, tree2Tag, tag2Span);
181
        td.oldTopLevel = (JCCompilationUnit) copy.getCompilationUnit();
189
        td.oldTopLevel = (JCCompilationUnit) copy.getCompilationUnit();
182
        int start = td.oldTopLevel.getPackageName() != null ? td.endPos(td.oldTopLevel.getPackageName()) : 0;
190
        int start = td.oldTopLevel.getPackageName() != null ? td.endPos(td.oldTopLevel.getPackageName()) : 0;
183
        
191
        
Lines 2250-2256 Link Here
2250
                                found = true;
2258
                                found = true;
2251
                                VeryPretty oldPrinter = this.printer;
2259
                                VeryPretty oldPrinter = this.printer;
2252
                                int old = oldPrinter.indent();
2260
                                int old = oldPrinter.indent();
2253
                                this.printer = new VeryPretty(workingCopy);
2261
                                this.printer = new VeryPretty(workingCopy, CodeStyle.getDefault(null), tree2Tag, tag2Span, oldPrinter.toString().length() + oldPrinter.getInitialOffset());//XXX
2254
                                this.printer.reset(old);
2262
                                this.printer.reset(old);
2255
                                int index = oldList.indexOf(oldT);
2263
                                int index = oldList.indexOf(oldT);
2256
                                int[] poss = estimator.getPositions(index);
2264
                                int[] poss = estimator.getPositions(index);
Lines 2266-2272 Link Here
2266
                        if (lastdel != null && treesMatch(item.element, lastdel, false)) {
2274
                        if (lastdel != null && treesMatch(item.element, lastdel, false)) {
2267
                            VeryPretty oldPrinter = this.printer;
2275
                            VeryPretty oldPrinter = this.printer;
2268
                            int old = oldPrinter.indent();
2276
                            int old = oldPrinter.indent();
2269
                            this.printer = new VeryPretty(workingCopy);
2277
                            this.printer = new VeryPretty(workingCopy, CodeStyle.getDefault(null), tree2Tag, tag2Span, oldPrinter.toString().length() + oldPrinter.getInitialOffset());//XXX
2270
                            this.printer.reset(old);
2278
                            this.printer.reset(old);
2271
                            int index = oldList.indexOf(lastdel);
2279
                            int index = oldList.indexOf(lastdel);
2272
                            int[] poss = estimator.getPositions(index);
2280
                            int[] poss = estimator.getPositions(index);
Lines 2465-2471 Link Here
2465
     * just returns.
2473
     * just returns.
2466
     * 
2474
     * 
2467
     * @param  oldT  original tree in source code
2475
     * @param  oldT  original tree in source code
2468
     * @param  newT  tree to repace the original tree
2476
     * @param  newT  tree to replace the original tree
2469
     * @return position in original source
2477
     * @return position in original source
2470
     */
2478
     */
2471
    protected int diffTree(JCTree oldT, JCTree newT, int[] elementBounds) {
2479
    protected int diffTree(JCTree oldT, JCTree newT, int[] elementBounds) {
Lines 2473-2478 Link Here
2473
    }
2481
    }
2474
    
2482
    
2475
    protected int diffTree(JCTree oldT, JCTree newT, JCTree parent /*used only for modifiers*/, int[] elementBounds) {
2483
    protected int diffTree(JCTree oldT, JCTree newT, JCTree parent /*used only for modifiers*/, int[] elementBounds) {
2484
        Object t = tree2Tag.get(newT);
2485
        int result;
2486
        if (t != null) {
2487
            int start = printer.toString().length();
2488
            result = diffTreeImpl(oldT, newT, parent, elementBounds);
2489
            int end = printer.toString().length();
2490
            tag2Span.put(t, new int[]{start + printer.getInitialOffset(), end + printer.getInitialOffset()});
2491
        } else {
2492
            result = diffTreeImpl(oldT, newT, parent, elementBounds);
2493
        }
2494
        return result;
2495
    }
2496
    
2497
    protected int diffTreeImpl(JCTree oldT, JCTree newT, JCTree parent /*used only for modifiers*/, int[] elementBounds) {
2476
        if (oldT == null && newT != null)
2498
        if (oldT == null && newT != null)
2477
            throw new IllegalArgumentException("Null is not allowed in parameters.");
2499
            throw new IllegalArgumentException("Null is not allowed in parameters.");
2478
 
2500
 
(-)a/java.source/src/org/netbeans/modules/java/source/transform/ImmutableTreeTranslator.java (-4 / +14 lines)
Lines 51-56 Link Here
51
51
52
import java.util.ArrayList;
52
import java.util.ArrayList;
53
import java.util.List;
53
import java.util.List;
54
import java.util.Map;
54
import org.netbeans.modules.java.source.builder.ASTService;
55
import org.netbeans.modules.java.source.builder.ASTService;
55
import org.netbeans.modules.java.source.builder.CommentHandlerService;
56
import org.netbeans.modules.java.source.builder.CommentHandlerService;
56
import org.netbeans.modules.java.source.builder.QualIdentTree;
57
import org.netbeans.modules.java.source.builder.QualIdentTree;
Lines 86-102 Link Here
86
    protected ASTService model;
87
    protected ASTService model;
87
    private CompilationUnitTree topLevel;
88
    private CompilationUnitTree topLevel;
88
    private ImportAnalysis2 importAnalysis;
89
    private ImportAnalysis2 importAnalysis;
90
    private Map<Tree, Object> tree2Tag;
89
91
90
    public void attach(Context context, ImportAnalysis2 importAnalysis, CompilationUnitTree topLevel) {
92
    public void attach(Context context, ImportAnalysis2 importAnalysis, CompilationUnitTree topLevel, Map<Tree, Object> tree2Tag) {
91
        make = TreeFactory.instance(context);
93
        make = TreeFactory.instance(context);
92
        comments = CommentHandlerService.instance(context);
94
        comments = CommentHandlerService.instance(context);
93
        model = ASTService.instance(context);
95
        model = ASTService.instance(context);
94
        this.importAnalysis = importAnalysis;
96
        this.importAnalysis = importAnalysis;
95
        this.topLevel = topLevel;
97
        this.topLevel = topLevel;
98
        this.tree2Tag = tree2Tag;
96
    }
99
    }
97
    
100
    
98
    public void attach(Context context) {
101
    public void attach(Context context) {
99
        attach(context, new ImportAnalysis2(context), null);
102
        attach(context, new ImportAnalysis2(context), null, null);
100
    }
103
    }
101
    
104
    
102
    public void release() {
105
    public void release() {
Lines 112-119 Link Here
112
    public Tree translate(Tree tree) {
115
    public Tree translate(Tree tree) {
113
	if (tree == null)
116
	if (tree == null)
114
	    return null;
117
	    return null;
115
	else
118
	else {
116
	    return tree.accept(this, null);
119
	    Tree t = tree.accept(this, null);
120
            
121
            if (tree2Tag != null && tree != t) {
122
                tree2Tag.put(t, tree2Tag.get(tree));
123
            }
124
            
125
            return t;
126
        }
117
    }
127
    }
118
128
119
    public <T extends Tree> T translateClassRef(T tree) {
129
    public <T extends Tree> T translateClassRef(T tree) {

Return to bug 138225