This repository has been archived by the owner on Apr 3, 2018. It is now read-only.
/
BlockHeuristicsScannner.java
309 lines (263 loc) · 9.77 KB
/
BlockHeuristicsScannner.java
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/*******************************************************************************
* Copyright (c) 2010 Bruno Medeiros and other Contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Bruno Medeiros - initial API and implementation
*******************************************************************************/
package melnorme.lang.ide.core.text;
import static melnorme.utilbox.core.Assert.AssertNamespace.assertFail;
import static melnorme.utilbox.core.Assert.AssertNamespace.assertTrue;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
/**
* A scanner to parse block tokens, and determine the balance of open vs. close tokens.
* The blocks are specified by pairs of characters (must be one char in length each).
* The scanning is partition aware, it only parse partitions of a given type.
*
* The scanner is heuristic in that the block balance may not be 100% accurate according to
* the underlying language sematics of the source being scanned.
*/
public class BlockHeuristicsScannner extends AbstractDocumentScanner {
public static final class BlockTokenRule {
public final char open;
public final char close;
public BlockTokenRule(char open, char close) {
this.open = open;
this.close = close;
}
}
protected final BlockTokenRule[] blockRules;
protected final BlockTokenRule[] blockRulesReversed;
public BlockHeuristicsScannner(IDocument document, String partitioning, String contentType,
BlockTokenRule... blockRules) {
super(document, partitioning, contentType);
this.blockRules = blockRules;
blockRulesReversed = new BlockTokenRule[blockRules.length];
for (int i = 0; i < blockRules.length; i++) {
BlockTokenRule blockRule = blockRules[i];
blockRulesReversed[i] = new BlockTokenRule(blockRule.close, blockRule.open);
}
}
public char getClosingPeer(char openChar) {
return getMatchingPeer(openChar, blockRules);
}
public char getOpeningPeer(char closeChar) {
return getMatchingPeer(closeChar, blockRulesReversed);
}
public boolean isClosingBrace(char closeChar) {
for (BlockTokenRule blockTokenRule : blockRules) {
if(closeChar == blockTokenRule.close) {
return true;
}
}
return false;
}
public static char getMatchingPeer(char openChar, BlockTokenRule[] blockTokenRules) {
for (int i = 0; i < blockTokenRules.length; i++) {
BlockTokenRule blockRule = blockTokenRules[i];
if(blockRule.open == openChar){
return blockRule.close;
}
}
throw assertFail();
}
protected int getPriorityOfBlockToken(char blockToken) {
for (int i = 0; i < blockRules.length; i++) {
BlockTokenRule blockRule = blockRules[i];
if(blockRule.open == blockToken || blockRule.close == blockToken) {
return i;
}
}
throw assertFail();
}
/*-------------------*/
public static class BlockBalanceResult {
public int unbalancedOpens = 0;
public int unbalancedCloses = 0;
public int rightmostUnbalancedBlockCloseOffset = -1;
public int rightmostUnbalancedBlockOpenOffset = -1;
}
/** Calculate the block balance in given range. */
public BlockBalanceResult calculateBlockBalances(int beginPos, int endPos) throws BadLocationException {
// Calculate backwards
setScanRange(endPos, beginPos);
// Ideally we would fully parse the code to figure the delta.
// But ATM we just estimate using number of blocks
BlockBalanceResult result = new BlockBalanceResult();
while(readPreviousCharacter() != TOKEN_EOF) {
for (int i = 0; i < blockRules.length; i++) {
BlockTokenRule blockRule = blockRules[i];
if(token == blockRule.close) {
int blockCloseOffset = getPosition();
// do a subscan
int balance = scanToBlockPeer(i, prevTokenFn, blockRules);
if(balance > 0) {
// block start not found
result.unbalancedCloses = balance;
result.rightmostUnbalancedBlockCloseOffset = blockCloseOffset;
return result;
}
break;
}
if(token == blockRule.open) {
result.unbalancedOpens++;
if(result.rightmostUnbalancedBlockOpenOffset == -1) {
result.rightmostUnbalancedBlockOpenOffset = getPosition();
}
break;
}
}
}
return result;
}
public abstract class FnTokenAdvance {
public abstract int advanceToken() ;
public abstract void revertToken() ;
}
public final FnTokenAdvance prevTokenFn = new FnTokenAdvance() {
@Override
public int advanceToken() {
return readPreviousCharacter();
}
@Override
public void revertToken() {
revertPreviousCharacter();
}
};
public final FnTokenAdvance nextTokenFn = new FnTokenAdvance() {
@Override
public int advanceToken() {
return readNextCharacter();
}
@Override
public void revertToken() {
revertNextCharacter();
}
};
public int scanToBlockStart(int blockCloseOffset) throws BadLocationException {
char blockClose = document.getChar(blockCloseOffset);
return scanToBlockStart(blockCloseOffset, blockClose);
}
public int scanToBlockStart(int blockCloseOffset, char blockClose) {
setPosition(blockCloseOffset);
posLimit = 0;
return scanToBlockStartForChar(blockClose, prevTokenFn, blockRules);
}
public int scanToBlockEnd(int blockOpenOffset) throws BadLocationException {
setScanRange(blockOpenOffset+1, document.getLength());
char blockOpen = document.getChar(blockOpenOffset);
return scanToBlockEnd(blockOpen);
}
protected int scanToBlockEnd(char blockOpen) {
return scanToBlockStartForChar(blockOpen, nextTokenFn, blockRulesReversed);
}
protected int scanToBlockStartForChar(char blockClose, FnTokenAdvance fnAdvance, BlockTokenRule[] blockTkRules) {
int ix = getPriorityOfBlockToken(blockClose);
return scanToBlockPeer(ix, fnAdvance, blockTkRules);
}
/** Scans in search of a block peer (open/close).
* Stops on EOF, or when block peer is found (balance is 0)
* @return 0 if block peer token was found (even if assumed by a syntax correction),
* or a count of how many blocks were left open.
*/
protected int scanToBlockPeer(int expectedTokenIx, FnTokenAdvance fnAdvance, BlockTokenRule[] blockTkRules) {
assertTrue(expectedTokenIx >= 0 && expectedTokenIx < blockTkRules.length);
while(fnAdvance.advanceToken() != TOKEN_EOF) {
for (int i = 0; i < blockTkRules.length; i++) {
BlockTokenRule blockRule = blockTkRules[i];
if(token == blockRule.close) {
int pendingBlocks = scanToBlockPeer(i, fnAdvance, blockTkRules);
if(pendingBlocks > 0) {
return pendingBlocks + 1;
}
break;
}
if(token == blockRule.open) {
if(i == expectedTokenIx){
return 0;
} else {
// syntax error
if(i < expectedTokenIx) {
// Stronger rule takes precedence.
// Assume syntax correction, as if blockRule[expectedTokenIx].open was found:
fnAdvance.revertToken();
token = TOKEN_INVALID;
return 0;
} else {
// ignore token
}
}
break;
}
}
}
return 1; // Balance is 1 if we reached the end without finding peer
}
/** Finds the offset where starts the blocks whose end token is at given blockCloseOffset */
public int findBlockStart(int blockCloseOffset) throws BadLocationException {
scanToBlockStart(blockCloseOffset);
return getPosition();
}
public int findBlockStart(int blockCloseOffset, char blockClose) {
scanToBlockStart(blockCloseOffset, blockClose);
return getPosition();
}
public boolean shouldCloseBlock(int blockOpenOffset) {
assertTrue(blockOpenOffset != -1);
char primaryBlockOpen = source.charAt(blockOpenOffset);
int primaryBlockPriority = getPriorityOfBlockToken(primaryBlockOpen);
char blockOpen = primaryBlockOpen;
int leftOffset = blockOpenOffset;
int rightOffset = blockOpenOffset+1;
while(true) {
assertTrue(getPriorityOfBlockToken(blockOpen) == primaryBlockPriority);
setScanRange(rightOffset, document.getLength());
int balance = scanToBlockEnd(blockOpen);
if(balance == 0 && token == TOKEN_INVALID) {
return true; // a block close is necessary
}
if(balance > 0) {
return true;
}
// Otherwise look for unmatched block opens on left, that are at least as important at the primary block
rightOffset = getPosition(); // save value for later iterations
setScanRange(leftOffset, 0);
int balanceToTheLeft = findUnmatchedOpen(primaryBlockPriority);
leftOffset = getPosition(); // save value for later iterations
if(balanceToTheLeft <= 0) {
return false; // relevant balance is zero or less, should not close
} else {
// Got an unmatched open
blockOpen = (char) token;
if(getPriorityOfBlockToken(blockOpen) < primaryBlockPriority) {
// opening is from syntax-dominant block, doesn't matter the rest of the balance
return false;
}
continue;
}
}
}
protected int findUnmatchedOpen(int requiredPriority) {
while(prevTokenFn.advanceToken() != TOKEN_EOF) {
for (int i = 0; i < blockRules.length; i++) {
BlockTokenRule blockRule = blockRules[i];
if(token == blockRule.close) {
// do a subscan
if(scanToBlockPeer(i, prevTokenFn, blockRules) > 0) {
// block start not found, so there is an unmatched close
return -1;
}
break;
}
if(token == blockRule.open && (getPriorityOfBlockToken((char) token) <= requiredPriority)) {
return 1;
}
}
}
return 0;
}
}