ScriptEnvironment.java revision 1451:d47674217066
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. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26package jdk.nashorn.internal.runtime; 27 28import java.io.PrintWriter; 29import java.util.HashMap; 30import java.util.List; 31import java.util.Locale; 32import java.util.Map; 33import java.util.StringTokenizer; 34import java.util.TimeZone; 35import java.util.logging.Level; 36import jdk.nashorn.internal.codegen.Namespace; 37import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor; 38import jdk.nashorn.internal.runtime.options.KeyValueOption; 39import jdk.nashorn.internal.runtime.options.LoggingOption; 40import jdk.nashorn.internal.runtime.options.LoggingOption.LoggerInfo; 41import jdk.nashorn.internal.runtime.options.Option; 42import jdk.nashorn.internal.runtime.options.Options; 43 44/** 45 * Script environment consists of command line options, arguments, script files 46 * and output and error writers, top level Namespace etc. 47 */ 48public final class ScriptEnvironment { 49 // Primarily intended to be used in test environments so that eager compilation tests work without an 50 // error when tested with optimistic compilation. 51 private static final boolean ALLOW_EAGER_COMPILATION_SILENT_OVERRIDE = Options.getBooleanProperty( 52 "nashorn.options.allowEagerCompilationSilentOverride", false); 53 54 /** Output writer for this environment */ 55 private final PrintWriter out; 56 57 /** Error writer for this environment */ 58 private final PrintWriter err; 59 60 /** Top level namespace. */ 61 private final Namespace namespace; 62 63 /** Current Options object. */ 64 private final Options options; 65 66 /** Size of the per-global Class cache size */ 67 public final int _class_cache_size; 68 69 /** -classpath value. */ 70 public final String _classpath; 71 72 /** Only compile script, do not run it or generate other ScriptObjects */ 73 public final boolean _compile_only; 74 75 /** Accept "const" keyword and treat it as variable. Interim feature */ 76 public final boolean _const_as_var; 77 78 /** Accumulated callsite flags that will be used when bootstrapping script callsites */ 79 public final int _callsite_flags; 80 81 /** Generate line number table in class files */ 82 public final boolean _debug_lines; 83 84 /** Directory in which source files and generated class files are dumped */ 85 public final String _dest_dir; 86 87 /** Display stack trace upon error, default is false */ 88 public final boolean _dump_on_error; 89 90 /** Invalid lvalue expressions should be reported as early errors */ 91 public final boolean _early_lvalue_error; 92 93 /** Empty statements should be preserved in the AST */ 94 public final boolean _empty_statements; 95 96 /** Show full Nashorn version */ 97 public final boolean _fullversion; 98 99 /** Launch using as fx application */ 100 public final boolean _fx; 101 102 /** Use single Global instance per jsr223 engine instance. */ 103 public final boolean _global_per_engine; 104 105 /** Enable experimental ECMAScript 6 features. */ 106 public final boolean _es6; 107 108 /** Argument passed to compile only if optimistic compilation should take place */ 109 public static final String COMPILE_ONLY_OPTIMISTIC_ARG = "optimistic"; 110 111 /** 112 * Behavior when encountering a function declaration in a lexical context where only statements are acceptable 113 * (function declarations are source elements, but not statements). 114 */ 115 public enum FunctionStatementBehavior { 116 /** 117 * Accept the function declaration silently and treat it as if it were a function expression assigned to a local 118 * variable. 119 */ 120 ACCEPT, 121 /** 122 * Log a parser warning, but accept the function declaration and treat it as if it were a function expression 123 * assigned to a local variable. 124 */ 125 WARNING, 126 /** 127 * Raise a {@code SyntaxError}. 128 */ 129 ERROR 130 } 131 132 /** 133 * Behavior when encountering a function declaration in a lexical context where only statements are acceptable 134 * (function declarations are source elements, but not statements). 135 */ 136 public final FunctionStatementBehavior _function_statement; 137 138 /** Should lazy compilation take place */ 139 public final boolean _lazy_compilation; 140 141 /** Should optimistic types be used */ 142 public final boolean _optimistic_types; 143 144 /** Create a new class loaded for each compilation */ 145 public final boolean _loader_per_compile; 146 147 /** Do not support Java support extensions. */ 148 public final boolean _no_java; 149 150 /** Do not support non-standard syntax extensions. */ 151 public final boolean _no_syntax_extensions; 152 153 /** Do not support typed arrays. */ 154 public final boolean _no_typed_arrays; 155 156 /** Only parse the source code, do not compile */ 157 public final boolean _parse_only; 158 159 /** Enable disk cache for compiled scripts */ 160 public final boolean _persistent_cache; 161 162 /** Print the AST before lowering */ 163 public final boolean _print_ast; 164 165 /** Print the AST after lowering */ 166 public final boolean _print_lower_ast; 167 168 /** Print resulting bytecode for script */ 169 public final boolean _print_code; 170 171 /** Directory (optional) to print files to */ 172 public final String _print_code_dir; 173 174 /** List of functions to write to the print code dir, optional */ 175 public final String _print_code_func; 176 177 /** Print memory usage for IR after each phase */ 178 public final boolean _print_mem_usage; 179 180 /** Print function will no print newline characters */ 181 public final boolean _print_no_newline; 182 183 /** Print AST in more human readable form */ 184 public final boolean _print_parse; 185 186 /** Print AST in more human readable form after Lowering */ 187 public final boolean _print_lower_parse; 188 189 /** print symbols and their contents for the script */ 190 public final boolean _print_symbols; 191 192 /** is this environment in scripting mode? */ 193 public final boolean _scripting; 194 195 /** is this environment in strict mode? */ 196 public final boolean _strict; 197 198 /** print version info of Nashorn */ 199 public final boolean _version; 200 201 /** should code verification be done of generated bytecode */ 202 public final boolean _verify_code; 203 204 /** time zone for this environment */ 205 public final TimeZone _timezone; 206 207 /** Local for error messages */ 208 public final Locale _locale; 209 210 /** Logging */ 211 public final Map<String, LoggerInfo> _loggers; 212 213 /** Timing */ 214 public final Timing _timing; 215 216 /** Whether to use anonymous classes. See {@link #useAnonymousClasses(boolean)}. */ 217 private final AnonymousClasses _anonymousClasses; 218 private enum AnonymousClasses { 219 AUTO, 220 OFF, 221 ON 222 } 223 224 /** 225 * Constructor 226 * 227 * @param options a Options object 228 * @param out output print writer 229 * @param err error print writer 230 */ 231 @SuppressWarnings("unused") 232 public ScriptEnvironment(final Options options, final PrintWriter out, final PrintWriter err) { 233 this.out = out; 234 this.err = err; 235 this.namespace = new Namespace(); 236 this.options = options; 237 238 _class_cache_size = options.getInteger("class.cache.size"); 239 _classpath = options.getString("classpath"); 240 _compile_only = options.getBoolean("compile.only"); 241 _const_as_var = options.getBoolean("const.as.var"); 242 _debug_lines = options.getBoolean("debug.lines"); 243 _dest_dir = options.getString("d"); 244 _dump_on_error = options.getBoolean("doe"); 245 _early_lvalue_error = options.getBoolean("early.lvalue.error"); 246 _empty_statements = options.getBoolean("empty.statements"); 247 _fullversion = options.getBoolean("fullversion"); 248 if (options.getBoolean("function.statement.error")) { 249 _function_statement = FunctionStatementBehavior.ERROR; 250 } else if (options.getBoolean("function.statement.warning")) { 251 _function_statement = FunctionStatementBehavior.WARNING; 252 } else { 253 _function_statement = FunctionStatementBehavior.ACCEPT; 254 } 255 _fx = options.getBoolean("fx"); 256 _global_per_engine = options.getBoolean("global.per.engine"); 257 _optimistic_types = options.getBoolean("optimistic.types"); 258 final boolean lazy_compilation = options.getBoolean("lazy.compilation"); 259 if (!lazy_compilation && _optimistic_types) { 260 if (!ALLOW_EAGER_COMPILATION_SILENT_OVERRIDE) { 261 throw new IllegalStateException( 262 ECMAErrors.getMessage( 263 "config.error.eagerCompilationConflictsWithOptimisticTypes", 264 options.getOptionTemplateByKey("lazy.compilation").getName(), 265 options.getOptionTemplateByKey("optimistic.types").getName())); 266 } 267 _lazy_compilation = true; 268 } else { 269 _lazy_compilation = lazy_compilation; 270 } 271 _loader_per_compile = options.getBoolean("loader.per.compile"); 272 _no_java = options.getBoolean("no.java"); 273 _no_syntax_extensions = options.getBoolean("no.syntax.extensions"); 274 _no_typed_arrays = options.getBoolean("no.typed.arrays"); 275 _parse_only = options.getBoolean("parse.only"); 276 _persistent_cache = options.getBoolean("persistent.code.cache"); 277 _print_ast = options.getBoolean("print.ast"); 278 _print_lower_ast = options.getBoolean("print.lower.ast"); 279 _print_code = options.getString("print.code") != null; 280 _print_mem_usage = options.getBoolean("print.mem.usage"); 281 _print_no_newline = options.getBoolean("print.no.newline"); 282 _print_parse = options.getBoolean("print.parse"); 283 _print_lower_parse = options.getBoolean("print.lower.parse"); 284 _print_symbols = options.getBoolean("print.symbols"); 285 _scripting = options.getBoolean("scripting"); 286 _strict = options.getBoolean("strict"); 287 _version = options.getBoolean("version"); 288 _verify_code = options.getBoolean("verify.code"); 289 290 final String anonClasses = options.getString("anonymous.classes"); 291 if (anonClasses == null || anonClasses.equals("auto")) { 292 _anonymousClasses = AnonymousClasses.AUTO; 293 } else if (anonClasses.equals("true")) { 294 _anonymousClasses = AnonymousClasses.ON; 295 } else if (anonClasses.equals("false")) { 296 _anonymousClasses = AnonymousClasses.OFF; 297 } else { 298 throw new RuntimeException("Unsupported value for anonymous classes: " + anonClasses); 299 } 300 301 302 final String language = options.getString("language"); 303 if (language == null || language.equals("es5")) { 304 _es6 = false; 305 } else if (language.equals("es6")) { 306 _es6 = true; 307 } else { 308 throw new RuntimeException("Unsupported language: " + language); 309 } 310 311 String dir = null; 312 String func = null; 313 final String pc = options.getString("print.code"); 314 if (pc != null) { 315 final StringTokenizer st = new StringTokenizer(pc, ","); 316 while (st.hasMoreTokens()) { 317 final StringTokenizer st2 = new StringTokenizer(st.nextToken(), ":"); 318 while (st2.hasMoreTokens()) { 319 final String cmd = st2.nextToken(); 320 if ("dir".equals(cmd)) { 321 dir = st2.nextToken(); 322 } else if ("function".equals(cmd)) { 323 func = st2.nextToken(); 324 } 325 } 326 } 327 } 328 _print_code_dir = dir; 329 _print_code_func = func; 330 331 int callSiteFlags = 0; 332 if (options.getBoolean("profile.callsites")) { 333 callSiteFlags |= NashornCallSiteDescriptor.CALLSITE_PROFILE; 334 } 335 336 if (options.get("trace.callsites") instanceof KeyValueOption) { 337 callSiteFlags |= NashornCallSiteDescriptor.CALLSITE_TRACE; 338 final KeyValueOption kv = (KeyValueOption)options.get("trace.callsites"); 339 if (kv.hasValue("miss")) { 340 callSiteFlags |= NashornCallSiteDescriptor.CALLSITE_TRACE_MISSES; 341 } 342 if (kv.hasValue("enterexit") || (callSiteFlags & NashornCallSiteDescriptor.CALLSITE_TRACE_MISSES) == 0) { 343 callSiteFlags |= NashornCallSiteDescriptor.CALLSITE_TRACE_ENTEREXIT; 344 } 345 if (kv.hasValue("objects")) { 346 callSiteFlags |= NashornCallSiteDescriptor.CALLSITE_TRACE_VALUES; 347 } 348 } 349 this._callsite_flags = callSiteFlags; 350 351 final Option<?> timezoneOption = options.get("timezone"); 352 if (timezoneOption != null) { 353 this._timezone = (TimeZone)timezoneOption.getValue(); 354 } else { 355 this._timezone = TimeZone.getDefault(); 356 } 357 358 final Option<?> localeOption = options.get("locale"); 359 if (localeOption != null) { 360 this._locale = (Locale)localeOption.getValue(); 361 } else { 362 this._locale = Locale.getDefault(); 363 } 364 365 final LoggingOption loggingOption = (LoggingOption)options.get("log"); 366 this._loggers = loggingOption == null ? new HashMap<String, LoggerInfo>() : loggingOption.getLoggers(); 367 368 final LoggerInfo timeLoggerInfo = _loggers.get(Timing.getLoggerName()); 369 this._timing = new Timing(timeLoggerInfo != null && timeLoggerInfo.getLevel() != Level.OFF); 370 } 371 372 /** 373 * Get the output stream for this environment 374 * @return output print writer 375 */ 376 public PrintWriter getOut() { 377 return out; 378 } 379 380 /** 381 * Get the error stream for this environment 382 * @return error print writer 383 */ 384 public PrintWriter getErr() { 385 return err; 386 } 387 388 /** 389 * Get the namespace for this environment 390 * @return namespace 391 */ 392 public Namespace getNamespace() { 393 return namespace; 394 } 395 396 /** 397 * Return the JavaScript files passed to the program 398 * 399 * @return a list of files 400 */ 401 public List<String> getFiles() { 402 return options.getFiles(); 403 } 404 405 /** 406 * Return the user arguments to the program, i.e. those trailing "--" after 407 * the filename 408 * 409 * @return a list of user arguments 410 */ 411 public List<String> getArguments() { 412 return options.getArguments(); 413 } 414 415 /** 416 * Check if there is a logger registered for a particular name: typically 417 * the "name" attribute of a Loggable annotation on a class 418 * 419 * @param name logger name 420 * @return true, if a logger exists for that name, false otherwise 421 */ 422 public boolean hasLogger(final String name) { 423 return _loggers.get(name) != null; 424 } 425 426 /** 427 * Check if compilation/runtime timings are enabled 428 * @return true if enabled 429 */ 430 public boolean isTimingEnabled() { 431 return _timing != null ? _timing.isEnabled() : false; 432 } 433 434 /** 435 * Returns true if compilation should use anonymous classes. 436 * @param isEval true if compilation is an eval call. 437 * @return true if anonymous classes should be used 438 */ 439 public boolean useAnonymousClasses(final boolean isEval) { 440 return _anonymousClasses == AnonymousClasses.ON || (_anonymousClasses == AnonymousClasses.AUTO && isEval); 441 } 442 443} 444