File: Parser.java

package info (click to toggle)
libpgjava 8.4-701-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 3,532 kB
  • ctags: 4,162
  • sloc: java: 33,948; xml: 3,158; makefile: 14; sh: 10
file content (303 lines) | stat: -rw-r--r-- 10,233 bytes parent folder | download
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
/*-------------------------------------------------------------------------
*
* Copyright (c) 2006-2008, PostgreSQL Global Development Group
*
* IDENTIFICATION
*   $PostgreSQL: pgjdbc/org/postgresql/core/Parser.java,v 1.4 2008/01/08 06:56:27 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core;

/**
 * Basic query parser infrastructure.
 * 
 * @author Michael Paesold (mpaesold@gmx.at)
 */
public class Parser {

    /**
     * Find the end of the single-quoted string starting at the given offset.
     * 
     * Note: for <tt>'single '' quote in string'</tt>, this method currently
     * returns the offset of first <tt>'</tt> character after the initial
     * one. The caller must call the method a second time for the second
     * part of the quoted string.
     */
    public static int parseSingleQuotes(final char[] query, int offset,
                                        boolean standardConformingStrings) {
        // check for escape string syntax (E'')
        if (standardConformingStrings
                && offset >= 2
                && (query[offset-1] == 'e' || query[offset-1] == 'E')
                && charTerminatesIdentifier(query[offset-2]))
        {
            standardConformingStrings = false;
        }
        
        if (standardConformingStrings)
        {
            // do NOT treat backslashes as escape characters
            while (++offset < query.length)
            {
                switch (query[offset])
                {
                case '\'':
                    return offset;
                default:
                    break;
                }
            }
        }
        else
        {
            // treat backslashes as escape characters
            while (++offset < query.length)
            {
                switch (query[offset])
                {
                case '\\':
                    ++offset;
                    break;
                case '\'':
                    return offset;
                default:
                    break;
                }
            }
        }
        
        return query.length;
    }

    /**
     * Find the end of the double-quoted string starting at the given offset.
     *
     * Note: for <tt>&quot;double &quot;&quot; quote in string&quot;</tt>,
     * this method currently returns the offset of first <tt>&quot;</tt>
     * character after the initial one. The caller must call the method a
     * second time for the second part of the quoted string.
     */
    public static int parseDoubleQuotes(final char[] query, int offset) {
        while (++offset < query.length && query[offset] != '"') ;
        return offset;
    }

    /**
     * Test if the dollar character (<tt>$</tt>) at the given offset starts
     * a dollar-quoted string and return the offset of the ending dollar
     * character.
     */
    public static int parseDollarQuotes(final char[] query, int offset) {
        if (offset + 1 < query.length
                && (offset == 0 || !isIdentifierContChar(query[offset-1])))
        {
            int endIdx = -1;
            if (query[offset + 1] == '$')
                endIdx = offset + 1;
            else if (isDollarQuoteStartChar(query[offset + 1]))
            {
                for (int d = offset + 2; d < query.length; ++d)
                {
                    if (query[d] == '$')
                    {
                        endIdx = d;
                        break;
                    }
                    else if (!isDollarQuoteContChar(query[d]))
                        break;
                }
            }
            if (endIdx > 0)
            {
                // found; note: tag includes start and end $ character
                int tagIdx = offset, tagLen = endIdx - offset + 1;
                offset = endIdx; // loop continues at endIdx + 1
                for (++offset; offset < query.length; ++offset)
                {
                    if (query[offset] == '$' &&
                        subArraysEqual(query, tagIdx, offset, tagLen))
                    {
                        offset += tagLen - 1;
                        break;
                    }
                }
            }
        }        
        return offset;
    }

    /**
     * Test if the <tt>-</tt> character at <tt>offset</tt> starts a
     * <tt>--</tt> style line comment, and return the position of the first
     * <tt>\r</tt> or <tt>\n</tt> character.
     */
    public static int parseLineComment(final char[] query, int offset) {
        if (offset + 1 < query.length && query[offset + 1] == '-')
        {
            while (++offset < query.length)
            {
                if (query[offset] == '\r' || query[offset] == '\n')
                    break;
            }
        }
        return offset;
    }

    /**
     * Test if the <tt>/</tt> character at <tt>offset</tt> starts a block
     * comment, and return the position of the last <tt>/</tt> character.
     */
    public static int parseBlockComment(final char[] query, int offset) {
        if (offset + 1 < query.length && query[offset + 1] == '*')
        {
            // /* /* */ */ nest, according to SQL spec
            int level = 1;
            for (offset += 2; offset < query.length; ++offset)
            {
                switch (query[offset-1])
                {
                case '*':
                    if (query[offset] == '/')
                    {
                        --level;
                        ++offset; // don't parse / in */* twice
                    }
                    break;
                case '/':
                    if (query[offset] == '*')
                    {
                        ++level;
                        ++offset; // don't parse * in /*/ twice
                    }
                    break;
                default:
                    break;
                }

                if (level == 0)
                {
                    --offset; // reset position to last '/' char
                    break;
                }
            }
        }
        return offset;
    }
    
    /**
     * @return true if the character is a whitespace character as defined
     *         in the backend's parser
     */
    public static boolean isSpace(char c) {
       return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
    }
    
    /**
     * @return true if the given character is a valid character for an
     *         operator in the backend's parser
     */
    public static boolean isOperatorChar(char c) {
        /*
         * Extracted from operators defined by {self} and {op_chars}
         * in pgsql/src/backend/parser/scan.l.
         */
        return ",()[].;:+-*/%^<>=~!@#&|`?".indexOf(c) != -1;
    }

    /**
     * Checks if a character is valid as the start of an identifier.
     * 
     * @param c the character to check
     * @return true if valid as first character of an identifier; false if not
     */
    public static boolean isIdentifierStartChar(char c) {
        /*
         * Extracted from {ident_start} and {ident_cont} in
         * pgsql/src/backend/parser/scan.l:
         * ident_start    [A-Za-z\200-\377_]
         * ident_cont     [A-Za-z\200-\377_0-9\$]
         */
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
                || c == '_' || c > 127 ;
    }
    
    /**
     * Checks if a character is valid as the second or later character of an
     * identifier.
     * 
     * @param c the character to check
     * @return true if valid as second or later character of an identifier; false if not
     */
    public static boolean isIdentifierContChar(char c) {
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
                || c == '_' || c > 127
                || (c >= '0' && c <= '9')
                || c == '$';
    }
    
    /**
     * @return true if the character terminates an identifier
     */
    public static boolean charTerminatesIdentifier(char c) {
        return c == '"' || isSpace(c) || isOperatorChar(c);
    }

    /**
     * Checks if a character is valid as the start of a dollar quoting tag.
     * 
     * @param c the character to check
     * @return true if valid as first character of a dollar quoting tag; false if not
     */
    public static boolean isDollarQuoteStartChar(char c) {
        /*
         * The allowed dollar quote start and continuation characters
         * must stay in sync with what the backend defines in
         * pgsql/src/backend/parser/scan.l
         */
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
                || c == '_' || c > 127;
    }

    /**
     * Checks if a character is valid as the second or later character of a
     * dollar quoting tag.
     * 
     * @param c the character to check
     * @return true if valid as second or later character of a dollar quoting tag;
     *         false if not
     */
    public static boolean isDollarQuoteContChar(char c) {
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
                || c == '_' || c > 127
                || (c >= '0' && c <= '9');
    }

    /**
     * Compares two sub-arrays of the given character array for equalness.
     * If the length is zero, the result is true if and only if the offsets
     * are within the bounds of the array.
     * 
     * @param arr  a char array
     * @param offA first sub-array start offset
     * @param offB second sub-array start offset
     * @param len  length of the sub arrays to compare
     * @return     true if the sub-arrays are equal; false if not
     */
    private static boolean subArraysEqual(final char[] arr,
                                          final int offA, final int offB,
                                          final int len) {
        if (offA < 0 || offB < 0
                || offA >= arr.length || offB >= arr.length
                || offA + len > arr.length || offB + len > arr.length)
            return false;
        
        for (int i = 0; i < len; ++i)
        {
            if (arr[offA + i] != arr[offB + i])
                return false;
        }
    
        return true;
    }
}