• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package com.github.javaparser.ast.nodeTypes;
2 
3 import com.github.javaparser.Position;
4 import com.github.javaparser.Range;
5 import com.github.javaparser.ast.Node;
6 
7 import java.util.Optional;
8 
9 /**
10  * A node that has a Range, which is every Node.
11  */
12 public interface NodeWithRange<N> {
getRange()13     Optional<Range> getRange();
14 
setRange(Range range)15     N setRange(Range range);
16 
17     /**
18      * The begin position of this node in the source file.
19      */
getBegin()20     default Optional<Position> getBegin() {
21         return getRange().map(r -> r.begin);
22     }
23 
24     /**
25      * The end position of this node in the source file.
26      */
getEnd()27     default Optional<Position> getEnd() {
28         return getRange().map(r -> r.end);
29     }
30 
31     /**
32      * @deprecated use {@link #containsWithinRange(Node)} instead.
33      */
34     @Deprecated
containsWithin(Node other)35     default boolean containsWithin(Node other) {
36         return containsWithinRange(other);
37     }
38 
39     /**
40      * Checks whether the range of the given {@code Node} is contained within the range of this {@code NodeWithRange}.
41      * Note that any range contains itself, i.e., for any node {@code n}, we have that
42      * {@code n.containsWithinRange(n) == true}.
43      *
44      * <b>Notice:</b> This method compares two nodes based on their ranges <i>only</i>, but <i>not</i> based on the
45      * storage unit of the two nodes. Therefore, this method may return {@code true} for a node that is contained in a
46      * different file than this {@code NodeWithRange}. You may wish to use {@link Node#isAncestorOf(Node)} instead.
47      *
48      * @param other the node whose range should be compared with this node's range.
49      * @return {@code true} if the given node's range is contained within this node's range, and {@code false}
50      * otherwise.
51      */
containsWithinRange(Node other)52     default boolean containsWithinRange(Node other) {
53         if (getRange().isPresent() && other.getRange().isPresent()) {
54             return getRange().get().contains(other.getRange().get());
55         }
56         return false;
57     }
58 }
59