Try to fold away unnecessary object instantiation.
e.g. this[new String('eval')] -> this.eval
552481
private Node tryFoldCtorCall(Node n) {
    checkArgument(n.isNew());

    // we can remove this for GETELEM calls (anywhere else?)
    if (inForcedStringContext(n)) {
      return tryFoldInForcedStringContext(n);
    }
    return n;
  }
16413
function() {
    var extended = {},
        deep     = false,
        i        = 0,
        length   = arguments.length;

    if (Object.prototype.toString.call(arguments[0]) === '[object Boolean]'){
      deep = arguments[0];
      i++;
    }

    var merge = function(obj) {
      for (var prop in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, prop)) {
          if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') {
            extended[prop] = window.AB.extend(true, extended[prop], obj[prop]);
          } else {
            extended[prop] = obj[prop];
          }
        }
      }
    };

    for (; i < length; i++) {
      merge(arguments[i]);
    }

    return extended;
  }
922050
Object eval(Class scriptClass, final ScriptContext ctx) throws ScriptException {
        // Bindings so script has access to this environment.
        // Only initialize once.
        if (null == ctx.getAttribute("context", ScriptContext.ENGINE_SCOPE)) {
            // add context to bindings
            ctx.setAttribute("context", ctx, ScriptContext.ENGINE_SCOPE);

            // direct output to ctx.getWriter
            // If we're wrapping with a PrintWriter here,
            // enable autoFlush because otherwise it might not get done!
            final Writer writer = ctx.getWriter();
            ctx.setAttribute("out", (writer instanceof PrintWriter) ?
                    writer :
                    new PrintWriter(writer, true),
                    ScriptContext.ENGINE_SCOPE);

// Not going to do this after all (at least for now).
// Scripts can use context.{reader, writer, errorWriter}.
// That is a modern version of System.{in, out, err} or Console.{reader, writer}().
//
//            // New I/O names consistent with ScriptContext and java.io.Console.
//
//            ctx.setAttribute("writer", writer, ScriptContext.ENGINE_SCOPE);
//
//            // Direct errors to ctx.getErrorWriter
//            final Writer errorWriter = ctx.getErrorWriter();
//            ctx.setAttribute("errorWriter", (errorWriter instanceof PrintWriter) ?
//                                    errorWriter :
//                                    new PrintWriter(errorWriter),
//                                    ScriptContext.ENGINE_SCOPE);
//
//            // Get input from ctx.getReader
//            // We don't wrap with BufferedReader here because we expect that if
//            // the host wants that they do it.  Either way Groovy scripts will
//            // always have readLine because the GDK supplies it for Reader.
//            ctx.setAttribute("reader", ctx.getReader(), ScriptContext.ENGINE_SCOPE);
        }

        // Fix for GROOVY-3669: Can't use several times the same JSR-223 ScriptContext for differents groovy script
        if (ctx.getWriter() != null) {
            ctx.setAttribute("out", new PrintWriter(ctx.getWriter(), true), ScriptContext.ENGINE_SCOPE);
        }

        /*
         * We use the following Binding instance so that global variable lookup
         * will be done in the current ScriptContext instance.
         */
        Binding binding = new Binding(ctx.getBindings(ScriptContext.ENGINE_SCOPE)) {
            @Override
            public Object getVariable(String name) {
                synchronized (ctx) {
                    int scope = ctx.getAttributesScope(name);
                    if (scope != -1) {
                        return ctx.getAttribute(name, scope);
                    }
                }
                throw new MissingPropertyException(name, getClass());
            }

            @Override
            public void setVariable(String name, Object value) {
                synchronized (ctx) {
                    int scope = ctx.getAttributesScope(name);
                    if (scope == -1) {
                        scope = ScriptContext.ENGINE_SCOPE;
                    }
                    ctx.setAttribute(name, value, scope);
                }
            }
        };

        try {
            // if this class is not an instance of Script, it's a full-blown class
            // then simply return that class
            if (!Script.class.isAssignableFrom(scriptClass)) {
                return scriptClass;
            } else {
                // it's a script
                Script scriptObject = InvokerHelper.createScript(scriptClass, binding);

                // save all current closures into global closures map
                Method[] methods = scriptClass.getMethods();
                for (Method m : methods) {
                    String name = m.getName();
                    globalClosures.put(name, new MethodClosure(scriptObject, name));
                }

                MetaClass oldMetaClass = scriptObject.getMetaClass();

                /*
                * We override the MetaClass of this script object so that we can
                * forward calls to global closures (of previous or future "eval" calls)
                * This gives the illusion of working on the same "global" scope.
                */
                scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) {
                    @Override
                    public Object invokeMethod(Object object, String name, Object args) {
                        if (args == null) {
                            return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY);
                        }
                        if (args instanceof Tuple) {
                            return invokeMethod(object, name, ((Tuple) args).toArray());
                        }
                        if (args instanceof Object[]) {
                            return invokeMethod(object, name, (Object[]) args);
                        } else {
                            return invokeMethod(object, name, new Object[]{args});
                        }
                    }

                    @Override
                    public Object invokeMethod(Object object, String name, Object[] args) {
                        try {
                            return super.invokeMethod(object, name, args);
                        } catch (MissingMethodException mme) {
                            return callGlobal(name, args, ctx);
                        }
                    }

                    @Override
                    public Object invokeStaticMethod(Object object, String name, Object[] args) {
                        try {
                            return super.invokeStaticMethod(object, name, args);
                        } catch (MissingMethodException mme) {
                            return callGlobal(name, args, ctx);
                        }
                    }
                });

                return scriptObject.run();
            }
        } catch (Exception e) {
            throw new ScriptException(e);
        } finally {
            // Fix for GROOVY-3669: Can't use several times the same JSR-223 ScriptContext for different groovy script
            // Groovy's scripting engine implementation adds those two variables in the binding
            // but should clean up afterwards
            ctx.removeAttribute("context", ScriptContext.ENGINE_SCOPE);
            ctx.removeAttribute("out", ScriptContext.ENGINE_SCOPE);
        }
    }
151393
def Scope(value) # rubocop:disable Naming/MethodName
      case value
      when ObjectInspector::Scope
        value
      else
        ObjectInspector::Scope.new(value)
      end
    end
205003
function objectExtendDeep(extended) {
  var currentObject;
  var currentType;
  var extendedType;
  var currentItem;
  var currentTypeInner;

  for (var i = 1, c = arguments.length; i < c; i++) {
    currentObject = arguments[i];
    if (!currentObject)
      continue;
    currentType = type(currentObject);
    extendedType = type(extended);
    // type mismatch
    if (currentType !== extendedType) {
      if (currentType === 'array') {
        extended = [];
      } else if (currentType === 'object' && extendedType !== 'function') {
        extended = {};
      }
      // else copy, primitive, date, regexp, function ...
    }
    // extend arrays
    if (currentType === 'array') {
      extended = extended.concat(currentObject);
    } else {
      // or objects ;)
      for (var key in currentObject) {
        if (ownProperty.call(currentObject, key)) {
          currentTypeInner = type(currentObject[key]);
          currentItem = currentObject[key];
          if (/^(object|array)$/.test(currentTypeInner)) {
            extended[key] = objectExtendDeep(extended[key], currentItem);
          } else if (currentTypeInner === 'date') {
            extended[key] = new Date(currentItem.getTime());
          } else if (currentTypeInner === 'regexp') {
            extended[key] = cloneRegExp(currentItem);
          } else {
            extended[key] = currentItem;
          }
        }
      }
    }
  }
  return extended;
}
154368
public Object eval( String statements, NameSpace nameSpace )
        throws EvalError
    {
        String s = ( statements.endsWith(";") ? statements : statements+";" );
        return eval(
            new StringReader(s), nameSpace,
            "inline evaluation of: ``"+ showEvalString(s)+"''" );
    }
1125654
def evaluate_object(obj, cls=None, cache=False, **kwargs):
        """"""
        old_obj = obj
        if isinstance(obj, Element):
            if cache:
                obj = obj.evaluate_cached(**kwargs)
            else:
                obj = obj.evaluate(cache=cache, **kwargs)

        if cls is not None and type(obj) != cls:
            obj = cls(obj)

        for attr in ('string', 'location', 'tokens'):
            if hasattr(old_obj, attr):
                setattr(obj, attr, getattr(old_obj, attr))

        return obj
659955
function promisify(repl) {
  var _eval = repl.eval;
  repl.eval = function(cmd, context, filename, callback) {
    _eval.call(repl, cmd, context, filename, function(err, res) {
      if (isPromiseLike(res)) {
        res.then(function(ret) {
          callback(null, ret);
        }, function(err) {
          callback(err);
        });
      } else {
        callback(err, res);
      }
    });
  };
  return repl;
}
1007318
function clean(obj) {
  var ret = {};

  // Remove traits/properties that are already represented
  // outside of the data container
  // TODO: Refactor into `omit` call
  var excludeKeys = ['id', 'name', 'firstName', 'lastName'];
  each(excludeKeys, function(omitKey) {
    clear(obj, omitKey);
  });

  // Flatten nested hierarchy, preserving arrays
  obj = flatten(obj);

  // Discard nulls, represent arrays as comma-separated strings
  // FIXME: This also discards `undefined`s. Is that OK?
  for (var key in obj) {
    if (has.call(obj, key)) {
      var val = obj[key];
      if (val == null) {
        continue;
      }

      if (is.array(val)) {
        ret[key] = val.toString();
        continue;
      }

      ret[key] = val;
    }
  }

  return ret;
}
350546
function() {
      var t = this,
          newValue = t.eval_control(t.key, t.depth);

      // Set the new value if it has changed from the current value
      if (!_.isEqual(newValue, t.get('value'))) {
        t.set({value: newValue});
      }
    }
1060748
private void evaluateExpressions() throws JspException {
        /* 
         * Note: we don't check for type mismatches here; we assume
         * the expression evaluator will return the expected type
         * (by virtue of knowledge we give it about what that type is).
         * A ClassCastException here is truly unexpected, so we let it
         * propagate up.
         */

        if (begin_ != null) {
            Object r = ExpressionEvaluatorManager.evaluate(
                    "begin", begin_, Integer.class, this, pageContext);
            if (r == null) {
                throw new NullAttributeException("forEach", "begin");
            }
            begin = ((Integer) r).intValue();
            validateBegin();
        }

        if (end_ != null) {
            Object r = ExpressionEvaluatorManager.evaluate(
                    "end", end_, Integer.class, this, pageContext);
            if (r == null) {
                throw new NullAttributeException("forEach", "end");
            }
            end = ((Integer) r).intValue();
            validateEnd();
        }

        if (step_ != null) {
            Object r = ExpressionEvaluatorManager.evaluate(
                    "step", step_, Integer.class, this, pageContext);
            if (r == null) {
                throw new NullAttributeException("forEach", "step");
            }
            step = ((Integer) r).intValue();
            validateStep();
        }

        if (items_ != null) {
            rawItems = ExpressionEvaluatorManager.evaluate(
                    "items", items_, Object.class, this, pageContext);
            // use an empty list to indicate "no iteration", if relevant
            if (rawItems == null) {
                rawItems = new ArrayList();
            }
        }
    }
754714
public Object eval(Bindings bindings) throws ScriptException {
        if (this.compiledScript == null) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("No compiled script available, invoking ScriptEngine.eval(String, Bindings) for script:\n" + this.script);
            }

            return this.scriptEngine.eval(this.script, bindings);
        }

        try {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Compiled script available, invoking CompiledScript.eval(Bindings) for script:\n" + this.script);
            }

            return evalCompiledScriptWithBindingsMethod.invoke(this.compiledScript, bindings);
        }
        catch (Exception e) {
            if (e instanceof ScriptException) {
                throw (ScriptException)e;
            }
            
            throw new ScriptException(e);
        }
    }
1352559
private Object evalSource(Object source, ScriptContext scriptContext) throws ScriptException {
        try {
            Interpreter bsh = getInterpreter();
            NameSpace contextNameSpace = getEngineNameSpace(scriptContext);
            bsh.setNameSpace(contextNameSpace);

            bsh.setOut(toPrintStream(scriptContext.getWriter()));
            bsh.setErr(toPrintStream(scriptContext.getErrorWriter()));


            if (source instanceof Reader) {
                return bsh.eval((Reader) source);
            } else {
                return bsh.eval((String) source);
            }
        } catch (ParseException e) {
            // explicit parsing error
            throw new ScriptException(e.toString(), e.getErrorSourceFile(), e.getErrorLineNumber());
        } catch (TargetError e) {
            // The script threw an application level exception
            ScriptException se = new ScriptException(e.toString(), e.getErrorSourceFile(), e.getErrorLineNumber());
            se.initCause(e.getTarget());
            throw se;
        } catch (EvalError e) {
            // The script couldn't be evaluated properly
            throw new ScriptException(e.toString(), e.getErrorSourceFile(), e.getErrorLineNumber());
        } catch (IOException e) {
            throw new ScriptException(e.toString());
        }
    }
208629
function init() {
        CodeMirror.defineExtension("foldCode", function (pos, options, force) {
            return doFold(this, pos, options, force);
        });

        CodeMirror.defineExtension("unfoldCode", function (pos, options) {
            return doFold(this, pos, options, "unfold");
        });

        CodeMirror.defineExtension("isFolded", function (line) {
            return this._lineFolds && this._lineFolds[line];
        });

        /**
          * Checks the validity of the ranges passed in the parameter and returns the foldranges
          * that are still valid in the current document
          * @param {object} folds the dictionary of lines in the current document that should be folded
          * @returns {object} valid folds found in those passed in parameter
          */
        CodeMirror.defineExtension("getValidFolds", function (folds) {
            var keys, rf = CodeMirror.fold.auto, cm = this, result = {}, range, cachedRange;
            if (folds && (keys = Object.keys(folds)).length) {
                keys.forEach(function (lineNumber) {
                    lineNumber = +lineNumber;
                    if (lineNumber >= cm.firstLine() && lineNumber <= cm.lastLine()) {
                        range = rf(cm, CodeMirror.Pos(lineNumber, 0));
                        cachedRange = folds[lineNumber];
                        if (range && cachedRange && range.from.line === cachedRange.from.line &&
                                range.to.line === cachedRange.to.line) {
                            result[lineNumber] = folds[lineNumber];
                        }
                    }
                });
            }
            return result;
        });

        /**
          * Utility function to fold the region at the current cursor position in  a document
          * @param {CodeMirror} cm the CodeMirror instance
          * @param {?options} options extra options to pass to the fold function
          */
        CodeMirror.commands.fold = function (cm, options) {
            cm.foldCode(cm.getCursor(), options, "fold");
        };

        /**
          * Utility function to unfold the region at the current cursor position in  a document
          * @param {CodeMirror} cm the CodeMirror instance
          * @param {?options} options extra options to pass to the fold function
          */
        CodeMirror.commands.unfold = function (cm, options) {
            cm.foldCode(cm.getCursor(), options, "unfold");
        };

        /**
          * Utility function to fold all foldable regions in a document
          * @param {CodeMirror} cm the CodeMirror instance
          */
        CodeMirror.commands.foldAll = function (cm) {
            cm.operation(function () {
                var i, e;
                for (i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) {
                    cm.foldCode(CodeMirror.Pos(i, 0), null, "fold");
                }
            });
        };

        /**
          * Utility function to unfold all folded regions in a document
          * @param {CodeMirror} cm the CodeMirror instance
          * @param {?number} from the line number for the beginning of the region to unfold
          * @param {?number} to the line number for the end of the region to unfold
          */
        CodeMirror.commands.unfoldAll = function (cm, from, to) {
            from = from || cm.firstLine();
            to = to || cm.lastLine();
            cm.operation(function () {
                var i, e;
                for (i = from, e = to; i <= e; i++) {
                    if (cm.isFolded(i)) { cm.unfoldCode(i, {range: cm._lineFolds[i]}); }
                }
            });
        };

        /**
          * Folds the specified range. The descendants of any fold regions within the range are also folded up to
          * a level set globally in the `maxFoldLevel' preferences
          * @param {CodeMirror} cm the CodeMirror instance
          * @param {?number} start the line number for the beginning of the region to fold
          * @param {?number} end the line number for the end of the region to fold
          */
        CodeMirror.commands.foldToLevel = function (cm, start, end) {
            var rf = CodeMirror.fold.auto;
            function foldLevel(n, from, to) {
                if (n > 0) {
                    var i = from, range;
                    while (i < to) {
                        range = rf(cm, CodeMirror.Pos(i, 0));
                        if (range) {
                            //call fold level for the range just folded
                            foldLevel(n - 1, range.from.line + 1, range.to.line - 1);
                            cm.foldCode(CodeMirror.Pos(i, 0), null, "fold");
                            i = range.to.line + 1;
                        } else {
                            i++;
                        }
                    }
                }
            }
            cm.operation(function () {
                start = start === undefined ? cm.firstLine() : start;
                end = end || cm.lastLine();
                foldLevel(prefs.getSetting("maxFoldLevel"), start, end);
            });
        };

        /**
          * Helper to combine an array of fold range finders into one. This goes through the
          * list of fold helpers in the parameter arguments and returns the first non-null
          * range found from calling the fold helpers in order.
          */
        CodeMirror.registerHelper("fold", "combine", function () {
            var funcs = Array.prototype.slice.call(arguments, 0);
            return function (cm, start) {
                var i;
                for (i = 0; i < funcs.length; ++i) {
                    var found = funcs[i] && funcs[i](cm, start);
                    if (found) {
                        return found;
                    }
                }
            };
        });

        /**
          * Creates a helper which returns the appropriate fold function based on the mode of the current position in
          * a document.
          * @param {CodeMirror} cm the CodeMirror instance
          * @param {number} start the current position in the document
          */
        CodeMirror.registerHelper("fold", "auto", function (cm, start) {
            var helpers = cm.getHelpers(start, "fold"), i, range;
            //ensure mode helper is loaded if there is one
            var mode = cm.getMode().name;
            var modeHelper = CodeMirror.fold[mode];
            if (modeHelper && helpers.indexOf(modeHelper) < 0) {
                helpers.push(modeHelper);
            }
            for (i = 0; i < helpers.length; i++) {
                range = helpers[i](cm, start);
                if (range && range.to.line - range.from.line >= prefs.getSetting("minFoldSize")) { return range; }
            }
        });
    }
579745
private Node tryFoldInstanceof(Node n, Node left, Node right) {
    checkArgument(n.isInstanceOf());

    // TODO(johnlenz) Use type information if available to fold
    // instanceof.
    if (NodeUtil.isLiteralValue(left, true)
        && !mayHaveSideEffects(right)) {

      Node replacementNode = null;

      if (NodeUtil.isImmutableValue(left)) {
        // Non-object types are never instances.
        replacementNode = IR.falseNode();
      } else if (right.isName()
          && "Object".equals(right.getString())) {
        replacementNode = IR.trueNode();
      }

      if (replacementNode != null) {
        n.replaceWith(replacementNode);
        reportChangeToEnclosingScope(replacementNode);
        markFunctionsDeleted(n);
        return replacementNode;
      }
    }

    return n;
  }
845346
@Override
    public Object eval(Reader reader, ScriptContext context) throws ScriptException {
	try {
	    return eval(IOUtil.toString(reader), context);
	}
	catch (IOException ioe) {
	    throw toScriptException(ioe);
	}
    }
1289121
public Object eval(
        Reader in, NameSpace nameSpace, String sourceFileInfo
            /*, CallStack callstack */ )
        throws EvalError
    {
        Object retVal = null;
        Interpreter.debug("eval: nameSpace = ", nameSpace);

        /*
            Create non-interactive local interpreter for this namespace
            with source from the input stream and out/err same as
            this interpreter.
        */
        Interpreter localInterpreter = new Interpreter(
            in, getOut(), getErr(), false, nameSpace, this, sourceFileInfo  );
        CallStack callstack = new CallStack( nameSpace );

        SimpleNode node = null;
        boolean eof = false;
        while( !eof )
        {
            try
            {
                eof = localInterpreter.readLine();
                if (localInterpreter.get_jjtree().nodeArity() > 0)
                {
                    node = (SimpleNode)localInterpreter.get_jjtree().rootNode();
                    // nodes remember from where they were sourced
                    node.setSourceFile( sourceFileInfo );

                    if ( TRACE )
                        println( "// " +node.getText() );

                    retVal = node.eval( callstack, localInterpreter );

                    // sanity check during development
                    if ( callstack.depth() > 1 )
                        throw new InterpreterError(
                            "Callstack growing: "+callstack);

                    if ( retVal instanceof ReturnControl ) {
                        retVal = ((ReturnControl)retVal).value;
                        break; // non-interactive, return control now
                    }
                }
            } catch(ParseException e) {
                if ( DEBUG.get() )
                    // show extra "expecting..." info
                    error( e.getMessage(DEBUG.get()) );

                // add the source file info and throw again
                e.setErrorSourceFile( sourceFileInfo );
                throw e;
            } catch ( InterpreterError e ) {
                throw new EvalError(
                    "Sourced file: "+sourceFileInfo+" internal Error: "
                    + e.getMessage(), node, callstack, e);
            } catch ( TargetError e ) {
                // failsafe, set the Line as the origin of the error.
                if ( e.getNode()==null )
                    e.setNode( node );
                e.reThrow("Sourced file: "+sourceFileInfo);
            } catch ( EvalError e) {
                if ( DEBUG.get())
                    e.printStackTrace();
                // failsafe, set the Line as the origin of the error.
                if ( e.getNode()==null )
                    e.setNode( node );
                e.reThrow( "Sourced file: "+sourceFileInfo );
            } catch ( Exception e) {
                if ( DEBUG.get())
                    e.printStackTrace();
                throw new EvalError(
                    "Sourced file: "+sourceFileInfo+" unknown error: "
                    + e.getMessage(), node, callstack, e);
            } finally {
                localInterpreter.get_jjtree().reset();

                // reinit the callstack
                if ( callstack.depth() > 1 ) {
                    callstack.clear();
                    callstack.push( nameSpace );
                }
            }
        }
        return Primitive.unwrap( retVal );
    }