<commit_before>/*                     __                                               *\
**     ________ ___   / /  ___      __ ____  Scala.js sbt plugin        **
**    / __/ __// _ | / /  / _ | __ / // __/  (c) 2013, LAMP/EPFL        **
**  __\ \/ /__/ __ |/ /__/ __ |/_// /_\ \    http://scala-js.org/       **
** /____/\___/_/ |_/____/_/ | |__/ /____/                               **
**                          |/____/                                     **
\*                                                                      */


package scala.scalajs.sbtplugin.env.rhino

import scala.scalajs.tools.sem.Semantics
import scala.scalajs.tools.io._
import scala.scalajs.tools.classpath._
import scala.scalajs.tools.env._
import scala.scalajs.tools.logging._

import scala.io.Source

import org.mozilla.javascript._

class RhinoJSEnv(semantics: Semantics,
    withDOM: Boolean = false) extends JSEnv {

  /** Executes code in an environment where the Scala.js library is set up to
   *  load its classes lazily.
   *
   *  Other .js scripts in the inputs are executed eagerly before the provided
   *  `code` is called.
   */
  def runJS(classpath: CompleteClasspath, code: VirtualJSFile,
      logger: Logger, console: JSConsole): Unit = {

    val context = Context.enter()
    try {
      val scope = context.initStandardObjects()

      if (withDOM) {
        // Fetch env.rhino.js from webjar
        val name = "env.rhino.js"
        val path = "/META-INF/resources/webjars/envjs/1.2/" + name
        val resource = getClass.getResource(path)
        assert(resource != null, s"need $name as resource")

        // Rhino can't optimize envjs
        context.setOptimizationLevel(-1)

        // Don't print envjs header
        scope.addFunction("print", args => ())

        // Pipe file to Rhino
        val reader = Source.fromURL(resource).bufferedReader
        context.evaluateReader(scope, reader, name, 1, null);

        // No need to actually define print here: It is captured by envjs to
        // implement console.log, which we'll override in the next statement
      }

      // Make sure Rhino does not do its magic for JVM top-level packages (#364)
      for (name <- Seq("java", "scala", "com", "org"))
        ScriptableObject.putProperty(scope, name, Undefined.instance)

      // Setup console.log
      val jsconsole = context.newObject(scope)
      jsconsole.addFunction("log", _.foreach(console.log _))
      ScriptableObject.putProperty(scope, "console", jsconsole)

      try {
        // Make the classpath available. Either through lazy loading or by
        // simply inserting
        classpath match {
          case cp: IRClasspath =>
            // Setup lazy loading classpath and source mapper
            val optLoader = if (cp.scalaJSIR.nonEmpty) {
              val loader = new ScalaJSCoreLib(semantics, cp)

              // Setup sourceMapper
              val scalaJSenv = context.newObject(scope)
<commit_msg>Fix #364 for good: remove magical Rhino top-level package objects.<commit_after>/*                     __                                               *\
**     ________ ___   / /  ___      __ ____  Scala.js sbt plugin        **
**    / __/ __// _ | / /  / _ | __ / // __/  (c) 2013, LAMP/EPFL        **
**  __\ \/ /__/ __ |/ /__/ __ |/_// /_\ \    http://scala-js.org/       **
** /____/\___/_/ |_/____/_/ | |__/ /____/                               **
**                          |/____/                                     **
\*                                                                      */


package scala.scalajs.sbtplugin.env.rhino

import scala.scalajs.tools.sem.Semantics
import scala.scalajs.tools.io._
import scala.scalajs.tools.classpath._
import scala.scalajs.tools.env._
import scala.scalajs.tools.logging._

import scala.io.Source

import org.mozilla.javascript._

class RhinoJSEnv(semantics: Semantics,
    withDOM: Boolean = false) extends JSEnv {

  /** Executes code in an environment where the Scala.js library is set up to
   *  load its classes lazily.
   *
   *  Other .js scripts in the inputs are executed eagerly before the provided
   *  `code` is called.
   */
  def runJS(classpath: CompleteClasspath, code: VirtualJSFile,
      logger: Logger, console: JSConsole): Unit = {

    val context = Context.enter()
    try {
      val scope = context.initStandardObjects()

      if (withDOM) {
        // Fetch env.rhino.js from webjar
        val name = "env.rhino.js"
        val path = "/META-INF/resources/webjars/envjs/1.2/" + name
        val resource = getClass.getResource(path)
        assert(resource != null, s"need $name as resource")

        // Rhino can't optimize envjs
        context.setOptimizationLevel(-1)

        // Don't print envjs header
        scope.addFunction("print", args => ())

        // Pipe file to Rhino
        val reader = Source.fromURL(resource).bufferedReader
        context.evaluateReader(scope, reader, name, 1, null);

        // No need to actually define print here: It is captured by envjs to
        // implement console.log, which we'll override in the next statement
      }

      // Make sure Rhino does not do its magic for JVM top-level packages (#364)
      val PackagesObject =
        ScriptableObject.getProperty(scope, "Packages").asInstanceOf[Scriptable]
      val topLevelPackageIds = ScriptableObject.getPropertyIds(PackagesObject)
      for (id <- topLevelPackageIds) (id: Any) match {
        case name: String => ScriptableObject.deleteProperty(scope, name)
        case index: Int   => ScriptableObject.deleteProperty(scope, index)
        case _            => // should not happen, I think, but with Rhino you never know
      }

      // Setup console.log
      val jsconsole = context.newObject(scope)
      jsconsole.addFunction("log", _.foreach(console.log _))
      ScriptableObject.putProperty(scope, "console", jsconsole)

      try {
        // Make the classpath available. Either through lazy loading or by
        // simply inserting
        classpath match {
          case cp: IRClasspath =>
            // Setup lazy loading classpath and source mapper
            val optLoader = if (cp.scalaJSIR.nonEmpty) {
              val loader = new ScalaJSCoreLib(semantics, cp)

              // Setup sourceMapper
              val scalaJSenv = context.newObject(scope)

{'fraction_non_alphanumeric': 0.1055284296739644, 'fraction_numerical': 0.0039376279729091196, 'mean_word_length': 1.8360875390799465, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4942738', 'n_tokens_mistral': 1858, 'n_tokens_neox': 1768, 'n_words': 473}