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