Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 44885fcb9c161135e256ed291f38a555f286f77d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package org.eclipse.cdt.core.dom.lrparser.action;

import java.util.Arrays;
import java.util.List;

import lpg.lpgjavaruntime.IToken;

import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.internal.core.dom.parser.ASTNode;

@SuppressWarnings("restriction")
public final class ParserUtil {

	private ParserUtil() {}
	
	
	public static int offset(IToken token) {
		return token.getStartOffset();
	}

	public static int offset(IASTNode node) {
		return ((ASTNode)node).getOffset();
	}

	public static int length(IToken token) {
		return endOffset(token) - offset(token);
	}

	public static int length(IASTNode node) {
		return ((ASTNode)node).getLength();
	}

	public static int endOffset(IASTNode node) {
		return offset(node) + length(node);
	}

	public static int endOffset(IToken token) {
		return token.getEndOffset();
	}


	

	public static void setOffsetAndLength(IASTNode node, IToken token) {
		((ASTNode)node).setOffsetAndLength(offset(token), length(token));
	}

	public static void setOffsetAndLength(IASTNode node, int offset, int length) {
		((ASTNode)node).setOffsetAndLength(offset, length);
	}
	
	public static void setOffsetAndLength(IASTNode node, IASTNode from) {
		setOffsetAndLength(node, offset(from), length(from));
	}

	
	public static boolean isSameName(IASTName name1, IASTName name2) {
		return Arrays.equals(name1.getLookupKey(), name2.getLookupKey());
	}
	
	
	/**
	 * Allows simple pattern match testing of lists of tokens.
	 * 
	 * @throws NullPointerException if source or pattern is null
	 */
	public static boolean matchTokens(List<IToken> source, ITokenMap tokenMap, Integer ... pattern) {
		if(source.size() != pattern.length) // throws NPE if either parameter is null
			return false;
		
		for(int i = 0, n = pattern.length; i < n; i++) {
			if(tokenMap.mapKind(source.get(i).getKind()) != pattern[i].intValue())
				return false;
		}
		return true;
	}
	
	
	/**
	 * Finds the tokens in the given list that are between startOffset and endOffset.
	 * Note, the offsets have to be exact.
	 */
	public static List<IToken> tokenOffsetSubList(List<IToken> tokens, int startOffset, int endOffset) {
		int first = 0, last = 0;
		int i = 0;
		for(IToken t : tokens) {
			if(offset(t) == startOffset) {
				first = i;
			}
			if(endOffset(t) == endOffset) {
				last = i;
				break;
			}
			i++;
		}
		return tokens.subList(first, last + 1);
	}
	
	
	
}

Back to the top