aboutsummaryrefslogtreecommitdiff
path: root/src/jdk/nashorn/internal/parser/JSONParser.java
blob: 5468ca3d74e172ba2c6643c129bc8136c0cee6c4 (plain)
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package jdk.nashorn.internal.parser;

import static jdk.nashorn.internal.parser.TokenType.COLON;
import static jdk.nashorn.internal.parser.TokenType.COMMARIGHT;
import static jdk.nashorn.internal.parser.TokenType.EOF;
import static jdk.nashorn.internal.parser.TokenType.ESCSTRING;
import static jdk.nashorn.internal.parser.TokenType.RBRACE;
import static jdk.nashorn.internal.parser.TokenType.RBRACKET;
import static jdk.nashorn.internal.parser.TokenType.STRING;

import java.util.ArrayList;
import java.util.List;
import jdk.nashorn.internal.ir.LiteralNode;
import jdk.nashorn.internal.ir.Node;
import jdk.nashorn.internal.ir.ObjectNode;
import jdk.nashorn.internal.ir.PropertyNode;
import jdk.nashorn.internal.ir.UnaryNode;
import jdk.nashorn.internal.runtime.ErrorManager;
import jdk.nashorn.internal.runtime.Source;

/**
 * Parses JSON text and returns the corresponding IR node. This is derived from the objectLiteral production of the main parser.
 *
 * See: 15.12.1.2 The JSON Syntactic Grammar
 */
public class JSONParser extends AbstractParser {

    /**
     * Constructor
     * @param source  the source
     * @param errors  the error manager
     * @param strict  are we in strict mode
     */
    public JSONParser(final Source source, final ErrorManager errors, final boolean strict) {
        super(source, errors, strict);
    }

    /**
     * Implementation of the Quote(value) operation as defined in the ECMA script spec
     * It wraps a String value in double quotes and escapes characters within in
     *
     * @param value string to quote
     *
     * @return quoted and escaped string
     */
    public static String quote(final String value) {

        final StringBuilder product = new StringBuilder();

        product.append("\"");

        for (final char ch : value.toCharArray()) {
            // TODO: should use a table?
            switch (ch) {
            case '\\':
                product.append("\\\\");
                break;
            case '"':
                product.append("\\\"");
                break;
            case '\b':
                product.append("\\b");
                break;
            case '\f':
                product.append("\\f");
                break;
            case '\n':
                product.append("\\n");
                break;
            case '\r':
                product.append("\\r");
                break;
            case '\t':
                product.append("\\t");
                break;
            default:
                if (ch < ' ') {
                    product.append(Lexer.unicodeEscape(ch));
                    break;
                }

                product.append(ch);
                break;
            }
        }

        product.append("\"");

        return product.toString();
    }

    /**
     * Public parsed method - start lexing a new token stream for
     * a JSON script
     *
     * @return the JSON literal
     */
    public Node parse() {
        stream = new TokenStream();

        lexer = new Lexer(source, stream) {

            @Override
            protected boolean skipComments() {
                return false;
            }

            @Override
            protected boolean isStringDelimiter(final char ch) {
                return ch == '\"';
            }

            @Override
            protected boolean isWhitespace(final char ch) {
                return Lexer.isJsonWhitespace(ch);
            }

            @Override
            protected boolean isEOL(final char ch) {
                return Lexer.isJsonEOL(ch);
            }
        };

        k = -1;

        next();

        final Node resultNode = jsonLiteral();
        expect(EOF);

        return resultNode;
    }

    @SuppressWarnings("fallthrough")
    private LiteralNode<?> getStringLiteral() {
        final LiteralNode<?> literal = getLiteral();
        final String         str     = (String)literal.getValue();

        for (int i = 0; i < str.length(); i++) {
            final char ch = str.charAt(i);
            switch (ch) {
            default:
                if (ch > 0x001f) {
                    break;
                }
            case '"':
            case '\\':
                error(AbstractParser.message("unexpected.token", str));
                break;
            }
        }

        return literal;
    }

    /**
     * Parse a JSON literal from the token stream
     * @return the JSON literal as a Node
     */
    private Node jsonLiteral() {
        final long literalToken = token;

        switch (type) {
        case STRING:
            return getStringLiteral();
        case ESCSTRING:
        case DECIMAL:
        case FLOATING:
            return getLiteral();
        case FALSE:
            next();
            return LiteralNode.newInstance(source, literalToken, finish, false);
        case TRUE:
            next();
            return LiteralNode.newInstance(source, literalToken, finish, true);
        case NULL:
            next();
            return LiteralNode.newInstance(source, literalToken, finish);
        case LBRACKET:
            return arrayLiteral();
        case LBRACE:
            return objectLiteral();
        /*
         * A.8.1 JSON Lexical Grammar
         *
         * JSONNumber :: See 15.12.1.1
         *    -opt DecimalIntegerLiteral JSONFractionopt ExponentPartopt
         */
        case SUB:
            next();

            final long realToken = token;
            final Object value = getValue();

            if (value instanceof Number) {
                next();
                return new UnaryNode(source, literalToken, LiteralNode.newInstance(source, realToken, finish, (Number)value));
            }

            error(AbstractParser.message("expected", "number", type.getNameOrType()));
            break;
        default:
            break;
        }

        error(AbstractParser.message("expected", "json literal", type.getNameOrType()));
        return null;
    }

    /**
     * Parse an array literal from the token stream
     * @return the array literal as a Node
     */
    private Node arrayLiteral() {
        // Unlike JavaScript array literals, elison is not permitted in JSON.

        // Capture LBRACKET token.
        final long arrayToken = token;
        // LBRACKET tested in caller.
        next();

        Node result = null;
        // Prepare to accummulating elements.
        final List<Node> elements = new ArrayList<>();

loop:
        while (true) {
            switch (type) {
            case RBRACKET:
                next();
                result = LiteralNode.newInstance(source, arrayToken, finish, elements);
                break loop;

            case COMMARIGHT:
                next();
                break;

            default:
                // Add expression element.
                elements.add(jsonLiteral());
                // Comma between array elements is mandatory in JSON.
                if (type != COMMARIGHT && type != RBRACKET) {
                    error(AbstractParser.message("expected", ", or ]", type.getNameOrType()));
                }
                break;
            }
        }

        return result;
    }

    /**
     * Parse an object literal from the token stream
     * @return the object literal as a Node
     */
    private Node objectLiteral() {
        // Capture LBRACE token.
        final long objectToken = token;
        // LBRACE tested in caller.
        next();

        // Prepare to accumulate elements.
        final List<Node> elements = new ArrayList<>();

        // Create a block for the object literal.
loop:
        while (true) {
            switch (type) {
            case RBRACE:
                next();
                break loop;

            case COMMARIGHT:
                next();
                break;

            default:
                // Get and add the next property.
                final Node property = propertyAssignment();
                elements.add(property);

                // Comma between property assigments is mandatory in JSON.
                if (type != RBRACE && type != COMMARIGHT) {
                    error(AbstractParser.message("expected", ", or }", type.getNameOrType()));
                }
                break;
            }
        }

        // Construct new object literal.
        return new ObjectNode(source, objectToken, finish, elements);
    }

    /**
     * Parse a property assignment from the token stream
     * @return the property assignment as a Node
     */
    private Node propertyAssignment() {
        // Capture firstToken.
        final long propertyToken = token;
        LiteralNode<?> name = null;

        if (type == STRING) {
            name = getStringLiteral();
        } else if (type == ESCSTRING) {
            name = getLiteral();
        }

        if (name != null) {
            expect(COLON);
            final Node value = jsonLiteral();
            return new PropertyNode(source, propertyToken, value.getFinish(), name, value);
        }

        // Raise an error.
        error(AbstractParser.message("expected", "string", type.getNameOrType()));

        return null;
    }

}