utils.js revision 1224:065b159bb922
1/*
2 * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/**
25 *
26 * @subtest
27 */
28
29var parser = Java.type('jdk.nashorn.api.tree.Parser');
30var tree = Java.type('jdk.nashorn.api.tree.Tree');
31var list = Java.type('java.util.List');
32var visitor = Java.type('jdk.nashorn.api.tree.SimpleTreeVisitorES5_1');
33var file = Java.type('java.io.File')
34var cls = Java.type('java.lang.Class')
35
36function convert (value) {
37    if (!value) {
38        return value;
39    }
40    var  obj = Object.bindProperties({}, value)
41    var result = {}
42    for (var i in obj) {
43        var val = obj[i]
44        if (typeof(val) == 'object') {
45            if (val instanceof cls) {
46                continue;
47            }
48            if (val instanceof tree) {
49                result[i] = convert(val)
50            }
51            else if (val instanceof list) {
52                var lst = []
53                for (var j in val) {
54                    lst.push(convert(val[j]))
55                }
56                result[i] = lst
57            }
58            else {
59                result[i] = String(val)
60            }
61        } else if (typeof(val) != 'function') {
62            result[i] = String(val)
63        }
64    }
65    return result
66}
67
68function parse(name, code, args, visitor, listener) {
69    var tree =  parser.create(args).parse(name, code, listener || null)
70    var results = []
71    tree.accept(visitor, results)
72    print(JSON.stringify(results, null, 2))
73}
74
75
76function parseDiagnostic (code, args) {
77    var messages = new Array()
78    var tree = parser.create(args).parse("test.js",  code, function (message) {
79        messages.push(convert(message))
80    })
81    print(JSON.stringify(messages, null, 2))
82}