Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.library / org.gvsig.expressionevaluator / org.gvsig.expressionevaluator.lib / org.gvsig.expressionevaluator.lib.api / src / main / java / org / gvsig / expressionevaluator / spi / AbstractLexicalAnalyzer.java @ 44750

History | View | Annotate | Download (15 KB)

1
package org.gvsig.expressionevaluator.spi;
2

    
3
import org.gvsig.expressionevaluator.LexicalAnalyzer;
4
import java.text.NumberFormat;
5
import java.text.ParsePosition;
6
import java.util.HashMap;
7
import java.util.Locale;
8
import java.util.Map;
9
import java.util.Objects;
10
import java.util.Stack;
11
import org.apache.commons.lang3.StringUtils;
12
import org.gvsig.expressionevaluator.ExpressionRuntimeException;
13
import org.gvsig.expressionevaluator.ExpressionSyntaxException;
14
import org.gvsig.expressionevaluator.I18N;
15
import org.gvsig.tools.lang.Cloneable;
16

    
17
public abstract class AbstractLexicalAnalyzer implements LexicalAnalyzer {
18

    
19
    protected class DefaultToken implements Token {
20

    
21
        private int type;
22
        private String literal;
23
        private Object value;
24

    
25
        public DefaultToken() {
26
        }
27

    
28
        @Override
29
        public Token clone() throws CloneNotSupportedException {
30
            // We will assume that the properties of the class are immutable, so 
31
            // it would suffice to call the super class.
32
            DefaultToken other = (DefaultToken) super.clone();
33
            return other;
34
        }
35

    
36
        @Override
37
        public void set(int type, String literal) {
38
            this.set(type, literal, literal);
39
        }
40

    
41
        @Override
42
        public void set(int type, String literal, Object value) {
43
            this.literal = literal;
44
            this.type = type;
45
            this.value = value;
46
        }
47

    
48
        @Override
49
        public int getType() {
50
            return type;
51
        }
52

    
53
        @Override
54
        public Object getValue() {
55
            return value;
56
        }
57

    
58
        @Override
59
        public String getLiteral() {
60
            return literal;
61
        }
62

    
63
        @Override
64
        public void setLiteral(String literal) {
65
            this.literal = literal;
66
        }
67

    
68
        @Override
69
        public boolean is(String... values) {
70
            for (String theValue : values) {
71
                if( StringUtils.isBlank(literal) ) {
72
                    if( StringUtils.isBlank(theValue) ) {
73
                        return true;
74
                    }
75
                    continue;
76
                }
77
                if( StringUtils.isBlank(theValue) ) {
78
                    continue;
79
                }
80
                if( theValue.trim().equalsIgnoreCase(this.literal.trim()) ) {
81
                    return true;
82
                }
83
            }
84
            return false;
85
        }
86

    
87
        @Override
88
        public String toString() {
89
            return String.format("{%d,%s,%s}", this.type, Objects.toString(this.literal), Objects.toString(value));
90
        }
91
        
92
    }
93

    
94
    protected class Buffer implements Cloneable {
95

    
96
        StringBuilder builder;
97

    
98
        public Buffer() {
99
            this.builder = new StringBuilder();
100
        }
101

    
102
        @Override
103
        public Buffer clone() throws CloneNotSupportedException {
104
            Buffer other = (Buffer) super.clone();
105
            other.builder = new StringBuilder(builder);
106
            return other;
107
        }
108

    
109
        public void clear() {
110
            builder.delete(0, builder.length());
111
        }
112

    
113
        public void add(char ch) {
114
            builder.append(ch);
115
        }
116

    
117
        public int length() {
118
            return this.builder.length();
119
        }
120

    
121
        @Override
122
        public String toString() {
123
            return this.builder.toString();
124
        }
125
    }
126

    
127
    protected static final char EOF = 0;
128

    
129
    private NumberFormat nf;
130
    private ParsePosition nfPos;
131
    private Stack<Integer> states;
132
    private String source;
133
    private int position;
134
    private int lineno;
135
    private int column;
136

    
137
    protected Buffer buffer;
138
    protected Token token;
139
    protected Map<String, Integer> tokens;
140
    protected boolean useBracketsForIdentifiers;
141
            
142
    public AbstractLexicalAnalyzer(String source) {
143
        this.useBracketsForIdentifiers = false;
144
        this.position = 0;
145
        this.source = source;
146
        this.states = new Stack<>();
147
        this.buffer = new Buffer();
148
        this.token = this.createToken();
149

    
150
        this.nf = NumberFormat.getInstance(Locale.UK);
151
        this.nf.setGroupingUsed(false);
152
        
153
        this.nfPos = new ParsePosition(0);
154

    
155
        this.tokens = new HashMap<>();
156
    }
157

    
158
    public AbstractLexicalAnalyzer() {
159
        this(null);
160
    }
161

    
162
    protected Token createToken() {
163
        return new DefaultToken();
164
    }
165
    
166
    @Override
167
    public LexicalAnalyzer clone() throws CloneNotSupportedException {
168
        AbstractLexicalAnalyzer other = (AbstractLexicalAnalyzer) super.clone();
169
        other.nf = NumberFormat.getInstance(Locale.UK);
170
        other.nfPos = new ParsePosition(0);
171
        other.buffer = buffer.clone();
172
        other.token = token.clone();
173
        other.states = new Stack<>();
174
        other.states.addAll(states);
175
        other.tokens = new HashMap<>(tokens);
176
        return other;
177
    }
178

    
179
    @Override
180
    public void setSource(String source) {
181
        this.source = source;
182
        this.position = 0;
183
    }
184

    
185
    @Override
186
    public String getSource() {
187
        return this.source;
188
    }
189

    
190
    @Override
191
    public Token next() {
192
        return getToken();
193
    }
194

    
195
    @Override
196
    public Token look() {
197
        save_state();
198
        try {
199
            return getToken();
200
        } finally {
201
            restore_state();
202
        }
203
    }
204

    
205
    abstract protected Token getToken();
206

    
207
    public void save_state() {
208
        this.states.push(position);
209
    }
210

    
211
    public void restore_state() {
212
        position = this.states.pop();
213
    }
214

    
215
    public void drop_state() {
216
        this.states.pop();
217
    }
218

    
219
    @Override
220
    public int getPosition() {
221
        return position;
222
    }
223
    
224
    private void calcualteLineAndColumn() {
225
        final String s = this.source;
226
        int max = s.length();
227
        if( max > this.position ) {
228
            max = this.position;
229
        }
230
        int line = 1;
231
        int col = 0;
232
        for (int i = 0; i < max ; i++) {
233
            if( s.charAt(i)=='\n' ) {
234
                line++;
235
                col = 0;
236
            } 
237
            col++;
238
        }
239
        this.lineno = line;
240
        this.column = col;
241
    }
242

    
243
    @Override
244
    public int getLine() {
245
        this.calcualteLineAndColumn();
246
        return lineno;
247
    }
248

    
249
    @Override
250
    public int getColumn() {
251
        this.calcualteLineAndColumn();
252
        return column;
253
    }
254

    
255
    @Override
256
    public boolean isEOF() {
257
        return this.position >= this.source.length();
258
    }
259

    
260
    protected void skipblanks() {
261
        if (isEOF()) {
262
            return;
263
        }
264
        char ch = getch();
265
        while (ch != EOF && Character.isWhitespace(ch)) {
266
            ch = getch();
267
        }
268
        ungetch();
269
    }
270

    
271
    protected char lookch() {
272
        if (this.position >= this.source.length()) {
273
            return EOF;
274
        }
275
        return this.source.charAt(this.position);
276
    }
277

    
278
    protected char getch() {
279
        if (this.position >= this.source.length()) {
280
            return EOF;
281
        }
282
        this.column++;
283
        return this.source.charAt(this.position++);
284
    }
285

    
286
    protected void ungetch() {
287
        this.position--;
288
        if (this.position < 0) {
289
            this.position = 0;
290
        }
291
        this.column--;
292
        if (this.column < 0) {
293
            this.column = 0;
294
        }
295
    }
296

    
297
    protected void parseString() {
298
        buffer.clear();
299
        char ch = getch();
300
        while (true) {
301
            if (ch == EOF) {
302
                throw new ExpressionSyntaxException(I18N.End_of_string_was_expected_and_end_of_source_was_found(), this);
303
            }
304
            if (ch == '\'') {
305
                ch = getch();
306
                if (ch == EOF) {
307
                    break;
308
                }
309
                if (ch != '\'') {
310
                    ungetch();
311
                    break;
312
                }
313
            }
314
            buffer.add(ch);
315
            ch = getch();
316
        }
317
        token.set(Token.STRING_LITERAL, buffer.toString());
318
    }
319

    
320
    protected void parseDMSNumber() {
321
        int d;
322
        int m;
323
        int s_i;
324
        double s_d;
325
        double s;
326
        char ch;
327
        Integer sign = null;
328
        
329
        skipblanks();
330
        ch = getch();
331
        if( ch!='@' ) {
332
            throw new ExpressionSyntaxException(I18N.Wrong_special_number_start(), this);
333
        }
334
        
335
        // Parseamos los grados
336
        skipblanks();
337
        ch = getch();
338
        if( ch=='+' ) {
339
            sign = 1;
340
            ch = getch();
341
        } else if ( ch=='-' ) {
342
            sign = -1;
343
            ch = getch();
344
        }
345
        
346
        buffer.clear();
347
        if( !Character.isDigit(ch) ) {
348
            throw new ExpressionSyntaxException(I18N.Expected_a_number_at_position_XpositionX(this.getPosition()), this);        
349
        }
350
        while (true) {
351
            if (ch == EOF) {
352
                throw new ExpressionSyntaxException(I18N.End_of_string_was_expected_and_end_of_source_was_found(), this);        
353
            }
354
            if( !Character.isDigit(ch) ) {
355
                break;
356
            }
357
            buffer.add(ch);
358
            ch = getch();
359
        }
360
        if( !StringUtils.contains(" ?:", ch) ) {
361
            throw new ExpressionSyntaxException(I18N.Expected_XexpectedX_and_found_XfoundX(" ", String.valueOf(ch)), this);
362
        }
363
        d = Integer.parseInt(buffer.toString());
364
        
365
        // Parseamos los minutos
366
        skipblanks();
367
        ch = getch();
368
        buffer.clear();
369
        if( !Character.isDigit(ch) ) {
370
            throw new ExpressionSyntaxException(I18N.Expected_a_number_at_position_XpositionX(this.getPosition()), this);        
371
        }
372
        while (true) {
373
            if (ch == EOF) {
374
                throw new ExpressionSyntaxException(I18N.End_of_string_was_expected_and_end_of_source_was_found(), this);        
375
            }
376
            if( !Character.isDigit(ch) ) {
377
                break;
378
            }
379
            buffer.add(ch);
380
            ch = getch();
381
        }
382
        if( !StringUtils.contains(" ':", ch) ) {
383
            throw new ExpressionSyntaxException(I18N.Expected_XexpectedX_and_found_XfoundX(" ", String.valueOf(ch)), this);
384
        }
385
        m = Integer.parseInt(buffer.toString());
386

    
387
        // Parseamos la parte entera de los segundos
388
        skipblanks();
389
        ch = getch();
390
        buffer.clear();
391
        if( !Character.isDigit(ch) ) {
392
            throw new ExpressionSyntaxException(I18N.Expected_a_number_at_position_XpositionX(this.getPosition()), this);        
393
        }
394
        while (true) {
395
            if (ch == EOF) {
396
                throw new ExpressionSyntaxException(I18N.End_of_string_was_expected_and_end_of_source_was_found(), this);        
397
            }
398
            if( !Character.isDigit(ch) ) {
399
                break;
400
            }
401
            buffer.add(ch);
402
            ch = getch();
403
        }
404
        s_i = Integer.parseInt(buffer.toString());
405

    
406
        if( ch == '.' ) {
407
            // Parseamos la parte decimal de los segundos
408
            skipblanks();
409
            ch = getch();
410
            buffer.clear();
411
            if( !Character.isDigit(ch) ) {
412
                throw new ExpressionSyntaxException(I18N.Expected_a_number_at_position_XpositionX(this.getPosition()), this);        
413
            }
414
            while (true) {
415
                if (ch == EOF) {
416
//                    throw new ExpressionSyntaxException(I18N.End_of_string_was_expected_and_end_of_source_was_found(), this);        
417
                    break;
418
                }
419
                if( !Character.isDigit(ch) ) {
420
                    break;
421
                }
422
                buffer.add(ch);
423
                ch = getch();
424
            }            
425
            String ss = buffer.toString();
426
            s_d = (double) Integer.parseInt(ss) / Math.pow(10, ss.length());
427
        } else {
428
            s_d = 0;
429
        }
430
        if( ch!=EOF && !StringUtils.contains(" \"", ch) ) {
431
            throw new ExpressionSyntaxException(I18N.Expected_XexpectedX_and_found_XfoundX(" ", String.valueOf(ch)), this);
432
        }
433
        
434
        s = s_i + s_d; 
435
        
436
        double dd = d + m / 60.0 + s / 3600.0;
437
        
438
        if( sign==null ) {
439
            skipblanks();
440
            ch = getch();
441
            switch(ch) {
442
                case 'N':
443
                case 'n':
444
                    if( dd>90 ) {
445
                        throw new ExpressionSyntaxException(I18N.Incorrect_value_for_latitude(dd), this);
446
                    }
447
                    sign = 1;
448
                    break;
449

    
450
                case 'S':
451
                case 's':
452
                    if( dd>90 ) {
453
                        throw new ExpressionSyntaxException(I18N.Incorrect_value_for_latitude(dd), this);
454
                    }
455
                    sign = -1;
456
                    break;
457
                case 'E':
458
                case 'e':
459
                    if( dd>180 ) {
460
                        throw new ExpressionSyntaxException(I18N.Incorrect_value_for_latitude(dd), this);
461
                    }
462
                    sign = 1;
463
                    break;
464

    
465
                case 'O':
466
                case 'o':
467
                case 'W':
468
                case 'w':
469
                    if( dd>180 ) {
470
                        throw new ExpressionSyntaxException(I18N.Incorrect_value_for_longitude(dd), this);
471
                    }
472
                    sign = -1;
473
                    break;
474

    
475
                default:
476
                    throw new ExpressionSyntaxException(I18N.Expected_XexpectedX_and_found_XfoundX("N/S/E/W", String.valueOf(ch)), this);
477
            }
478
        } 
479
        dd = dd * sign;
480
        token.set(
481
                Token.FLOATING_POINT_LITERAL,
482
                String.format("@%s%d? %d' %f\"", sign<0? "-":"+", d,m,s) ,
483
                dd
484
        );
485
    }
486
    
487
    protected void parseNumber() {
488
        this.nfPos.setIndex(this.position);
489
        Number n = nf.parse(source, this.nfPos);
490
        if (this.nfPos.getIndex() == this.position) {
491
            throw new ExpressionRuntimeException(I18N.Expected_a_number_at_position_XpositionX(this.nfPos.getIndex()));
492
        }
493
        String literal = source.substring(this.position, this.nfPos.getIndex());
494
        this.position = this.nfPos.getIndex();
495
        if( n instanceof Long ) {
496
            long l = ((Long)n);
497
            if( l>Integer.MIN_VALUE && l<Integer.MAX_VALUE ) {
498
                token.set(Token.INTEGER_LITERAL, literal, (int)l);
499
            } else {
500
                token.set(Token.INTEGER_LITERAL, literal, n);
501
            }
502
        } else if( n instanceof Integer) {
503
            token.set(Token.INTEGER_LITERAL, literal, n);
504
        } else {
505
            token.set(Token.FLOATING_POINT_LITERAL, literal, n);
506
        }
507
    }
508
    
509
    @Override
510
    public void setUseBracketsForIdentifiers(boolean useBracketsForIdentifiers) {
511
        this.useBracketsForIdentifiers = useBracketsForIdentifiers;
512
    }
513
    
514
    @Override
515
    public boolean getUseBracketsForIdentifiers() {
516
        return this.useBracketsForIdentifiers;
517
    }
518
    
519
    public String getSourceContext() {
520
        String s = StringUtils.left(source, position) + "[*]" + StringUtils.mid(source, position, 200);
521
        if( s.length()>200 ) {
522
            s = "..."+StringUtils.mid(s, position-100, 200)+"...";
523
        }
524
        return s;
525
    }      
526
    
527
}