parser.js revision 1423:c13179703f65
1/* 2 * Copyright (c) 2010, 2013, 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 * Parse function returns a JSON object representing ECMAScript code passed. 26 * name is optional name for the code source and location param tells whether to 27 * include location information for AST nodes or not. 28 * 29 * Example: 30 * 31 * load("nashorn:parser.js"); 32 * try { 33 * var json = parse("print('hello')"); 34 * print(JSON.stringify(json)); 35 * } catch (e) { 36 * print(e); 37 * } 38 */ 39function parse(/*code, [name], [location]*/) { 40 var code, name = "<unknown>", location = false; 41 switch (arguments.length) { 42 case 3: 43 location = arguments[2]; 44 case 2: 45 name = arguments[1]; 46 case 1: 47 code = arguments[0]; 48 } 49 50 var jsonStr = Packages.jdk.nashorn.api.scripting.ScriptUtils.parse(code, name, location); 51 return JSON.parse(jsonStr, 52 function (prop, value) { 53 if (typeof(value) == 'string' && prop == "value") { 54 // handle regexps and strings - both are encoded as strings but strings 55 // do not start with '/'. If regexp, then eval it to make RegExp object 56 return value.startsWith('/')? eval(value) : value.substring(1); 57 } else { 58 // anything else is returned "as is" 59 return value; 60 } 61 }); 62} 63 64