summaryrefslogtreecommitdiff
path: root/java/src/json/ext/Generator.java
blob: 6a996868e04e4e01a73d27aab8da95e8685dceb6 (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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/*
 * This code is copyrighted work by Daniel Luz <dev at mernen dot com>.
 *
 * Distributed under the Ruby license: https://www.ruby-lang.org/en/about/license.txt
 */
package json.ext;

import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBasicObject;
import org.jruby.RubyBignum;
import org.jruby.RubyBoolean;
import org.jruby.RubyFixnum;
import org.jruby.RubyFloat;
import org.jruby.RubyHash;
import org.jruby.RubyString;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;

public final class Generator {
    private Generator() {
        throw new RuntimeException();
    }

    /**
     * Encodes the given object as a JSON string, using the given handler.
     */
    static <T extends IRubyObject> RubyString
            generateJson(ThreadContext context, T object,
                         Handler<? super T> handler, IRubyObject[] args) {
        Session session = new Session(context, args.length > 0 ? args[0] : null);
        return session.infect(handler.generateNew(session, object));
    }

    /**
     * Encodes the given object as a JSON string, detecting the appropriate handler
     * for the given object.
     */
    static <T extends IRubyObject> RubyString
            generateJson(ThreadContext context, T object, IRubyObject[] args) {
        Handler<? super T> handler = getHandlerFor(context.runtime, object);
        return generateJson(context, object, handler, args);
    }

    /**
     * Encodes the given object as a JSON string, using the appropriate
     * handler if one is found or calling #to_json if not.
     */
    public static <T extends IRubyObject> RubyString
            generateJson(ThreadContext context, T object,
                         GeneratorState config) {
        Session session = new Session(context, config);
        Handler<? super T> handler = getHandlerFor(context.runtime, object);
        return handler.generateNew(session, object);
    }

    /**
     * Returns the best serialization handler for the given object.
     */
    // Java's generics can't handle this satisfactorily, so I'll just leave
    // the best I could get and ignore the warnings
    @SuppressWarnings("unchecked")
    private static <T extends IRubyObject> Handler<? super T> getHandlerFor(Ruby runtime, T object) {
        switch (((RubyBasicObject) object).getNativeClassIndex()) {
            case NIL    : return (Handler) NIL_HANDLER;
            case TRUE   : return (Handler) TRUE_HANDLER;
            case FALSE  : return (Handler) FALSE_HANDLER;
            case FLOAT  : return (Handler) FLOAT_HANDLER;
            case FIXNUM : return (Handler) FIXNUM_HANDLER;
            case BIGNUM : return (Handler) BIGNUM_HANDLER;
            case STRING :
                if (((RubyBasicObject) object).getMetaClass() != runtime.getString()) break;
                return (Handler) STRING_HANDLER;
            case ARRAY  :
                if (((RubyBasicObject) object).getMetaClass() != runtime.getArray()) break;
                return (Handler) ARRAY_HANDLER;
            case HASH   :
                if (((RubyBasicObject) object).getMetaClass() != runtime.getHash()) break;
                return (Handler) HASH_HANDLER;
        }
        return GENERIC_HANDLER;
    }


    /* Generator context */

    /**
     * A class that concentrates all the information that is shared by
     * generators working on a single session.
     *
     * <p>A session is defined as the process of serializing a single root
     * object; any handler directly called by container handlers (arrays and
     * hashes/objects) shares this object with its caller.
     *
     * <p>Note that anything called indirectly (via {@link GENERIC_HANDLER})
     * won't be part of the session.
     */
    static class Session {
        private final ThreadContext context;
        private GeneratorState state;
        private IRubyObject possibleState;
        private RuntimeInfo info;
        private StringEncoder stringEncoder;

        private boolean tainted = false;
        private boolean untrusted = false;

        Session(ThreadContext context, GeneratorState state) {
            this.context = context;
            this.state = state;
        }

        Session(ThreadContext context, IRubyObject possibleState) {
            this.context = context;
            this.possibleState = possibleState == null || possibleState.isNil()
                    ? null : possibleState;
        }

        public ThreadContext getContext() {
            return context;
        }

        public Ruby getRuntime() {
            return context.getRuntime();
        }

        public GeneratorState getState() {
            if (state == null) {
                state = GeneratorState.fromState(context, getInfo(), possibleState);
            }
            return state;
        }

        public RuntimeInfo getInfo() {
            if (info == null) info = RuntimeInfo.forRuntime(getRuntime());
            return info;
        }

        public StringEncoder getStringEncoder() {
            if (stringEncoder == null) {
                stringEncoder = new StringEncoder(context, getState().asciiOnly(), getState().escapeSlash());
            }
            return stringEncoder;
        }

        public void infectBy(IRubyObject object) {
            if (object.isTaint()) tainted = true;
            if (object.isUntrusted()) untrusted = true;
        }

        public <T extends IRubyObject> T infect(T object) {
            if (tainted) object.setTaint(true);
            if (untrusted) object.setUntrusted(true);
            return object;
        }
    }


    /* Handler base classes */

    private static abstract class Handler<T extends IRubyObject> {
        /**
         * Returns an estimative of how much space the serialization of the
         * given object will take. Used for allocating enough buffer space
         * before invoking other methods.
         */
        int guessSize(Session session, T object) {
            return 4;
        }

        RubyString generateNew(Session session, T object) {
            RubyString result;
            ByteList buffer = new ByteList(guessSize(session, object));
            generate(session, object, buffer);
            result = RubyString.newString(session.getRuntime(), buffer);
            ThreadContext context = session.getContext();
            RuntimeInfo info = session.getInfo();
            result.force_encoding(context, info.utf8.get());
            return result;
        }

        abstract void generate(Session session, T object, ByteList buffer);
    }

    /**
     * A handler that returns a fixed keyword regardless of the passed object.
     */
    private static class KeywordHandler<T extends IRubyObject>
            extends Handler<T> {
        private final ByteList keyword;

        private KeywordHandler(String keyword) {
            this.keyword = new ByteList(ByteList.plain(keyword), false);
        }

        @Override
        int guessSize(Session session, T object) {
            return keyword.length();
        }

        @Override
        RubyString generateNew(Session session, T object) {
            return RubyString.newStringShared(session.getRuntime(), keyword);
        }

        @Override
        void generate(Session session, T object, ByteList buffer) {
            buffer.append(keyword);
        }
    }


    /* Handlers */

    static final Handler<RubyBignum> BIGNUM_HANDLER =
        new Handler<RubyBignum>() {
            @Override
            void generate(Session session, RubyBignum object, ByteList buffer) {
                // JRUBY-4751: RubyBignum.to_s() returns generic object
                // representation (fixed in 1.5, but we maintain backwards
                // compatibility; call to_s(IRubyObject[]) then
                buffer.append(((RubyString)object.to_s(IRubyObject.NULL_ARRAY)).getByteList());
            }
        };

    static final Handler<RubyFixnum> FIXNUM_HANDLER =
        new Handler<RubyFixnum>() {
            @Override
            void generate(Session session, RubyFixnum object, ByteList buffer) {
                buffer.append(object.to_s().getByteList());
            }
        };

    static final Handler<RubyFloat> FLOAT_HANDLER =
        new Handler<RubyFloat>() {
            @Override
            void generate(Session session, RubyFloat object, ByteList buffer) {
                double value = RubyFloat.num2dbl(object);

                if (Double.isInfinite(value) || Double.isNaN(value)) {
                    if (!session.getState().allowNaN()) {
                        throw Utils.newException(session.getContext(),
                                Utils.M_GENERATOR_ERROR,
                                object + " not allowed in JSON");
                    }
                }
                buffer.append(((RubyString)object.to_s()).getByteList());
            }
        };

    static final Handler<RubyArray> ARRAY_HANDLER =
        new Handler<RubyArray>() {
            @Override
            int guessSize(Session session, RubyArray object) {
                GeneratorState state = session.getState();
                int depth = state.getDepth();
                int perItem =
                    4                                           // prealloc
                    + (depth + 1) * state.getIndent().length()  // indent
                    + 1 + state.getArrayNl().length();          // ',' arrayNl
                return 2 + object.size() * perItem;
            }

            @Override
            void generate(Session session, RubyArray object, ByteList buffer) {
                ThreadContext context = session.getContext();
                Ruby runtime = context.getRuntime();
                GeneratorState state = session.getState();
                int depth = state.increaseDepth();

                ByteList indentUnit = state.getIndent();
                byte[] shift = Utils.repeat(indentUnit, depth);

                ByteList arrayNl = state.getArrayNl();
                byte[] delim = new byte[1 + arrayNl.length()];
                delim[0] = ',';
                System.arraycopy(arrayNl.unsafeBytes(), arrayNl.begin(), delim, 1,
                        arrayNl.length());

                session.infectBy(object);

                buffer.append((byte)'[');
                buffer.append(arrayNl);
                boolean firstItem = true;
                for (int i = 0, t = object.getLength(); i < t; i++) {
                    IRubyObject element = object.eltInternal(i);
                    session.infectBy(element);
                    if (firstItem) {
                        firstItem = false;
                    } else {
                        buffer.append(delim);
                    }
                    buffer.append(shift);
                    Handler<IRubyObject> handler = (Handler<IRubyObject>) getHandlerFor(runtime, element);
                    handler.generate(session, element, buffer);
                }

                state.decreaseDepth();
                if (arrayNl.length() != 0) {
                    buffer.append(arrayNl);
                    buffer.append(shift, 0, state.getDepth() * indentUnit.length());
                }

                buffer.append((byte)']');
            }
        };

    static final Handler<RubyHash> HASH_HANDLER =
        new Handler<RubyHash>() {
            @Override
            int guessSize(Session session, RubyHash object) {
                GeneratorState state = session.getState();
                int perItem =
                    12    // key, colon, comma
                    + (state.getDepth() + 1) * state.getIndent().length()
                    + state.getSpaceBefore().length()
                    + state.getSpace().length();
                return 2 + object.size() * perItem;
            }

            @Override
            void generate(final Session session, RubyHash object,
                          final ByteList buffer) {
                ThreadContext context = session.getContext();
                final Ruby runtime = context.getRuntime();
                final GeneratorState state = session.getState();
                final int depth = state.increaseDepth();

                final ByteList objectNl = state.getObjectNl();
                final byte[] indent = Utils.repeat(state.getIndent(), depth);
                final ByteList spaceBefore = state.getSpaceBefore();
                final ByteList space = state.getSpace();

                buffer.append((byte)'{');
                buffer.append(objectNl);

                final boolean[] firstPair = new boolean[]{true};
                object.visitAll(new RubyHash.Visitor() {
                    @Override
                    public void visit(IRubyObject key, IRubyObject value) {
                        if (firstPair[0]) {
                            firstPair[0] = false;
                        } else {
                            buffer.append((byte)',');
                            buffer.append(objectNl);
                        }
                        if (objectNl.length() != 0) buffer.append(indent);

                        STRING_HANDLER.generate(session, key.asString(), buffer);
                        session.infectBy(key);

                        buffer.append(spaceBefore);
                        buffer.append((byte)':');
                        buffer.append(space);

                        Handler<IRubyObject> valueHandler = (Handler<IRubyObject>) getHandlerFor(runtime, value);
                        valueHandler.generate(session, value, buffer);
                        session.infectBy(value);
                    }
                });
                state.decreaseDepth();
                if (!firstPair[0] && objectNl.length() != 0) {
                    buffer.append(objectNl);
                }
                buffer.append(Utils.repeat(state.getIndent(), state.getDepth()));
                buffer.append((byte)'}');
            }
        };

    static final Handler<RubyString> STRING_HANDLER =
        new Handler<RubyString>() {
            @Override
            int guessSize(Session session, RubyString object) {
                // for most applications, most strings will be just a set of
                // printable ASCII characters without any escaping, so let's
                // just allocate enough space for that + the quotes
                return 2 + object.getByteList().length();
            }

            @Override
            void generate(Session session, RubyString object, ByteList buffer) {
                RuntimeInfo info = session.getInfo();
                RubyString src;

                if (object.encoding(session.getContext()) != info.utf8.get()) {
                    src = (RubyString)object.encode(session.getContext(),
                                                    info.utf8.get());
                } else {
                    src = object;
                }

                session.getStringEncoder().encode(src.getByteList(), buffer);
            }
        };

    static final Handler<RubyBoolean> TRUE_HANDLER =
        new KeywordHandler<RubyBoolean>("true");
    static final Handler<RubyBoolean> FALSE_HANDLER =
        new KeywordHandler<RubyBoolean>("false");
    static final Handler<IRubyObject> NIL_HANDLER =
        new KeywordHandler<IRubyObject>("null");

    /**
     * The default handler (<code>Object#to_json</code>): coerces the object
     * to string using <code>#to_s</code>, and serializes that string.
     */
    static final Handler<IRubyObject> OBJECT_HANDLER =
        new Handler<IRubyObject>() {
            @Override
            RubyString generateNew(Session session, IRubyObject object) {
                RubyString str = object.asString();
                return STRING_HANDLER.generateNew(session, str);
            }

            @Override
            void generate(Session session, IRubyObject object, ByteList buffer) {
                RubyString str = object.asString();
                STRING_HANDLER.generate(session, str, buffer);
            }
        };

    /**
     * A handler that simply calls <code>#to_json(state)</code> on the
     * given object.
     */
    static final Handler<IRubyObject> GENERIC_HANDLER =
        new Handler<IRubyObject>() {
            @Override
            RubyString generateNew(Session session, IRubyObject object) {
                if (object.respondsTo("to_json")) {
                    IRubyObject result = object.callMethod(session.getContext(), "to_json",
                              new IRubyObject[] {session.getState()});
                    if (result instanceof RubyString) return (RubyString)result;
                    throw session.getRuntime().newTypeError("to_json must return a String");
                } else {
                    return OBJECT_HANDLER.generateNew(session, object);
                }
            }

            @Override
            void generate(Session session, IRubyObject object, ByteList buffer) {
                RubyString result = generateNew(session, object);
                buffer.append(result.getByteList());
            }
        };
}